59
79
from bzrlib.merge import merge_inner
60
80
import bzrlib.merge3
62
import bzrlib.osutils as osutils
63
81
import bzrlib.plugin
64
import bzrlib.progress as progress
65
from bzrlib.revision import common_ancestor
82
from bzrlib.smart import client, request, server
66
83
import bzrlib.store
84
from bzrlib import symbol_versioning
85
from bzrlib.symbol_versioning import (
67
91
import bzrlib.trace
68
92
from bzrlib.transport import get_transport
69
93
import bzrlib.transport
70
from bzrlib.transport.local import LocalRelpathServer
94
from bzrlib.transport.local import LocalURLServer
95
from bzrlib.transport.memory import MemoryServer
71
96
from bzrlib.transport.readonly import ReadonlyServer
72
from bzrlib.trace import mutter
97
from bzrlib.trace import mutter, note
73
98
from bzrlib.tests import TestUtil
99
from bzrlib.tests.http_server import HttpServer
74
100
from bzrlib.tests.TestUtil import (
78
104
from bzrlib.tests.treeshape import build_tree_contents
79
import bzrlib.urlutils as urlutils
105
import bzrlib.version_info_formats.format_custom
80
106
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
82
default_transport = LocalRelpathServer
85
MODULES_TO_DOCTEST = [
87
bzrlib.bundle.serializer,
100
def packages_to_test():
101
"""Return a list of packages to test.
103
The packages are not globally imported so that import failures are
104
triggered when running selftest, not when importing the command.
107
import bzrlib.tests.blackbox
108
import bzrlib.tests.branch_implementations
109
import bzrlib.tests.bzrdir_implementations
110
import bzrlib.tests.interrepository_implementations
111
import bzrlib.tests.interversionedfile_implementations
112
import bzrlib.tests.intertree_implementations
113
import bzrlib.tests.repository_implementations
114
import bzrlib.tests.revisionstore_implementations
115
import bzrlib.tests.tree_implementations
116
import bzrlib.tests.workingtree_implementations
119
bzrlib.tests.blackbox,
120
bzrlib.tests.branch_implementations,
121
bzrlib.tests.bzrdir_implementations,
122
bzrlib.tests.interrepository_implementations,
123
bzrlib.tests.interversionedfile_implementations,
124
bzrlib.tests.intertree_implementations,
125
bzrlib.tests.repository_implementations,
126
bzrlib.tests.revisionstore_implementations,
127
bzrlib.tests.tree_implementations,
128
bzrlib.tests.workingtree_implementations,
132
class _MyResult(unittest._TextTestResult):
133
"""Custom TestResult.
135
Shows output in a different format, including displaying runtime for tests.
108
# Mark this python module as being part of the implementation
109
# of unittest: this gives us better tracebacks where the last
110
# shown frame is the test code, not our assertXYZ.
113
default_transport = LocalURLServer
116
class ExtendedTestResult(unittest._TextTestResult):
117
"""Accepts, reports and accumulates the results of running tests.
119
Compared to the unittest version this class adds support for
120
profiling, benchmarking, stopping as soon as a test fails, and
121
skipping tests. There are further-specialized subclasses for
122
different types of display.
124
When a test finishes, in whatever way, it calls one of the addSuccess,
125
addFailure or addError classes. These in turn may redirect to a more
126
specific case for the special test results supported by our extended
129
Note that just one of these objects is fed the results from many tests.
137
132
stop_early = False
139
def __init__(self, stream, descriptions, verbosity, pb=None):
134
def __init__(self, stream, descriptions, verbosity,
139
"""Construct new TestResult.
141
:param bench_history: Optionally, a writable file object to accumulate
140
144
unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
143
def extractBenchmarkTime(self, testCase):
145
if bench_history is not None:
146
from bzrlib.version import _get_bzr_source_tree
147
src_tree = _get_bzr_source_tree()
150
revision_id = src_tree.get_parent_ids()[0]
152
# XXX: if this is a brand new tree, do the same as if there
156
# XXX: If there's no branch, what should we do?
158
bench_history.write("--date %s %s\n" % (time.time(), revision_id))
159
self._bench_history = bench_history
160
self.ui = ui.ui_factory
161
self.num_tests = num_tests
163
self.failure_count = 0
164
self.known_failure_count = 0
166
self.not_applicable_count = 0
167
self.unsupported = {}
169
self._overall_start_time = time.time()
170
self._strict = strict
174
ok = self.wasStrictlySuccessful()
176
ok = self.wasSuccessful()
178
self.stream.write('tests passed\n')
180
self.stream.write('tests failed\n')
181
if TestCase._first_thread_leaker_id:
183
'%s is leaking threads among %d leaking tests.\n' % (
184
TestCase._first_thread_leaker_id,
185
TestCase._leaking_threads_tests))
187
def _extractBenchmarkTime(self, testCase):
144
188
"""Add a benchmark time for the current test case."""
145
self._benchmarkTime = getattr(testCase, "_benchtime", None)
189
return getattr(testCase, "_benchtime", None)
147
191
def _elapsedTestTimeString(self):
148
192
"""Return a time string for the overall time the current test has taken."""
149
193
return self._formatTime(time.time() - self._start_time)
151
def _testTimeString(self):
152
if self._benchmarkTime is not None:
195
def _testTimeString(self, testCase):
196
benchmark_time = self._extractBenchmarkTime(testCase)
197
if benchmark_time is not None:
153
198
return "%s/%s" % (
154
self._formatTime(self._benchmarkTime),
199
self._formatTime(benchmark_time),
155
200
self._elapsedTestTimeString())
157
return " %s" % self._elapsedTestTimeString()
202
return " %s" % self._elapsedTestTimeString()
159
204
def _formatTime(self, seconds):
160
205
"""Format seconds as milliseconds with leading spaces."""
161
return "%5dms" % (1000 * seconds)
206
# some benchmarks can take thousands of seconds to run, so we need 8
208
return "%8dms" % (1000 * seconds)
163
def _ellipsise_unimportant_words(self, a_string, final_width,
165
"""Add ellipses (sp?) for overly long strings.
167
:param keep_start: If true preserve the start of a_string rather
171
if len(a_string) > final_width:
172
result = a_string[:final_width-3] + '...'
176
if len(a_string) > final_width:
177
result = '...' + a_string[3-final_width:]
180
return result.ljust(final_width)
210
def _shortened_test_description(self, test):
212
what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
182
215
def startTest(self, test):
183
216
unittest.TestResult.startTest(self, test)
184
# In a short description, the important words are in
185
# the beginning, but in an id, the important words are
187
SHOW_DESCRIPTIONS = False
189
if not self.showAll and self.dots and self.pb is not None:
192
final_width = osutils.terminal_width()
193
final_width = final_width - 15 - 8
195
if SHOW_DESCRIPTIONS:
196
what = test.shortDescription()
198
what = self._ellipsise_unimportant_words(what, final_width, keep_start=True)
201
if what.startswith('bzrlib.tests.'):
203
what = self._ellipsise_unimportant_words(what, final_width)
205
self.stream.write(what)
206
elif self.dots and self.pb is not None:
207
self.pb.update(what, self.testsRun - 1, None)
219
self.report_test_start(test)
220
test.number = self.count
209
221
self._recordTestStartTime()
223
def startTests(self):
225
'testing: %s\n' % (osutils.realpath(sys.argv[0]),))
227
' %s (%s python%s)\n' % (
229
bzrlib.version_string,
230
bzrlib._format_version_tuple(sys.version_info),
232
self.stream.write('\n')
211
234
def _recordTestStartTime(self):
212
235
"""Record that a test has started."""
213
236
self._start_time = time.time()
238
def _cleanupLogFile(self, test):
239
# We can only do this if we have one of our TestCases, not if
241
setKeepLogfile = getattr(test, 'setKeepLogfile', None)
242
if setKeepLogfile is not None:
215
245
def addError(self, test, err):
216
if isinstance(err[1], TestSkipped):
217
return self.addSkipped(test, err)
218
unittest.TestResult.addError(self, test, err)
219
self.extractBenchmarkTime(test)
221
self.stream.writeln("ERROR %s" % self._testTimeString())
222
elif self.dots and self.pb is None:
223
self.stream.write('E')
225
self.pb.update(self._ellipsise_unimportant_words('ERROR', 13), self.testsRun, None)
226
self.pb.note(self._ellipsise_unimportant_words(
227
test.id() + ': ERROR',
228
osutils.terminal_width()))
246
"""Tell result that test finished with an error.
248
Called from the TestCase run() method when the test
249
fails with an unexpected error.
251
self._testConcluded(test)
252
if isinstance(err[1], TestNotApplicable):
253
return self._addNotApplicable(test, err)
254
elif isinstance(err[1], UnavailableFeature):
255
return self.addNotSupported(test, err[1].args[0])
257
unittest.TestResult.addError(self, test, err)
258
self.error_count += 1
259
self.report_error(test, err)
262
self._cleanupLogFile(test)
233
264
def addFailure(self, test, err):
234
unittest.TestResult.addFailure(self, test, err)
235
self.extractBenchmarkTime(test)
237
self.stream.writeln(" FAIL %s" % self._testTimeString())
238
elif self.dots and self.pb is None:
239
self.stream.write('F')
241
self.pb.update(self._ellipsise_unimportant_words('FAIL', 13), self.testsRun, None)
242
self.pb.note(self._ellipsise_unimportant_words(
243
test.id() + ': FAIL',
244
osutils.terminal_width()))
265
"""Tell result that test failed.
267
Called from the TestCase run() method when the test
268
fails because e.g. an assert() method failed.
270
self._testConcluded(test)
271
if isinstance(err[1], KnownFailure):
272
return self._addKnownFailure(test, err)
274
unittest.TestResult.addFailure(self, test, err)
275
self.failure_count += 1
276
self.report_failure(test, err)
279
self._cleanupLogFile(test)
249
281
def addSuccess(self, test):
250
self.extractBenchmarkTime(test)
252
self.stream.writeln(' OK %s' % self._testTimeString())
253
for bench_called, stats in getattr(test, '_benchcalls', []):
254
self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
255
stats.pprint(file=self.stream)
256
elif self.dots and self.pb is None:
257
self.stream.write('~')
259
self.pb.update(self._ellipsise_unimportant_words('OK', 13), self.testsRun, None)
282
"""Tell result that test completed successfully.
284
Called from the TestCase run()
286
self._testConcluded(test)
287
if self._bench_history is not None:
288
benchmark_time = self._extractBenchmarkTime(test)
289
if benchmark_time is not None:
290
self._bench_history.write("%s %s\n" % (
291
self._formatTime(benchmark_time),
293
self.report_success(test)
294
self._cleanupLogFile(test)
261
295
unittest.TestResult.addSuccess(self, test)
263
def addSkipped(self, test, skip_excinfo):
264
self.extractBenchmarkTime(test)
266
print >>self.stream, ' SKIP %s' % self._testTimeString()
267
print >>self.stream, ' %s' % skip_excinfo[1]
268
elif self.dots and self.pb is None:
269
self.stream.write('S')
271
self.pb.update(self._ellipsise_unimportant_words('SKIP', 13), self.testsRun, None)
273
# seems best to treat this as success from point-of-view of unittest
274
# -- it actually does nothing so it barely matters :)
296
test._log_contents = ''
298
def _testConcluded(self, test):
299
"""Common code when a test has finished.
301
Called regardless of whether it succeded, failed, etc.
305
def _addKnownFailure(self, test, err):
306
self.known_failure_count += 1
307
self.report_known_failure(test, err)
309
def addNotSupported(self, test, feature):
310
"""The test will not be run because of a missing feature.
312
# this can be called in two different ways: it may be that the
313
# test started running, and then raised (through addError)
314
# UnavailableFeature. Alternatively this method can be called
315
# while probing for features before running the tests; in that
316
# case we will see startTest and stopTest, but the test will never
318
self.unsupported.setdefault(str(feature), 0)
319
self.unsupported[str(feature)] += 1
320
self.report_unsupported(test, feature)
322
def addSkip(self, test, reason):
323
"""A test has not run for 'reason'."""
325
self.report_skip(test, reason)
327
def _addNotApplicable(self, test, skip_excinfo):
328
if isinstance(skip_excinfo[1], TestNotApplicable):
329
self.not_applicable_count += 1
330
self.report_not_applicable(test, skip_excinfo)
277
333
except KeyboardInterrupt:
280
self.addError(test, test.__exc_info())
336
self.addError(test, test.exc_info())
338
# seems best to treat this as success from point-of-view of unittest
339
# -- it actually does nothing so it barely matters :)
282
340
unittest.TestResult.addSuccess(self, test)
341
test._log_contents = ''
284
343
def printErrorList(self, flavour, errors):
285
344
for test, err in errors:
286
345
self.stream.writeln(self.separator1)
287
self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
346
self.stream.write("%s: " % flavour)
347
self.stream.writeln(self.getDescription(test))
288
348
if getattr(test, '_get_log', None) is not None:
290
print >>self.stream, \
291
('vvvv[log from %s]' % test.id()).ljust(78,'-')
292
print >>self.stream, test._get_log()
293
print >>self.stream, \
294
('^^^^[log from %s]' % test.id()).ljust(78,'-')
349
self.stream.write('\n')
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')
356
('^^^^[log from %s]' % test.id()).ljust(78,'-'))
357
self.stream.write('\n')
295
358
self.stream.writeln(self.separator2)
296
359
self.stream.writeln("%s" % err)
364
def report_cleaning_up(self):
367
def report_success(self, test):
370
def wasStrictlySuccessful(self):
371
if self.unsupported or self.known_failure_count:
373
return self.wasSuccessful()
376
class TextTestResult(ExtendedTestResult):
377
"""Displays progress and results of tests in text form"""
379
def __init__(self, stream, descriptions, verbosity,
385
ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
386
bench_history, num_tests, strict)
388
self.pb = self.ui.nested_progress_bar()
389
self._supplied_pb = False
392
self._supplied_pb = True
393
self.pb.show_pct = False
394
self.pb.show_spinner = False
395
self.pb.show_eta = False,
396
self.pb.show_count = False
397
self.pb.show_bar = False
399
def report_starting(self):
400
self.pb.update('[test 0/%d] Starting' % (self.num_tests))
402
def _progress_prefix_text(self):
403
# the longer this text, the less space we have to show the test
405
a = '[%d' % self.count # total that have been run
406
# tests skipped as known not to be relevant are not important enough
408
## if self.skip_count:
409
## a += ', %d skip' % self.skip_count
410
## if self.known_failure_count:
411
## a += '+%dX' % self.known_failure_count
412
if self.num_tests is not None:
413
a +='/%d' % self.num_tests
415
runtime = time.time() - self._overall_start_time
417
a += '%dm%ds' % (runtime / 60, runtime % 60)
421
a += ', %d err' % self.error_count
422
if self.failure_count:
423
a += ', %d fail' % self.failure_count
425
a += ', %d missing' % len(self.unsupported)
429
def report_test_start(self, test):
432
self._progress_prefix_text()
434
+ self._shortened_test_description(test))
436
def _test_description(self, test):
437
return self._shortened_test_description(test)
439
def report_error(self, test, err):
440
self.pb.note('ERROR: %s\n %s\n',
441
self._test_description(test),
445
def report_failure(self, test, err):
446
self.pb.note('FAIL: %s\n %s\n',
447
self._test_description(test),
451
def report_known_failure(self, test, err):
452
self.pb.note('XFAIL: %s\n%s\n',
453
self._test_description(test), err[1])
455
def report_skip(self, test, reason):
458
def report_not_applicable(self, test, skip_excinfo):
461
def report_unsupported(self, test, feature):
462
"""test cannot be run because feature is missing."""
464
def report_cleaning_up(self):
465
self.pb.update('Cleaning up')
468
if not self._supplied_pb:
472
class VerboseTestResult(ExtendedTestResult):
473
"""Produce long output, with one line per test run plus times"""
475
def _ellipsize_to_right(self, a_string, final_width):
476
"""Truncate and pad a string, keeping the right hand side"""
477
if len(a_string) > final_width:
478
result = '...' + a_string[3-final_width:]
481
return result.ljust(final_width)
483
def report_starting(self):
484
self.stream.write('running %d tests...\n' % self.num_tests)
486
def report_test_start(self, test):
488
name = self._shortened_test_description(test)
489
# width needs space for 6 char status, plus 1 for slash, plus 2 10-char
490
# numbers, plus a trailing blank
491
# when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on space
492
self.stream.write(self._ellipsize_to_right(name,
493
osutils.terminal_width()-30))
496
def _error_summary(self, err):
498
return '%s%s' % (indent, err[1])
500
def report_error(self, test, err):
501
self.stream.writeln('ERROR %s\n%s'
502
% (self._testTimeString(test),
503
self._error_summary(err)))
505
def report_failure(self, test, err):
506
self.stream.writeln(' FAIL %s\n%s'
507
% (self._testTimeString(test),
508
self._error_summary(err)))
510
def report_known_failure(self, test, err):
511
self.stream.writeln('XFAIL %s\n%s'
512
% (self._testTimeString(test),
513
self._error_summary(err)))
515
def report_success(self, test):
516
self.stream.writeln(' OK %s' % self._testTimeString(test))
517
for bench_called, stats in getattr(test, '_benchcalls', []):
518
self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
519
stats.pprint(file=self.stream)
520
# flush the stream so that we get smooth output. This verbose mode is
521
# used to show the output in PQM.
524
def report_skip(self, test, reason):
525
self.stream.writeln(' SKIP %s\n%s'
526
% (self._testTimeString(test), reason))
528
def report_not_applicable(self, test, skip_excinfo):
529
self.stream.writeln(' N/A %s\n%s'
530
% (self._testTimeString(test),
531
self._error_summary(skip_excinfo)))
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."
536
%(self._testTimeString(test), feature))
299
539
class TextTestRunner(object):
300
540
stop_on_failure = False
552
1099
self.fail("%r is an instance of %s rather than %s" % (
553
1100
obj, obj.__class__, kls))
1102
def expectFailure(self, reason, assertion, *args, **kwargs):
1103
"""Invoke a test, expecting it to fail for the given reason.
1105
This is for assertions that ought to succeed, but currently fail.
1106
(The failure is *expected* but not *wanted*.) Please be very precise
1107
about the failure you're expecting. If a new bug is introduced,
1108
AssertionError should be raised, not KnownFailure.
1110
Frequently, expectFailure should be followed by an opposite assertion.
1113
Intended to be used with a callable that raises AssertionError as the
1114
'assertion' parameter. args and kwargs are passed to the 'assertion'.
1116
Raises KnownFailure if the test fails. Raises AssertionError if the
1121
self.expectFailure('Math is broken', self.assertNotEqual, 54,
1123
self.assertEqual(42, dynamic_val)
1125
This means that a dynamic_val of 54 will cause the test to raise
1126
a KnownFailure. Once math is fixed and the expectFailure is removed,
1127
only a dynamic_val of 42 will allow the test to pass. Anything other
1128
than 54 or 42 will cause an AssertionError.
1131
assertion(*args, **kwargs)
1132
except AssertionError:
1133
raise KnownFailure(reason)
1135
self.fail('Unexpected success. Should have failed: %s' % reason)
1137
def assertFileEqual(self, content, path):
1138
"""Fail if path does not contain 'content'."""
1139
self.failUnlessExists(path)
1140
f = file(path, 'rb')
1145
self.assertEqualDiff(content, s)
1147
def failUnlessExists(self, path):
1148
"""Fail unless path or paths, which may be abs or relative, exist."""
1149
if not isinstance(path, basestring):
1151
self.failUnlessExists(p)
1153
self.failUnless(osutils.lexists(path),path+" does not exist")
1155
def failIfExists(self, path):
1156
"""Fail if path or paths, which may be abs or relative, exist."""
1157
if not isinstance(path, basestring):
1159
self.failIfExists(p)
1161
self.failIf(osutils.lexists(path),path+" exists")
1163
def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1164
"""A helper for callDeprecated and applyDeprecated.
1166
:param a_callable: A callable to call.
1167
:param args: The positional arguments for the callable
1168
:param kwargs: The keyword arguments for the callable
1169
:return: A tuple (warnings, result). result is the result of calling
1170
a_callable(``*args``, ``**kwargs``).
1173
def capture_warnings(msg, cls=None, stacklevel=None):
1174
# we've hooked into a deprecation specific callpath,
1175
# only deprecations should getting sent via it.
1176
self.assertEqual(cls, DeprecationWarning)
1177
local_warnings.append(msg)
1178
original_warning_method = symbol_versioning.warn
1179
symbol_versioning.set_warning_method(capture_warnings)
1181
result = a_callable(*args, **kwargs)
1183
symbol_versioning.set_warning_method(original_warning_method)
1184
return (local_warnings, result)
1186
def applyDeprecated(self, deprecation_format, a_callable, *args, **kwargs):
1187
"""Call a deprecated callable without warning the user.
1189
Note that this only captures warnings raised by symbol_versioning.warn,
1190
not other callers that go direct to the warning module.
1192
To test that a deprecated method raises an error, do something like
1195
self.assertRaises(errors.ReservedId,
1196
self.applyDeprecated,
1197
deprecated_in((1, 5, 0)),
1201
:param deprecation_format: The deprecation format that the callable
1202
should have been deprecated with. This is the same type as the
1203
parameter to deprecated_method/deprecated_function. If the
1204
callable is not deprecated with this format, an assertion error
1206
:param a_callable: A callable to call. This may be a bound method or
1207
a regular function. It will be called with ``*args`` and
1209
:param args: The positional arguments for the callable
1210
:param kwargs: The keyword arguments for the callable
1211
:return: The result of a_callable(``*args``, ``**kwargs``)
1213
call_warnings, result = self._capture_deprecation_warnings(a_callable,
1215
expected_first_warning = symbol_versioning.deprecation_string(
1216
a_callable, deprecation_format)
1217
if len(call_warnings) == 0:
1218
self.fail("No deprecation warning generated by call to %s" %
1220
self.assertEqual(expected_first_warning, call_warnings[0])
1223
def callCatchWarnings(self, fn, *args, **kw):
1224
"""Call a callable that raises python warnings.
1226
The caller's responsible for examining the returned warnings.
1228
If the callable raises an exception, the exception is not
1229
caught and propagates up to the caller. In that case, the list
1230
of warnings is not available.
1232
:returns: ([warning_object, ...], fn_result)
1234
# XXX: This is not perfect, because it completely overrides the
1235
# warnings filters, and some code may depend on suppressing particular
1236
# warnings. It's the easiest way to insulate ourselves from -Werror,
1237
# though. -- Andrew, 20071062
1239
def _catcher(message, category, filename, lineno, file=None, line=None):
1240
# despite the name, 'message' is normally(?) a Warning subclass
1242
wlist.append(message)
1243
saved_showwarning = warnings.showwarning
1244
saved_filters = warnings.filters
1246
warnings.showwarning = _catcher
1247
warnings.filters = []
1248
result = fn(*args, **kw)
1250
warnings.showwarning = saved_showwarning
1251
warnings.filters = saved_filters
1252
return wlist, result
1254
def callDeprecated(self, expected, callable, *args, **kwargs):
1255
"""Assert that a callable is deprecated in a particular way.
1257
This is a very precise test for unusual requirements. The
1258
applyDeprecated helper function is probably more suited for most tests
1259
as it allows you to simply specify the deprecation format being used
1260
and will ensure that that is issued for the function being called.
1262
Note that this only captures warnings raised by symbol_versioning.warn,
1263
not other callers that go direct to the warning module. To catch
1264
general warnings, use callCatchWarnings.
1266
:param expected: a list of the deprecation warnings expected, in order
1267
:param callable: The callable to call
1268
:param args: The positional arguments for the callable
1269
:param kwargs: The keyword arguments for the callable
1271
call_warnings, result = self._capture_deprecation_warnings(callable,
1273
self.assertEqual(expected, call_warnings)
555
1276
def _startLogFile(self):
556
1277
"""Send bzr and test log messages to a temporary file.
558
1279
The file is removed as the test is torn down.
560
1281
fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
561
encoder, decoder, stream_reader, stream_writer = codecs.lookup('UTF-8')
562
self._log_file = stream_writer(os.fdopen(fileno, 'w+'))
563
self._log_nonce = bzrlib.trace.enable_test_log(self._log_file)
1282
self._log_file = os.fdopen(fileno, 'w+')
1283
self._log_memento = bzrlib.trace.push_log_file(self._log_file)
564
1284
self._log_file_name = name
565
1285
self.addCleanup(self._finishLogFile)
567
1287
def _finishLogFile(self):
568
1288
"""Finished with the log file.
570
Read contents into memory, close, and delete.
1290
Close the file and delete it, unless setKeepLogfile was called.
572
1292
if self._log_file is None:
574
bzrlib.trace.disable_test_log(self._log_nonce)
575
self._log_file.seek(0)
576
self._log_contents = self._log_file.read()
1294
bzrlib.trace.pop_log_file(self._log_memento)
577
1295
self._log_file.close()
578
os.remove(self._log_file_name)
579
self._log_file = self._log_file_name = None
581
def addCleanup(self, callable):
1296
self._log_file = None
1297
if not self._keep_log_file:
1298
os.remove(self._log_file_name)
1299
self._log_file_name = None
1301
def setKeepLogfile(self):
1302
"""Make the logfile not be deleted when _finishLogFile is called."""
1303
self._keep_log_file = True
1305
def addCleanup(self, callable, *args, **kwargs):
582
1306
"""Arrange to run a callable when this case is torn down.
584
Callables are run in the reverse of the order they are registered,
1308
Callables are run in the reverse of the order they are registered,
585
1309
ie last-in first-out.
587
if callable in self._cleanups:
588
raise ValueError("cleanup function %r already registered on %s"
590
self._cleanups.append(callable)
1311
self._cleanups.append((callable, args, kwargs))
592
1313
def _cleanEnvironment(self):
1315
'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
594
1316
'HOME': os.getcwd(),
595
'APPDATA': os.getcwd(),
1317
# bzr now uses the Win32 API and doesn't rely on APPDATA, but the
1318
# tests do check our impls match APPDATA
1319
'BZR_EDITOR': None, # test_msgeditor manipulates this variable
596
1322
'BZR_EMAIL': None,
597
1323
'BZREMAIL': None, # may still be present in the environment
1325
'BZR_PROGRESS_BAR': None,
1327
'BZR_PLUGIN_PATH': None,
1329
'SSH_AUTH_SOCK': None,
1333
'https_proxy': None,
1334
'HTTPS_PROXY': None,
1339
# Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
1340
# least. If you do (care), please update this comment
1344
'BZR_REMOTE_PATH': None,
600
1346
self.__old_env = {}
601
1347
self.addCleanup(self._restoreEnvironment)
602
1348
for name, value in new_env.iteritems():
603
1349
self._captureVar(name, value)
606
1351
def _captureVar(self, name, newvalue):
607
"""Set an environment variable, preparing it to be reset when finished."""
608
self.__old_env[name] = os.environ.get(name, None)
610
if name in os.environ:
613
os.environ[name] = newvalue
1352
"""Set an environment variable, and reset it when finished."""
1353
self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
616
def _restoreVar(name, value):
618
if name in os.environ:
621
os.environ[name] = value
1355
def _restore_debug_flags(self):
1356
debug.debug_flags.clear()
1357
debug.debug_flags.update(self._preserved_debug_flags)
623
1359
def _restoreEnvironment(self):
624
1360
for name, value in self.__old_env.iteritems():
625
self._restoreVar(name, value)
1361
osutils.set_or_unset_env(name, value)
1363
def _restoreHooks(self):
1364
for klass, (name, hooks) in self._preserved_hooks.items():
1365
setattr(klass, name, hooks)
1367
def knownFailure(self, reason):
1368
"""This test has failed for some known reason."""
1369
raise KnownFailure(reason)
1371
def _do_skip(self, result, reason):
1372
addSkip = getattr(result, 'addSkip', None)
1373
if not callable(addSkip):
1374
result.addError(self, sys.exc_info())
1376
addSkip(self, reason)
1378
def run(self, result=None):
1379
if result is None: result = self.defaultTestResult()
1380
for feature in getattr(self, '_test_needs_features', []):
1381
if not feature.available():
1382
result.startTest(self)
1383
if getattr(result, 'addNotSupported', None):
1384
result.addNotSupported(self, feature)
1386
result.addSuccess(self)
1387
result.stopTest(self)
1391
result.startTest(self)
1392
absent_attr = object()
1394
method_name = getattr(self, '_testMethodName', absent_attr)
1395
if method_name is absent_attr:
1397
method_name = getattr(self, '_TestCase__testMethodName')
1398
testMethod = getattr(self, method_name)
1402
if not self._bzr_test_setUp_run:
1404
"test setUp did not invoke "
1405
"bzrlib.tests.TestCase's setUp")
1406
except KeyboardInterrupt:
1409
except TestSkipped, e:
1410
self._do_skip(result, e.args[0])
1414
result.addError(self, sys.exc_info())
1422
except self.failureException:
1423
result.addFailure(self, sys.exc_info())
1424
except TestSkipped, e:
1426
reason = "No reason given."
1429
self._do_skip(result, reason)
1430
except KeyboardInterrupt:
1434
result.addError(self, sys.exc_info())
1438
if not self._bzr_test_tearDown_run:
1440
"test tearDown did not invoke "
1441
"bzrlib.tests.TestCase's tearDown")
1442
except KeyboardInterrupt:
1446
result.addError(self, sys.exc_info())
1449
if ok: result.addSuccess(self)
1451
result.stopTest(self)
1453
except TestNotApplicable:
1454
# Not moved from the result [yet].
1457
except KeyboardInterrupt:
1462
for attr_name in self.attrs_to_keep:
1463
if attr_name in self.__dict__:
1464
saved_attrs[attr_name] = self.__dict__[attr_name]
1465
self.__dict__ = saved_attrs
627
1467
def tearDown(self):
628
1468
self._runCleanups()
1469
self._log_contents = ''
1470
self._bzr_test_tearDown_run = True
629
1471
unittest.TestCase.tearDown(self)
631
1473
def time(self, callable, *args, **kwargs):
632
1474
"""Run callable and accrue the time it takes to the benchmark time.
634
1476
If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
635
1477
this will cause lsprofile statistics to be gathered and stored in
636
1478
self._benchcalls.
745
1636
This sends the stdout/stderr results into the test's log,
746
1637
where it may be useful for debugging. See also run_captured.
748
:param stdin: A string to be used as stdin for the command.
1639
:keyword stdin: A string to be used as stdin for the command.
1640
:keyword retcode: The status code the command should return;
1642
:keyword working_dir: The directory to run the command in
1643
:keyword error_regexes: A list of expected error messages. If
1644
specified they must be seen in the error output of the command.
750
retcode = kwargs.pop('retcode', 0)
751
encoding = kwargs.pop('encoding', None)
752
stdin = kwargs.pop('stdin', None)
753
return self.run_bzr_captured(args, retcode=retcode, encoding=encoding, stdin=stdin)
755
def run_bzr_decode(self, *args, **kwargs):
756
if kwargs.has_key('encoding'):
757
encoding = kwargs['encoding']
759
encoding = bzrlib.user_encoding
760
return self.run_bzr(*args, **kwargs)[0].decode(encoding)
1646
out, err = self._run_bzr_autosplit(
1651
working_dir=working_dir,
1653
self.assertIsInstance(error_regexes, (list, tuple))
1654
for regex in error_regexes:
1655
self.assertContainsRe(err, regex)
762
1658
def run_bzr_error(self, error_regexes, *args, **kwargs):
763
1659
"""Run bzr, and check that stderr contains the supplied regexes
765
:param error_regexes: Sequence of regular expressions which
1661
:param error_regexes: Sequence of regular expressions which
766
1662
must each be found in the error output. The relative ordering
767
1663
is not enforced.
768
1664
:param args: command-line arguments for bzr
769
1665
:param kwargs: Keyword arguments which are interpreted by run_bzr
770
1666
This function changes the default value of retcode to be 3,
771
1667
since in most cases this is run when you expect bzr to fail.
772
:return: (out, err) The actual output of running the command (in case you
773
want to do more inspection)
1669
:return: (out, err) The actual output of running the command (in case
1670
you want to do more inspection)
776
1674
# Make sure that commit is failing because there is nothing to do
777
1675
self.run_bzr_error(['no changes to commit'],
778
'commit', '-m', 'my commit comment')
1676
['commit', '-m', 'my commit comment'])
779
1677
# Make sure --strict is handling an unknown file, rather than
780
1678
# giving us the 'nothing to do' error
781
1679
self.build_tree(['unknown'])
782
1680
self.run_bzr_error(['Commit refused because there are unknown files'],
783
'commit', '--strict', '-m', 'my commit comment')
1681
['commit', --strict', '-m', 'my commit comment'])
785
1683
kwargs.setdefault('retcode', 3)
1684
kwargs['error_regexes'] = error_regexes
786
1685
out, err = self.run_bzr(*args, **kwargs)
787
for regex in error_regexes:
788
self.assertContainsRe(err, regex)
791
1688
def run_bzr_subprocess(self, *args, **kwargs):
792
1689
"""Run bzr in a subprocess for testing.
794
This starts a new Python interpreter and runs bzr in there.
795
This should only be used for tests that have a justifiable need for
796
this isolation: e.g. they are testing startup time, or signal
797
handling, or early startup code, etc. Subprocess code can't be
798
profiled or debugged so easily.
1691
This starts a new Python interpreter and runs bzr in there.
1692
This should only be used for tests that have a justifiable need for
1693
this isolation: e.g. they are testing startup time, or signal
1694
handling, or early startup code, etc. Subprocess code can't be
1695
profiled or debugged so easily.
1697
:keyword retcode: The status code that is expected. Defaults to 0. If
1698
None is supplied, the status code is not checked.
1699
:keyword env_changes: A dictionary which lists changes to environment
1700
variables. A value of None will unset the env variable.
1701
The values must be strings. The change will only occur in the
1702
child, so you don't need to fix the environment after running.
1703
:keyword universal_newlines: Convert CRLF => LF
1704
:keyword allow_plugins: By default the subprocess is run with
1705
--no-plugins to ensure test reproducibility. Also, it is possible
1706
for system-wide plugins to create unexpected output on stderr,
1707
which can cause unnecessary test failures.
1709
env_changes = kwargs.get('env_changes', {})
1710
working_dir = kwargs.get('working_dir', None)
1711
allow_plugins = kwargs.get('allow_plugins', False)
1713
if isinstance(args[0], list):
1715
elif isinstance(args[0], basestring):
1716
args = list(shlex.split(args[0]))
1718
raise ValueError("passing varargs to run_bzr_subprocess")
1719
process = self.start_bzr_subprocess(args, env_changes=env_changes,
1720
working_dir=working_dir,
1721
allow_plugins=allow_plugins)
1722
# We distinguish between retcode=None and retcode not passed.
1723
supplied_retcode = kwargs.get('retcode', 0)
1724
return self.finish_bzr_subprocess(process, retcode=supplied_retcode,
1725
universal_newlines=kwargs.get('universal_newlines', False),
1728
def start_bzr_subprocess(self, process_args, env_changes=None,
1729
skip_if_plan_to_signal=False,
1731
allow_plugins=False):
1732
"""Start bzr in a subprocess for testing.
1734
This starts a new Python interpreter and runs bzr in there.
1735
This should only be used for tests that have a justifiable need for
1736
this isolation: e.g. they are testing startup time, or signal
1737
handling, or early startup code, etc. Subprocess code can't be
1738
profiled or debugged so easily.
1740
:param process_args: a list of arguments to pass to the bzr executable,
1741
for example ``['--version']``.
1742
:param env_changes: A dictionary which lists changes to environment
1743
variables. A value of None will unset the env variable.
1744
The values must be strings. The change will only occur in the
1745
child, so you don't need to fix the environment after running.
1746
:param skip_if_plan_to_signal: raise TestSkipped when true and os.kill
1748
:param allow_plugins: If False (default) pass --no-plugins to bzr.
1750
:returns: Popen object for the started process.
1752
if skip_if_plan_to_signal:
1753
if not getattr(os, 'kill', None):
1754
raise TestSkipped("os.kill not available.")
1756
if env_changes is None:
1760
def cleanup_environment():
1761
for env_var, value in env_changes.iteritems():
1762
old_env[env_var] = osutils.set_or_unset_env(env_var, value)
1764
def restore_environment():
1765
for env_var, value in old_env.iteritems():
1766
osutils.set_or_unset_env(env_var, value)
1768
bzr_path = self.get_bzr_path()
1771
if working_dir is not None:
1772
cwd = osutils.getcwd()
1773
os.chdir(working_dir)
1776
# win32 subprocess doesn't support preexec_fn
1777
# so we will avoid using it on all platforms, just to
1778
# make sure the code path is used, and we don't break on win32
1779
cleanup_environment()
1780
command = [sys.executable]
1781
# frozen executables don't need the path to bzr
1782
if getattr(sys, "frozen", None) is None:
1783
command.append(bzr_path)
1784
if not allow_plugins:
1785
command.append('--no-plugins')
1786
command.extend(process_args)
1787
process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
1789
restore_environment()
1795
def _popen(self, *args, **kwargs):
1796
"""Place a call to Popen.
1798
Allows tests to override this method to intercept the calls made to
1799
Popen for introspection.
1801
return Popen(*args, **kwargs)
1803
def get_bzr_path(self):
1804
"""Return the path of the 'bzr' executable for this test suite."""
1805
bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
1806
if not os.path.isfile(bzr_path):
1807
# We are probably installed. Assume sys.argv is the right file
1808
bzr_path = sys.argv[0]
1811
def finish_bzr_subprocess(self, process, retcode=0, send_signal=None,
1812
universal_newlines=False, process_args=None):
1813
"""Finish the execution of process.
1815
:param process: the Popen object returned from start_bzr_subprocess.
800
1816
:param retcode: The status code that is expected. Defaults to 0. If
801
None is supplied, the status code is not checked.
1817
None is supplied, the status code is not checked.
1818
:param send_signal: an optional signal to send to the process.
1819
:param universal_newlines: Convert CRLF => LF
1820
:returns: (stdout, stderr)
803
bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
805
process = Popen([sys.executable, bzr_path]+args, stdout=PIPE,
807
out = process.stdout.read()
808
err = process.stderr.read()
809
retcode = process.wait()
810
supplied_retcode = kwargs.get('retcode', 0)
811
if supplied_retcode is not None:
812
assert supplied_retcode == retcode
1822
if send_signal is not None:
1823
os.kill(process.pid, send_signal)
1824
out, err = process.communicate()
1826
if universal_newlines:
1827
out = out.replace('\r\n', '\n')
1828
err = err.replace('\r\n', '\n')
1830
if retcode is not None and retcode != process.returncode:
1831
if process_args is None:
1832
process_args = "(unknown args)"
1833
mutter('Output of bzr %s:\n%s', process_args, out)
1834
mutter('Error for bzr %s:\n%s', process_args, err)
1835
self.fail('Command bzr %s failed with retcode %s != %s'
1836
% (process_args, retcode, process.returncode))
813
1837
return [out, err]
815
1839
def check_inventory_shape(self, inv, shape):
864
1888
sys.stderr = real_stderr
865
1889
sys.stdin = real_stdin
867
def merge(self, branch_from, wt_to):
868
"""A helper for tests to do a ui-less merge.
870
This should move to the main library when someone has time to integrate
873
# minimal ui-less merge.
874
wt_to.branch.fetch(branch_from)
875
base_rev = common_ancestor(branch_from.last_revision(),
876
wt_to.branch.last_revision(),
877
wt_to.branch.repository)
878
merge_inner(wt_to.branch, branch_from.basis_tree(),
879
wt_to.branch.repository.revision_tree(base_rev),
881
wt_to.add_pending_merge(branch_from.last_revision())
884
BzrTestBase = TestCase
887
class TestCaseInTempDir(TestCase):
1891
def reduceLockdirTimeout(self):
1892
"""Reduce the default lock timeout for the duration of the test, so that
1893
if LockContention occurs during a test, it does so quickly.
1895
Tests that expect to provoke LockContention errors should call this.
1897
orig_timeout = bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS
1899
bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = orig_timeout
1900
self.addCleanup(resetTimeout)
1901
bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = 0
1903
def make_utf8_encoded_stringio(self, encoding_type=None):
1904
"""Return a StringIOWrapper instance, that will encode Unicode
1907
if encoding_type is None:
1908
encoding_type = 'strict'
1910
output_encoding = 'utf-8'
1911
sio = codecs.getwriter(output_encoding)(sio, errors=encoding_type)
1912
sio.encoding = output_encoding
1916
class CapturedCall(object):
1917
"""A helper for capturing smart server calls for easy debug analysis."""
1919
def __init__(self, params, prefix_length):
1920
"""Capture the call with params and skip prefix_length stack frames."""
1923
# The last 5 frames are the __init__, the hook frame, and 3 smart
1924
# client frames. Beyond this we could get more clever, but this is good
1926
stack = traceback.extract_stack()[prefix_length:-5]
1927
self.stack = ''.join(traceback.format_list(stack))
1930
return self.call.method
1933
return self.call.method
1939
class TestCaseWithMemoryTransport(TestCase):
1940
"""Common test class for tests that do not need disk resources.
1942
Tests that need disk resources should derive from TestCaseWithTransport.
1944
TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
1946
For TestCaseWithMemoryTransport the test_home_dir is set to the name of
1947
a directory which does not exist. This serves to help ensure test isolation
1948
is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
1949
must exist. However, TestCaseWithMemoryTransport does not offer local
1950
file defaults for the transport in tests, nor does it obey the command line
1951
override, so tests that accidentally write to the common directory should
1954
:cvar TEST_ROOT: Directory containing all temporary directories, plus
1955
a .bzr directory that stops us ascending higher into the filesystem.
1961
def __init__(self, methodName='runTest'):
1962
# allow test parameterization after test construction and before test
1963
# execution. Variables that the parameterizer sets need to be
1964
# ones that are not set by setUp, or setUp will trash them.
1965
super(TestCaseWithMemoryTransport, self).__init__(methodName)
1966
self.vfs_transport_factory = default_transport
1967
self.transport_server = None
1968
self.transport_readonly_server = None
1969
self.__vfs_server = None
1971
def get_transport(self, relpath=None):
1972
"""Return a writeable transport.
1974
This transport is for the test scratch space relative to
1977
:param relpath: a path relative to the base url.
1979
t = get_transport(self.get_url(relpath))
1980
self.assertFalse(t.is_readonly())
1983
def get_readonly_transport(self, relpath=None):
1984
"""Return a readonly transport for the test scratch space
1986
This can be used to test that operations which should only need
1987
readonly access in fact do not try to write.
1989
:param relpath: a path relative to the base url.
1991
t = get_transport(self.get_readonly_url(relpath))
1992
self.assertTrue(t.is_readonly())
1995
def create_transport_readonly_server(self):
1996
"""Create a transport server from class defined at init.
1998
This is mostly a hook for daughter classes.
2000
return self.transport_readonly_server()
2002
def get_readonly_server(self):
2003
"""Get the server instance for the readonly transport
2005
This is useful for some tests with specific servers to do diagnostics.
2007
if self.__readonly_server is None:
2008
if self.transport_readonly_server is None:
2009
# readonly decorator requested
2010
# bring up the server
2011
self.__readonly_server = ReadonlyServer()
2012
self.__readonly_server.setUp(self.get_vfs_only_server())
2014
self.__readonly_server = self.create_transport_readonly_server()
2015
self.__readonly_server.setUp(self.get_vfs_only_server())
2016
self.addCleanup(self.__readonly_server.tearDown)
2017
return self.__readonly_server
2019
def get_readonly_url(self, relpath=None):
2020
"""Get a URL for the readonly transport.
2022
This will either be backed by '.' or a decorator to the transport
2023
used by self.get_url()
2024
relpath provides for clients to get a path relative to the base url.
2025
These should only be downwards relative, not upwards.
2027
base = self.get_readonly_server().get_url()
2028
return self._adjust_url(base, relpath)
2030
def get_vfs_only_server(self):
2031
"""Get the vfs only read/write server instance.
2033
This is useful for some tests with specific servers that need
2036
For TestCaseWithMemoryTransport this is always a MemoryServer, and there
2037
is no means to override it.
2039
if self.__vfs_server is None:
2040
self.__vfs_server = MemoryServer()
2041
self.__vfs_server.setUp()
2042
self.addCleanup(self.__vfs_server.tearDown)
2043
return self.__vfs_server
2045
def get_server(self):
2046
"""Get the read/write server instance.
2048
This is useful for some tests with specific servers that need
2051
This is built from the self.transport_server factory. If that is None,
2052
then the self.get_vfs_server is returned.
2054
if self.__server is None:
2055
if self.transport_server is None or self.transport_server is self.vfs_transport_factory:
2056
return self.get_vfs_only_server()
2058
# bring up a decorated means of access to the vfs only server.
2059
self.__server = self.transport_server()
2061
self.__server.setUp(self.get_vfs_only_server())
2062
except TypeError, e:
2063
# This should never happen; the try:Except here is to assist
2064
# developers having to update code rather than seeing an
2065
# uninformative TypeError.
2066
raise Exception, "Old server API in use: %s, %s" % (self.__server, e)
2067
self.addCleanup(self.__server.tearDown)
2068
return self.__server
2070
def _adjust_url(self, base, relpath):
2071
"""Get a URL (or maybe a path) for the readwrite transport.
2073
This will either be backed by '.' or to an equivalent non-file based
2075
relpath provides for clients to get a path relative to the base url.
2076
These should only be downwards relative, not upwards.
2078
if relpath is not None and relpath != '.':
2079
if not base.endswith('/'):
2081
# XXX: Really base should be a url; we did after all call
2082
# get_url()! But sometimes it's just a path (from
2083
# LocalAbspathServer), and it'd be wrong to append urlescaped data
2084
# to a non-escaped local path.
2085
if base.startswith('./') or base.startswith('/'):
2088
base += urlutils.escape(relpath)
2091
def get_url(self, relpath=None):
2092
"""Get a URL (or maybe a path) for the readwrite transport.
2094
This will either be backed by '.' or to an equivalent non-file based
2096
relpath provides for clients to get a path relative to the base url.
2097
These should only be downwards relative, not upwards.
2099
base = self.get_server().get_url()
2100
return self._adjust_url(base, relpath)
2102
def get_vfs_only_url(self, relpath=None):
2103
"""Get a URL (or maybe a path for the plain old vfs transport.
2105
This will never be a smart protocol. It always has all the
2106
capabilities of the local filesystem, but it might actually be a
2107
MemoryTransport or some other similar virtual filesystem.
2109
This is the backing transport (if any) of the server returned by
2110
get_url and get_readonly_url.
2112
:param relpath: provides for clients to get a path relative to the base
2113
url. These should only be downwards relative, not upwards.
2116
base = self.get_vfs_only_server().get_url()
2117
return self._adjust_url(base, relpath)
2119
def _create_safety_net(self):
2120
"""Make a fake bzr directory.
2122
This prevents any tests propagating up onto the TEST_ROOT directory's
2125
root = TestCaseWithMemoryTransport.TEST_ROOT
2126
bzrdir.BzrDir.create_standalone_workingtree(root)
2128
def _check_safety_net(self):
2129
"""Check that the safety .bzr directory have not been touched.
2131
_make_test_root have created a .bzr directory to prevent tests from
2132
propagating. This method ensures than a test did not leaked.
2134
root = TestCaseWithMemoryTransport.TEST_ROOT
2135
wt = workingtree.WorkingTree.open(root)
2136
last_rev = wt.last_revision()
2137
if last_rev != 'null:':
2138
# The current test have modified the /bzr directory, we need to
2139
# recreate a new one or all the followng tests will fail.
2140
# If you need to inspect its content uncomment the following line
2141
# import pdb; pdb.set_trace()
2142
_rmtree_temp_dir(root + '/.bzr')
2143
self._create_safety_net()
2144
raise AssertionError('%s/.bzr should not be modified' % root)
2146
def _make_test_root(self):
2147
if TestCaseWithMemoryTransport.TEST_ROOT is None:
2148
root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
2149
TestCaseWithMemoryTransport.TEST_ROOT = root
2151
self._create_safety_net()
2153
# The same directory is used by all tests, and we're not
2154
# specifically told when all tests are finished. This will do.
2155
atexit.register(_rmtree_temp_dir, root)
2157
self.addCleanup(self._check_safety_net)
2159
def makeAndChdirToTestDir(self):
2160
"""Create a temporary directories for this one test.
2162
This must set self.test_home_dir and self.test_dir and chdir to
2165
For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this test.
2167
os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2168
self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
2169
self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
2171
def make_branch(self, relpath, format=None):
2172
"""Create a branch on the transport at relpath."""
2173
repo = self.make_repository(relpath, format=format)
2174
return repo.bzrdir.create_branch()
2176
def make_bzrdir(self, relpath, format=None):
2178
# might be a relative or absolute path
2179
maybe_a_url = self.get_url(relpath)
2180
segments = maybe_a_url.rsplit('/', 1)
2181
t = get_transport(maybe_a_url)
2182
if len(segments) > 1 and segments[-1] not in ('', '.'):
2186
if isinstance(format, basestring):
2187
format = bzrdir.format_registry.make_bzrdir(format)
2188
return format.initialize_on_transport(t)
2189
except errors.UninitializableFormat:
2190
raise TestSkipped("Format %s is not initializable." % format)
2192
def make_repository(self, relpath, shared=False, format=None):
2193
"""Create a repository on our default transport at relpath.
2195
Note that relpath must be a relative path, not a full url.
2197
# FIXME: If you create a remoterepository this returns the underlying
2198
# real format, which is incorrect. Actually we should make sure that
2199
# RemoteBzrDir returns a RemoteRepository.
2200
# maybe mbp 20070410
2201
made_control = self.make_bzrdir(relpath, format=format)
2202
return made_control.create_repository(shared=shared)
2204
def make_smart_server(self, path):
2205
smart_server = server.SmartTCPServer_for_testing()
2206
smart_server.setUp(self.get_server())
2207
remote_transport = get_transport(smart_server.get_url()).clone(path)
2208
self.addCleanup(smart_server.tearDown)
2209
return remote_transport
2211
def make_branch_and_memory_tree(self, relpath, format=None):
2212
"""Create a branch on the default transport and a MemoryTree for it."""
2213
b = self.make_branch(relpath, format=format)
2214
return memorytree.MemoryTree.create_on_branch(b)
2216
def make_branch_builder(self, relpath, format=None):
2217
branch = self.make_branch(relpath, format=format)
2218
return branchbuilder.BranchBuilder(branch=branch)
2220
def overrideEnvironmentForTesting(self):
2221
os.environ['HOME'] = self.test_home_dir
2222
os.environ['BZR_HOME'] = self.test_home_dir
2225
super(TestCaseWithMemoryTransport, self).setUp()
2226
self._make_test_root()
2227
_currentdir = os.getcwdu()
2228
def _leaveDirectory():
2229
os.chdir(_currentdir)
2230
self.addCleanup(_leaveDirectory)
2231
self.makeAndChdirToTestDir()
2232
self.overrideEnvironmentForTesting()
2233
self.__readonly_server = None
2234
self.__server = None
2235
self.reduceLockdirTimeout()
2237
def setup_smart_server_with_call_log(self):
2238
"""Sets up a smart server as the transport server with a call log."""
2239
self.transport_server = server.SmartTCPServer_for_testing
2240
self.hpss_calls = []
2242
# Skip the current stack down to the caller of
2243
# setup_smart_server_with_call_log
2244
prefix_length = len(traceback.extract_stack()) - 2
2245
def capture_hpss_call(params):
2246
self.hpss_calls.append(
2247
CapturedCall(params, prefix_length))
2248
client._SmartClient.hooks.install_named_hook(
2249
'call', capture_hpss_call, None)
2251
def reset_smart_call_log(self):
2252
self.hpss_calls = []
2255
class TestCaseInTempDir(TestCaseWithMemoryTransport):
888
2256
"""Derived class that runs a test within a temporary directory.
890
2258
This is useful for tests that need to create a branch, etc.
1188
2492
for readonly urls.
1190
2494
TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
1191
be used without needed to redo it when a different
2495
be used without needed to redo it when a different
1192
2496
subclass is in use ?
1195
2499
def setUp(self):
1196
2500
super(ChrootedTestCase, self).setUp()
1197
if not self.transport_server == bzrlib.transport.memory.MemoryServer:
1198
self.transport_readonly_server = bzrlib.transport.http.HttpServer
2501
if not self.vfs_transport_factory == MemoryServer:
2502
self.transport_readonly_server = HttpServer
2505
def condition_id_re(pattern):
2506
"""Create a condition filter which performs a re check on a test's id.
2508
:param pattern: A regular expression string.
2509
:return: A callable that returns True if the re matches.
2511
filter_re = osutils.re_compile_checked(pattern, 0,
2513
def condition(test):
2515
return filter_re.search(test_id)
2519
def condition_isinstance(klass_or_klass_list):
2520
"""Create a condition filter which returns isinstance(param, klass).
2522
:return: A callable which when called with one parameter obj return the
2523
result of isinstance(obj, klass_or_klass_list).
2526
return isinstance(obj, klass_or_klass_list)
2530
def condition_id_in_list(id_list):
2531
"""Create a condition filter which verify that test's id in a list.
2533
:param id_list: A TestIdList object.
2534
:return: A callable that returns True if the test's id appears in the list.
2536
def condition(test):
2537
return id_list.includes(test.id())
2541
def condition_id_startswith(starts):
2542
"""Create a condition filter verifying that test's id starts with a string.
2544
:param starts: A list of string.
2545
:return: A callable that returns True if the test's id starts with one of
2548
def condition(test):
2549
for start in starts:
2550
if test.id().startswith(start):
2556
def exclude_tests_by_condition(suite, condition):
2557
"""Create a test suite which excludes some tests from suite.
2559
:param suite: The suite to get tests from.
2560
:param condition: A callable whose result evaluates True when called with a
2561
test case which should be excluded from the result.
2562
:return: A suite which contains the tests found in suite that fail
2566
for test in iter_suite_tests(suite):
2567
if not condition(test):
2569
return TestUtil.TestSuite(result)
2572
def filter_suite_by_condition(suite, condition):
2573
"""Create a test suite by filtering another one.
2575
:param suite: The source suite.
2576
:param condition: A callable whose result evaluates True when called with a
2577
test case which should be included in the result.
2578
:return: A suite which contains the tests found in suite that pass
2582
for test in iter_suite_tests(suite):
2585
return TestUtil.TestSuite(result)
1201
2588
def filter_suite_by_re(suite, pattern):
1202
result = TestUtil.TestSuite()
1203
filter_re = re.compile(pattern)
2589
"""Create a test suite by filtering another one.
2591
:param suite: the source suite
2592
:param pattern: pattern that names must match
2593
:returns: the newly created suite
2595
condition = condition_id_re(pattern)
2596
result_suite = filter_suite_by_condition(suite, condition)
2600
def filter_suite_by_id_list(suite, test_id_list):
2601
"""Create a test suite by filtering another one.
2603
:param suite: The source suite.
2604
:param test_id_list: A list of the test ids to keep as strings.
2605
:returns: the newly created suite
2607
condition = condition_id_in_list(test_id_list)
2608
result_suite = filter_suite_by_condition(suite, condition)
2612
def filter_suite_by_id_startswith(suite, start):
2613
"""Create a test suite by filtering another one.
2615
:param suite: The source suite.
2616
:param start: A list of string the test id must start with one of.
2617
:returns: the newly created suite
2619
condition = condition_id_startswith(start)
2620
result_suite = filter_suite_by_condition(suite, condition)
2624
def exclude_tests_by_re(suite, pattern):
2625
"""Create a test suite which excludes some tests from suite.
2627
:param suite: The suite to get tests from.
2628
:param pattern: A regular expression string. Test ids that match this
2629
pattern will be excluded from the result.
2630
:return: A TestSuite that contains all the tests from suite without the
2631
tests that matched pattern. The order of tests is the same as it was in
2634
return exclude_tests_by_condition(suite, condition_id_re(pattern))
2637
def preserve_input(something):
2638
"""A helper for performing test suite transformation chains.
2640
:param something: Anything you want to preserve.
2646
def randomize_suite(suite):
2647
"""Return a new TestSuite with suite's tests in random order.
2649
The tests in the input suite are flattened into a single suite in order to
2650
accomplish this. Any nested TestSuites are removed to provide global
2653
tests = list(iter_suite_tests(suite))
2654
random.shuffle(tests)
2655
return TestUtil.TestSuite(tests)
2658
def split_suite_by_condition(suite, condition):
2659
"""Split a test suite into two by a condition.
2661
:param suite: The suite to split.
2662
:param condition: The condition to match on. Tests that match this
2663
condition are returned in the first test suite, ones that do not match
2664
are in the second suite.
2665
:return: A tuple of two test suites, where the first contains tests from
2666
suite matching the condition, and the second contains the remainder
2667
from suite. The order within each output suite is the same as it was in
1204
2672
for test in iter_suite_tests(suite):
1205
if filter_re.search(test.id()):
1206
result.addTest(test)
2674
matched.append(test)
2676
did_not_match.append(test)
2677
return TestUtil.TestSuite(matched), TestUtil.TestSuite(did_not_match)
2680
def split_suite_by_re(suite, pattern):
2681
"""Split a test suite into two by a regular expression.
2683
:param suite: The suite to split.
2684
:param pattern: A regular expression string. Test ids that match this
2685
pattern will be in the first test suite returned, and the others in the
2686
second test suite returned.
2687
:return: A tuple of two test suites, where the first contains tests from
2688
suite matching pattern, and the second contains the remainder from
2689
suite. The order within each output suite is the same as it was in
2692
return split_suite_by_condition(suite, condition_id_re(pattern))
1210
2695
def run_suite(suite, name='test', verbose=False, pattern=".*",
1211
stop_on_failure=False, keep_output=False,
1212
transport=None, lsprof_timed=None):
1213
TestCaseInTempDir._TEST_NAME = name
2696
stop_on_failure=False,
2697
transport=None, lsprof_timed=None, bench_history=None,
2698
matching_tests_first=None,
2701
exclude_pattern=None,
2704
suite_decorators=None,
2706
"""Run a test suite for bzr selftest.
2708
:param runner_class: The class of runner to use. Must support the
2709
constructor arguments passed by run_suite which are more than standard
2711
:return: A boolean indicating success.
1214
2713
TestCase._gather_lsprof_in_benchmarks = lsprof_timed
1220
pb = progress.ProgressBar()
1221
runner = TextTestRunner(stream=sys.stdout,
2718
if runner_class is None:
2719
runner_class = TextTestRunner
2722
runner = runner_class(stream=stream,
1222
2723
descriptions=0,
1223
2724
verbosity=verbosity,
1224
keep_output=keep_output,
2725
bench_history=bench_history,
2726
list_only=list_only,
1226
2729
runner.stop_on_failure=stop_on_failure
1228
suite = filter_suite_by_re(suite, pattern)
2730
# built in decorator factories:
2732
random_order(random_seed, runner),
2733
exclude_tests(exclude_pattern),
2735
if matching_tests_first:
2736
decorators.append(tests_first(pattern))
2738
decorators.append(filter_tests(pattern))
2739
if suite_decorators:
2740
decorators.extend(suite_decorators)
2741
for decorator in decorators:
2742
suite = decorator(suite)
1229
2743
result = runner.run(suite)
1230
return result.wasSuccessful()
2748
return result.wasStrictlySuccessful()
2750
return result.wasSuccessful()
2753
# A registry where get() returns a suite decorator.
2754
parallel_registry = registry.Registry()
2757
def fork_decorator(suite):
2758
concurrency = osutils.local_concurrency()
2759
if concurrency == 1:
2761
from testtools import ConcurrentTestSuite
2762
return ConcurrentTestSuite(suite, fork_for_tests)
2763
parallel_registry.register('fork', fork_decorator)
2766
def subprocess_decorator(suite):
2767
concurrency = osutils.local_concurrency()
2768
if concurrency == 1:
2770
from testtools import ConcurrentTestSuite
2771
return ConcurrentTestSuite(suite, reinvoke_for_tests)
2772
parallel_registry.register('subprocess', subprocess_decorator)
2775
def exclude_tests(exclude_pattern):
2776
"""Return a test suite decorator that excludes tests."""
2777
if exclude_pattern is None:
2778
return identity_decorator
2779
def decorator(suite):
2780
return ExcludeDecorator(suite, exclude_pattern)
2784
def filter_tests(pattern):
2786
return identity_decorator
2787
def decorator(suite):
2788
return FilterTestsDecorator(suite, pattern)
2792
def random_order(random_seed, runner):
2793
"""Return a test suite decorator factory for randomising tests order.
2795
:param random_seed: now, a string which casts to a long, or a long.
2796
:param runner: A test runner with a stream attribute to report on.
2798
if random_seed is None:
2799
return identity_decorator
2800
def decorator(suite):
2801
return RandomDecorator(suite, random_seed, runner.stream)
2805
def tests_first(pattern):
2807
return identity_decorator
2808
def decorator(suite):
2809
return TestFirstDecorator(suite, pattern)
2813
def identity_decorator(suite):
2818
class TestDecorator(TestSuite):
2819
"""A decorator for TestCase/TestSuite objects.
2821
Usually, subclasses should override __iter__(used when flattening test
2822
suites), which we do to filter, reorder, parallelise and so on, run() and
2826
def __init__(self, suite):
2827
TestSuite.__init__(self)
2830
def countTestCases(self):
2833
cases += test.countTestCases()
2840
def run(self, result):
2841
# Use iteration on self, not self._tests, to allow subclasses to hook
2844
if result.shouldStop:
2850
class ExcludeDecorator(TestDecorator):
2851
"""A decorator which excludes test matching an exclude pattern."""
2853
def __init__(self, suite, exclude_pattern):
2854
TestDecorator.__init__(self, suite)
2855
self.exclude_pattern = exclude_pattern
2856
self.excluded = False
2860
return iter(self._tests)
2861
self.excluded = True
2862
suite = exclude_tests_by_re(self, self.exclude_pattern)
2864
self.addTests(suite)
2865
return iter(self._tests)
2868
class FilterTestsDecorator(TestDecorator):
2869
"""A decorator which filters tests to those matching a pattern."""
2871
def __init__(self, suite, pattern):
2872
TestDecorator.__init__(self, suite)
2873
self.pattern = pattern
2874
self.filtered = False
2878
return iter(self._tests)
2879
self.filtered = True
2880
suite = filter_suite_by_re(self, self.pattern)
2882
self.addTests(suite)
2883
return iter(self._tests)
2886
class RandomDecorator(TestDecorator):
2887
"""A decorator which randomises the order of its tests."""
2889
def __init__(self, suite, random_seed, stream):
2890
TestDecorator.__init__(self, suite)
2891
self.random_seed = random_seed
2892
self.randomised = False
2893
self.stream = stream
2897
return iter(self._tests)
2898
self.randomised = True
2899
self.stream.writeln("Randomizing test order using seed %s\n" %
2900
(self.actual_seed()))
2901
# Initialise the random number generator.
2902
random.seed(self.actual_seed())
2903
suite = randomize_suite(self)
2905
self.addTests(suite)
2906
return iter(self._tests)
2908
def actual_seed(self):
2909
if self.random_seed == "now":
2910
# We convert the seed to a long to make it reuseable across
2911
# invocations (because the user can reenter it).
2912
self.random_seed = long(time.time())
2914
# Convert the seed to a long if we can
2916
self.random_seed = long(self.random_seed)
2919
return self.random_seed
2922
class TestFirstDecorator(TestDecorator):
2923
"""A decorator which moves named tests to the front."""
2925
def __init__(self, suite, pattern):
2926
TestDecorator.__init__(self, suite)
2927
self.pattern = pattern
2928
self.filtered = False
2932
return iter(self._tests)
2933
self.filtered = True
2934
suites = split_suite_by_re(self, self.pattern)
2936
self.addTests(suites)
2937
return iter(self._tests)
2940
def partition_tests(suite, count):
2941
"""Partition suite into count lists of tests."""
2943
tests = list(iter_suite_tests(suite))
2944
tests_per_process = int(math.ceil(float(len(tests)) / count))
2945
for block in range(count):
2946
low_test = block * tests_per_process
2947
high_test = low_test + tests_per_process
2948
process_tests = tests[low_test:high_test]
2949
result.append(process_tests)
2953
def fork_for_tests(suite):
2954
"""Take suite and start up one runner per CPU by forking()
2956
:return: An iterable of TestCase-like objects which can each have
2957
run(result) called on them to feed tests to result.
2959
concurrency = osutils.local_concurrency()
2961
from subunit import TestProtocolClient, ProtocolTestCase
2962
class TestInOtherProcess(ProtocolTestCase):
2963
# Should be in subunit, I think. RBC.
2964
def __init__(self, stream, pid):
2965
ProtocolTestCase.__init__(self, stream)
2968
def run(self, result):
2970
ProtocolTestCase.run(self, result)
2972
os.waitpid(self.pid, os.WNOHANG)
2974
test_blocks = partition_tests(suite, concurrency)
2975
for process_tests in test_blocks:
2976
process_suite = TestSuite()
2977
process_suite.addTests(process_tests)
2978
c2pread, c2pwrite = os.pipe()
2983
# Leave stderr and stdout open so we can see test noise
2984
# Close stdin so that the child goes away if it decides to
2985
# read from stdin (otherwise its a roulette to see what
2986
# child actually gets keystrokes for pdb etc).
2989
stream = os.fdopen(c2pwrite, 'wb', 1)
2990
subunit_result = TestProtocolClient(stream)
2991
process_suite.run(subunit_result)
2996
stream = os.fdopen(c2pread, 'rb', 1)
2997
test = TestInOtherProcess(stream, pid)
3002
def reinvoke_for_tests(suite):
3003
"""Take suite and start up one runner per CPU using subprocess().
3005
:return: An iterable of TestCase-like objects which can each have
3006
run(result) called on them to feed tests to result.
3008
concurrency = osutils.local_concurrency()
3010
from subunit import ProtocolTestCase
3011
class TestInSubprocess(ProtocolTestCase):
3012
def __init__(self, process, name):
3013
ProtocolTestCase.__init__(self, process.stdout)
3014
self.process = process
3015
self.process.stdin.close()
3018
def run(self, result):
3020
ProtocolTestCase.run(self, result)
3023
os.unlink(self.name)
3024
# print "pid %d finished" % finished_process
3025
test_blocks = partition_tests(suite, concurrency)
3026
for process_tests in test_blocks:
3027
# ugly; currently reimplement rather than reuses TestCase methods.
3028
bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
3029
if not os.path.isfile(bzr_path):
3030
# We are probably installed. Assume sys.argv is the right file
3031
bzr_path = sys.argv[0]
3032
fd, test_list_file_name = tempfile.mkstemp()
3033
test_list_file = os.fdopen(fd, 'wb', 1)
3034
for test in process_tests:
3035
test_list_file.write(test.id() + '\n')
3036
test_list_file.close()
3038
argv = [bzr_path, 'selftest', '--load-list', test_list_file_name,
3040
if '--no-plugins' in sys.argv:
3041
argv.append('--no-plugins')
3042
# stderr=STDOUT would be ideal, but until we prevent noise on
3043
# stderr it can interrupt the subunit protocol.
3044
process = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE,
3046
test = TestInSubprocess(process, test_list_file_name)
3049
os.unlink(test_list_file_name)
3054
class BZRTransformingResult(unittest.TestResult):
3056
def __init__(self, target):
3057
unittest.TestResult.__init__(self)
3058
self.result = target
3060
def startTest(self, test):
3061
self.result.startTest(test)
3063
def stopTest(self, test):
3064
self.result.stopTest(test)
3066
def addError(self, test, err):
3067
feature = self._error_looks_like('UnavailableFeature: ', err)
3068
if feature is not None:
3069
self.result.addNotSupported(test, feature)
3071
self.result.addError(test, err)
3073
def addFailure(self, test, err):
3074
known = self._error_looks_like('KnownFailure: ', err)
3075
if known is not None:
3076
self.result._addKnownFailure(test, [KnownFailure,
3077
KnownFailure(known), None])
3079
self.result.addFailure(test, err)
3081
def addSkip(self, test, reason):
3082
self.result.addSkip(test, reason)
3084
def addSuccess(self, test):
3085
self.result.addSuccess(test)
3087
def _error_looks_like(self, prefix, err):
3088
"""Deserialize exception and returns the stringify value."""
3092
if isinstance(exc, subunit.RemoteException):
3093
# stringify the exception gives access to the remote traceback
3094
# We search the last line for 'prefix'
3095
lines = str(exc).split('\n')
3096
while lines and not lines[-1]:
3099
if lines[-1].startswith(prefix):
3100
value = lines[-1][len(prefix):]
3104
# Controlled by "bzr selftest -E=..." option
3105
selftest_debug_flags = set()
1233
3108
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
1235
3109
transport=None,
1236
3110
test_suite_factory=None,
3113
matching_tests_first=None,
3116
exclude_pattern=None,
3122
suite_decorators=None,
1238
3124
"""Run the whole test suite under the enhanced runner"""
1239
3125
# XXX: Very ugly way to do this...
1240
3126
# Disable warning about old formats because we don't want it to disturb
1247
3133
transport = default_transport
1248
3134
old_transport = default_transport
1249
3135
default_transport = transport
3136
global selftest_debug_flags
3137
old_debug_flags = selftest_debug_flags
3138
if debug_flags is not None:
3139
selftest_debug_flags = set(debug_flags)
3141
if load_list is None:
3144
keep_only = load_test_id_list(load_list)
1251
3145
if test_suite_factory is None:
1252
suite = test_suite()
3146
suite = test_suite(keep_only, starting_with)
1254
3148
suite = test_suite_factory()
1255
3149
return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
1256
stop_on_failure=stop_on_failure, keep_output=keep_output,
3150
stop_on_failure=stop_on_failure,
1257
3151
transport=transport,
1258
lsprof_timed=lsprof_timed)
3152
lsprof_timed=lsprof_timed,
3153
bench_history=bench_history,
3154
matching_tests_first=matching_tests_first,
3155
list_only=list_only,
3156
random_seed=random_seed,
3157
exclude_pattern=exclude_pattern,
3159
runner_class=runner_class,
3160
suite_decorators=suite_decorators,
1260
3163
default_transport = old_transport
3164
selftest_debug_flags = old_debug_flags
3167
def load_test_id_list(file_name):
3168
"""Load a test id list from a text file.
3170
The format is one test id by line. No special care is taken to impose
3171
strict rules, these test ids are used to filter the test suite so a test id
3172
that do not match an existing test will do no harm. This allows user to add
3173
comments, leave blank lines, etc.
3177
ftest = open(file_name, 'rt')
3179
if e.errno != errno.ENOENT:
3182
raise errors.NoSuchFile(file_name)
3184
for test_name in ftest.readlines():
3185
test_list.append(test_name.strip())
3190
def suite_matches_id_list(test_suite, id_list):
3191
"""Warns about tests not appearing or appearing more than once.
3193
:param test_suite: A TestSuite object.
3194
:param test_id_list: The list of test ids that should be found in
3197
:return: (absents, duplicates) absents is a list containing the test found
3198
in id_list but not in test_suite, duplicates is a list containing the
3199
test found multiple times in test_suite.
3201
When using a prefined test id list, it may occurs that some tests do not
3202
exist anymore or that some tests use the same id. This function warns the
3203
tester about potential problems in his workflow (test lists are volatile)
3204
or in the test suite itself (using the same id for several tests does not
3205
help to localize defects).
3207
# Build a dict counting id occurrences
3209
for test in iter_suite_tests(test_suite):
3211
tests[id] = tests.get(id, 0) + 1
3216
occurs = tests.get(id, 0)
3218
not_found.append(id)
3220
duplicates.append(id)
3222
return not_found, duplicates
3225
class TestIdList(object):
3226
"""Test id list to filter a test suite.
3228
Relying on the assumption that test ids are built as:
3229
<module>[.<class>.<method>][(<param>+)], <module> being in python dotted
3230
notation, this class offers methods to :
3231
- avoid building a test suite for modules not refered to in the test list,
3232
- keep only the tests listed from the module test suite.
3235
def __init__(self, test_id_list):
3236
# When a test suite needs to be filtered against us we compare test ids
3237
# for equality, so a simple dict offers a quick and simple solution.
3238
self.tests = dict().fromkeys(test_id_list, True)
3240
# While unittest.TestCase have ids like:
3241
# <module>.<class>.<method>[(<param+)],
3242
# doctest.DocTestCase can have ids like:
3245
# <module>.<function>
3246
# <module>.<class>.<method>
3248
# Since we can't predict a test class from its name only, we settle on
3249
# a simple constraint: a test id always begins with its module name.
3252
for test_id in test_id_list:
3253
parts = test_id.split('.')
3254
mod_name = parts.pop(0)
3255
modules[mod_name] = True
3257
mod_name += '.' + part
3258
modules[mod_name] = True
3259
self.modules = modules
3261
def refers_to(self, module_name):
3262
"""Is there tests for the module or one of its sub modules."""
3263
return self.modules.has_key(module_name)
3265
def includes(self, test_id):
3266
return self.tests.has_key(test_id)
3269
class TestPrefixAliasRegistry(registry.Registry):
3270
"""A registry for test prefix aliases.
3272
This helps implement shorcuts for the --starting-with selftest
3273
option. Overriding existing prefixes is not allowed but not fatal (a
3274
warning will be emitted).
3277
def register(self, key, obj, help=None, info=None,
3278
override_existing=False):
3279
"""See Registry.register.
3281
Trying to override an existing alias causes a warning to be emitted,
3282
not a fatal execption.
3285
super(TestPrefixAliasRegistry, self).register(
3286
key, obj, help=help, info=info, override_existing=False)
3288
actual = self.get(key)
3289
note('Test prefix alias %s is already used for %s, ignoring %s'
3290
% (key, actual, obj))
3292
def resolve_alias(self, id_start):
3293
"""Replace the alias by the prefix in the given string.
3295
Using an unknown prefix is an error to help catching typos.
3297
parts = id_start.split('.')
3299
parts[0] = self.get(parts[0])
3301
raise errors.BzrCommandError(
3302
'%s is not a known test prefix alias' % parts[0])
3303
return '.'.join(parts)
3306
test_prefix_alias_registry = TestPrefixAliasRegistry()
3307
"""Registry of test prefix aliases."""
3310
# This alias allows to detect typos ('bzrlin.') by making all valid test ids
3311
# appear prefixed ('bzrlib.' is "replaced" by 'bzrlib.').
3312
test_prefix_alias_registry.register('bzrlib', 'bzrlib')
3314
# Obvious higest levels prefixes, feel free to add your own via a plugin
3315
test_prefix_alias_registry.register('bd', 'bzrlib.doc')
3316
test_prefix_alias_registry.register('bu', 'bzrlib.utils')
3317
test_prefix_alias_registry.register('bt', 'bzrlib.tests')
3318
test_prefix_alias_registry.register('bb', 'bzrlib.tests.blackbox')
3319
test_prefix_alias_registry.register('bp', 'bzrlib.plugins')
3322
def test_suite(keep_only=None, starting_with=None):
1264
3323
"""Build and return TestSuite for the whole of bzrlib.
3325
:param keep_only: A list of test ids limiting the suite returned.
3327
:param starting_with: An id limiting the suite returned to the tests
1266
3330
This function can be replaced if you need to change the default test
1267
3331
suite on a global basis, but it is not encouraged.
1269
3333
testmod_names = [
3335
'bzrlib.tests.blackbox',
3336
'bzrlib.tests.branch_implementations',
3337
'bzrlib.tests.bzrdir_implementations',
3338
'bzrlib.tests.commands',
3339
'bzrlib.tests.interrepository_implementations',
3340
'bzrlib.tests.intertree_implementations',
3341
'bzrlib.tests.inventory_implementations',
3342
'bzrlib.tests.per_interbranch',
3343
'bzrlib.tests.per_lock',
3344
'bzrlib.tests.per_repository',
3345
'bzrlib.tests.per_repository_chk',
3346
'bzrlib.tests.per_repository_reference',
3347
'bzrlib.tests.test__annotator',
3348
'bzrlib.tests.test__chk_map',
3349
'bzrlib.tests.test__dirstate_helpers',
3350
'bzrlib.tests.test__groupcompress',
3351
'bzrlib.tests.test__known_graph',
3352
'bzrlib.tests.test__rio',
3353
'bzrlib.tests.test__walkdirs_win32',
1270
3354
'bzrlib.tests.test_ancestry',
3355
'bzrlib.tests.test_annotate',
1271
3356
'bzrlib.tests.test_api',
1272
3357
'bzrlib.tests.test_atomicfile',
1273
3358
'bzrlib.tests.test_bad_files',
3359
'bzrlib.tests.test_bencode',
3360
'bzrlib.tests.test_bisect_multi',
1274
3361
'bzrlib.tests.test_branch',
3362
'bzrlib.tests.test_branchbuilder',
3363
'bzrlib.tests.test_btree_index',
3364
'bzrlib.tests.test_bugtracker',
1275
3365
'bzrlib.tests.test_bundle',
1276
3366
'bzrlib.tests.test_bzrdir',
1277
'bzrlib.tests.test_command',
3367
'bzrlib.tests.test__chunks_to_lines',
3368
'bzrlib.tests.test_cache_utf8',
3369
'bzrlib.tests.test_chk_map',
3370
'bzrlib.tests.test_chk_serializer',
3371
'bzrlib.tests.test_chunk_writer',
3372
'bzrlib.tests.test_clean_tree',
3373
'bzrlib.tests.test_commands',
1278
3374
'bzrlib.tests.test_commit',
1279
3375
'bzrlib.tests.test_commit_merge',
1280
3376
'bzrlib.tests.test_config',
1281
3377
'bzrlib.tests.test_conflicts',
3378
'bzrlib.tests.test_counted_lock',
1282
3379
'bzrlib.tests.test_decorators',
3380
'bzrlib.tests.test_delta',
3381
'bzrlib.tests.test_debug',
3382
'bzrlib.tests.test_deprecated_graph',
1283
3383
'bzrlib.tests.test_diff',
1284
'bzrlib.tests.test_doc_generate',
3384
'bzrlib.tests.test_directory_service',
3385
'bzrlib.tests.test_dirstate',
3386
'bzrlib.tests.test_email_message',
3387
'bzrlib.tests.test_eol_filters',
1285
3388
'bzrlib.tests.test_errors',
1286
'bzrlib.tests.test_escaped_store',
3389
'bzrlib.tests.test_export',
3390
'bzrlib.tests.test_extract',
1287
3391
'bzrlib.tests.test_fetch',
3392
'bzrlib.tests.test_fifo_cache',
3393
'bzrlib.tests.test_filters',
3394
'bzrlib.tests.test_ftp_transport',
3395
'bzrlib.tests.test_foreign',
3396
'bzrlib.tests.test_generate_docs',
3397
'bzrlib.tests.test_generate_ids',
3398
'bzrlib.tests.test_globbing',
1288
3399
'bzrlib.tests.test_gpg',
1289
3400
'bzrlib.tests.test_graph',
3401
'bzrlib.tests.test_groupcompress',
1290
3402
'bzrlib.tests.test_hashcache',
3403
'bzrlib.tests.test_help',
3404
'bzrlib.tests.test_hooks',
1291
3405
'bzrlib.tests.test_http',
1292
3406
'bzrlib.tests.test_http_response',
3407
'bzrlib.tests.test_https_ca_bundle',
1293
3408
'bzrlib.tests.test_identitymap',
1294
3409
'bzrlib.tests.test_ignores',
3410
'bzrlib.tests.test_index',
3411
'bzrlib.tests.test_info',
1295
3412
'bzrlib.tests.test_inv',
3413
'bzrlib.tests.test_inventory_delta',
1296
3414
'bzrlib.tests.test_knit',
3415
'bzrlib.tests.test_lazy_import',
3416
'bzrlib.tests.test_lazy_regex',
3417
'bzrlib.tests.test_lockable_files',
1297
3418
'bzrlib.tests.test_lockdir',
1298
'bzrlib.tests.test_lockable_files',
1299
3419
'bzrlib.tests.test_log',
3420
'bzrlib.tests.test_lru_cache',
3421
'bzrlib.tests.test_lsprof',
3422
'bzrlib.tests.test_mail_client',
3423
'bzrlib.tests.test_memorytree',
1300
3424
'bzrlib.tests.test_merge',
1301
3425
'bzrlib.tests.test_merge3',
1302
3426
'bzrlib.tests.test_merge_core',
3427
'bzrlib.tests.test_merge_directive',
1303
3428
'bzrlib.tests.test_missing',
1304
3429
'bzrlib.tests.test_msgeditor',
3430
'bzrlib.tests.test_multiparent',
3431
'bzrlib.tests.test_mutabletree',
1305
3432
'bzrlib.tests.test_nonascii',
1306
3433
'bzrlib.tests.test_options',
1307
3434
'bzrlib.tests.test_osutils',
3435
'bzrlib.tests.test_osutils_encodings',
3436
'bzrlib.tests.test_pack',
3437
'bzrlib.tests.test_pack_repository',
1308
3438
'bzrlib.tests.test_patch',
1309
3439
'bzrlib.tests.test_patches',
1310
3440
'bzrlib.tests.test_permissions',
1311
3441
'bzrlib.tests.test_plugins',
1312
3442
'bzrlib.tests.test_progress',
3443
'bzrlib.tests.test_read_bundle',
1313
3444
'bzrlib.tests.test_reconcile',
3445
'bzrlib.tests.test_reconfigure',
3446
'bzrlib.tests.test_registry',
3447
'bzrlib.tests.test_remote',
3448
'bzrlib.tests.test_rename_map',
1314
3449
'bzrlib.tests.test_repository',
3450
'bzrlib.tests.test_revert',
1315
3451
'bzrlib.tests.test_revision',
1316
'bzrlib.tests.test_revisionnamespaces',
3452
'bzrlib.tests.test_revisionspec',
1317
3453
'bzrlib.tests.test_revisiontree',
1318
3454
'bzrlib.tests.test_rio',
3455
'bzrlib.tests.test_rules',
1319
3456
'bzrlib.tests.test_sampler',
1320
3457
'bzrlib.tests.test_selftest',
3458
'bzrlib.tests.test_serializer',
1321
3459
'bzrlib.tests.test_setup',
1322
3460
'bzrlib.tests.test_sftp_transport',
3461
'bzrlib.tests.test_shelf',
3462
'bzrlib.tests.test_shelf_ui',
3463
'bzrlib.tests.test_smart',
1323
3464
'bzrlib.tests.test_smart_add',
3465
'bzrlib.tests.test_smart_request',
3466
'bzrlib.tests.test_smart_transport',
3467
'bzrlib.tests.test_smtp_connection',
1324
3468
'bzrlib.tests.test_source',
3469
'bzrlib.tests.test_ssh_transport',
1325
3470
'bzrlib.tests.test_status',
1326
3471
'bzrlib.tests.test_store',
3472
'bzrlib.tests.test_strace',
3473
'bzrlib.tests.test_subsume',
3474
'bzrlib.tests.test_switch',
1327
3475
'bzrlib.tests.test_symbol_versioning',
3476
'bzrlib.tests.test_tag',
1328
3477
'bzrlib.tests.test_testament',
1329
3478
'bzrlib.tests.test_textfile',
1330
3479
'bzrlib.tests.test_textmerge',
3480
'bzrlib.tests.test_timestamp',
1331
3481
'bzrlib.tests.test_trace',
1332
3482
'bzrlib.tests.test_transactions',
1333
3483
'bzrlib.tests.test_transform',
1334
3484
'bzrlib.tests.test_transport',
3485
'bzrlib.tests.test_transport_implementations',
3486
'bzrlib.tests.test_transport_log',
1335
3487
'bzrlib.tests.test_tree',
3488
'bzrlib.tests.test_treebuilder',
1336
3489
'bzrlib.tests.test_tsort',
1337
3490
'bzrlib.tests.test_tuned_gzip',
1338
3491
'bzrlib.tests.test_ui',
3492
'bzrlib.tests.test_uncommit',
1339
3493
'bzrlib.tests.test_upgrade',
3494
'bzrlib.tests.test_upgrade_stacked',
1340
3495
'bzrlib.tests.test_urlutils',
3496
'bzrlib.tests.test_version',
3497
'bzrlib.tests.test_version_info',
1341
3498
'bzrlib.tests.test_versionedfile',
1342
3499
'bzrlib.tests.test_weave',
1343
3500
'bzrlib.tests.test_whitebox',
3501
'bzrlib.tests.test_win32utils',
1344
3502
'bzrlib.tests.test_workingtree',
3503
'bzrlib.tests.test_workingtree_4',
3504
'bzrlib.tests.test_wsgi',
1345
3505
'bzrlib.tests.test_xml',
3506
'bzrlib.tests.tree_implementations',
3507
'bzrlib.tests.workingtree_implementations',
1347
test_transport_implementations = [
1348
'bzrlib.tests.test_transport_implementations',
1349
'bzrlib.tests.test_read_bundle',
1351
suite = TestUtil.TestSuite()
1352
3510
loader = TestUtil.TestLoader()
3512
if keep_only is not None:
3513
id_filter = TestIdList(keep_only)
3515
starting_with = [test_prefix_alias_registry.resolve_alias(start)
3516
for start in starting_with]
3517
# We take precedence over keep_only because *at loading time* using
3518
# both options means we will load less tests for the same final result.
3519
def interesting_module(name):
3520
for start in starting_with:
3522
# Either the module name starts with the specified string
3523
name.startswith(start)
3524
# or it may contain tests starting with the specified string
3525
or start.startswith(name)
3529
loader = TestUtil.FilteredByModuleTestLoader(interesting_module)
3531
elif keep_only is not None:
3532
loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
3533
def interesting_module(name):
3534
return id_filter.refers_to(name)
3537
loader = TestUtil.TestLoader()
3538
def interesting_module(name):
3539
# No filtering, all modules are interesting
3542
suite = loader.suiteClass()
3544
# modules building their suite with loadTestsFromModuleNames
1353
3545
suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
1354
from bzrlib.transport import TransportTestProviderAdapter
1355
adapter = TransportTestProviderAdapter()
1356
adapt_modules(test_transport_implementations, adapter, loader, suite)
1357
for package in packages_to_test():
1358
suite.addTest(package.test_suite())
1359
for m in MODULES_TO_TEST:
1360
suite.addTest(loader.loadTestsFromModule(m))
1361
for m in MODULES_TO_DOCTEST:
1362
suite.addTest(doctest.DocTestSuite(m))
1363
for name, plugin in bzrlib.plugin.all_plugins().items():
1364
if getattr(plugin, 'test_suite', None) is not None:
1365
suite.addTest(plugin.test_suite())
3547
modules_to_doctest = [
3549
'bzrlib.branchbuilder',
3552
'bzrlib.iterablefile',
3556
'bzrlib.symbol_versioning',
3559
'bzrlib.version_info_formats.format_custom',
3562
for mod in modules_to_doctest:
3563
if not interesting_module(mod):
3564
# No tests to keep here, move along
3567
# note that this really does mean "report only" -- doctest
3568
# still runs the rest of the examples
3569
doc_suite = doctest.DocTestSuite(mod,
3570
optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
3571
except ValueError, e:
3572
print '**failed to get doctest for: %s\n%s' % (mod, e)
3574
if len(doc_suite._tests) == 0:
3575
raise errors.BzrError("no doctests found in %s" % (mod,))
3576
suite.addTest(doc_suite)
3578
default_encoding = sys.getdefaultencoding()
3579
for name, plugin in bzrlib.plugin.plugins().items():
3580
if not interesting_module(plugin.module.__name__):
3582
plugin_suite = plugin.test_suite()
3583
# We used to catch ImportError here and turn it into just a warning,
3584
# but really if you don't have --no-plugins this should be a failure.
3585
# mbp 20080213 - see http://bugs.launchpad.net/bugs/189771
3586
if plugin_suite is None:
3587
plugin_suite = plugin.load_plugin_tests(loader)
3588
if plugin_suite is not None:
3589
suite.addTest(plugin_suite)
3590
if default_encoding != sys.getdefaultencoding():
3591
bzrlib.trace.warning(
3592
'Plugin "%s" tried to reset default encoding to: %s', name,
3593
sys.getdefaultencoding())
3595
sys.setdefaultencoding(default_encoding)
3598
suite = filter_suite_by_id_startswith(suite, starting_with)
3600
if keep_only is not None:
3601
# Now that the referred modules have loaded their tests, keep only the
3603
suite = filter_suite_by_id_list(suite, id_filter)
3604
# Do some sanity checks on the id_list filtering
3605
not_found, duplicates = suite_matches_id_list(suite, keep_only)
3607
# The tester has used both keep_only and starting_with, so he is
3608
# already aware that some tests are excluded from the list, there
3609
# is no need to tell him which.
3612
# Some tests mentioned in the list are not in the test suite. The
3613
# list may be out of date, report to the tester.
3614
for id in not_found:
3615
bzrlib.trace.warning('"%s" not found in the test suite', id)
3616
for id in duplicates:
3617
bzrlib.trace.warning('"%s" is used as an id by several tests', id)
1369
def adapt_modules(mods_list, adapter, loader, suite):
1370
"""Adapt the modules in mods_list using adapter and add to suite."""
1371
for test in iter_suite_tests(loader.loadTestsFromModuleNames(mods_list)):
1372
suite.addTests(adapter.adapt(test))
3622
def multiply_scenarios(scenarios_left, scenarios_right):
3623
"""Multiply two sets of scenarios.
3625
:returns: the cartesian product of the two sets of scenarios, that is
3626
a scenario for every possible combination of a left scenario and a
3630
('%s,%s' % (left_name, right_name),
3631
dict(left_dict.items() + right_dict.items()))
3632
for left_name, left_dict in scenarios_left
3633
for right_name, right_dict in scenarios_right]
3636
def multiply_tests(tests, scenarios, result):
3637
"""Multiply tests_list by scenarios into result.
3639
This is the core workhorse for test parameterisation.
3641
Typically the load_tests() method for a per-implementation test suite will
3642
call multiply_tests and return the result.
3644
:param tests: The tests to parameterise.
3645
:param scenarios: The scenarios to apply: pairs of (scenario_name,
3646
scenario_param_dict).
3647
:param result: A TestSuite to add created tests to.
3649
This returns the passed in result TestSuite with the cross product of all
3650
the tests repeated once for each scenario. Each test is adapted by adding
3651
the scenario name at the end of its id(), and updating the test object's
3652
__dict__ with the scenario_param_dict.
3654
>>> import bzrlib.tests.test_sampler
3655
>>> r = multiply_tests(
3656
... bzrlib.tests.test_sampler.DemoTest('test_nothing'),
3657
... [('one', dict(param=1)),
3658
... ('two', dict(param=2))],
3660
>>> tests = list(iter_suite_tests(r))
3664
'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
3670
for test in iter_suite_tests(tests):
3671
apply_scenarios(test, scenarios, result)
3675
def apply_scenarios(test, scenarios, result):
3676
"""Apply the scenarios in scenarios to test and add to result.
3678
:param test: The test to apply scenarios to.
3679
:param scenarios: An iterable of scenarios to apply to test.
3681
:seealso: apply_scenario
3683
for scenario in scenarios:
3684
result.addTest(apply_scenario(test, scenario))
3688
def apply_scenario(test, scenario):
3689
"""Copy test and apply scenario to it.
3691
:param test: A test to adapt.
3692
:param scenario: A tuple describing the scenarion.
3693
The first element of the tuple is the new test id.
3694
The second element is a dict containing attributes to set on the
3696
:return: The adapted test.
3698
new_id = "%s(%s)" % (test.id(), scenario[0])
3699
new_test = clone_test(test, new_id)
3700
for name, value in scenario[1].items():
3701
setattr(new_test, name, value)
3705
def clone_test(test, new_id):
3706
"""Clone a test giving it a new id.
3708
:param test: The test to clone.
3709
:param new_id: The id to assign to it.
3710
:return: The new test.
3712
from copy import deepcopy
3713
new_test = deepcopy(test)
3714
new_test.id = lambda: new_id
3718
def _rmtree_temp_dir(dirname):
3719
# If LANG=C we probably have created some bogus paths
3720
# which rmtree(unicode) will fail to delete
3721
# so make sure we are using rmtree(str) to delete everything
3722
# except on win32, where rmtree(str) will fail
3723
# since it doesn't have the property of byte-stream paths
3724
# (they are either ascii or mbcs)
3725
if sys.platform == 'win32':
3726
# make sure we are using the unicode win32 api
3727
dirname = unicode(dirname)
3729
dirname = dirname.encode(sys.getfilesystemencoding())
3731
osutils.rmtree(dirname)
3733
if sys.platform == 'win32' and e.errno == errno.EACCES:
3734
sys.stderr.write('Permission denied: '
3735
'unable to remove testing dir '
3737
% (os.path.basename(dirname), e))
3742
class Feature(object):
3743
"""An operating system Feature."""
3746
self._available = None
3748
def available(self):
3749
"""Is the feature available?
3751
:return: True if the feature is available.
3753
if self._available is None:
3754
self._available = self._probe()
3755
return self._available
3758
"""Implement this method in concrete features.
3760
:return: True if the feature is available.
3762
raise NotImplementedError
3765
if getattr(self, 'feature_name', None):
3766
return self.feature_name()
3767
return self.__class__.__name__
3770
class _SymlinkFeature(Feature):
3773
return osutils.has_symlinks()
3775
def feature_name(self):
3778
SymlinkFeature = _SymlinkFeature()
3781
class _HardlinkFeature(Feature):
3784
return osutils.has_hardlinks()
3786
def feature_name(self):
3789
HardlinkFeature = _HardlinkFeature()
3792
class _OsFifoFeature(Feature):
3795
return getattr(os, 'mkfifo', None)
3797
def feature_name(self):
3798
return 'filesystem fifos'
3800
OsFifoFeature = _OsFifoFeature()
3803
class _UnicodeFilenameFeature(Feature):
3804
"""Does the filesystem support Unicode filenames?"""
3808
# Check for character combinations unlikely to be covered by any
3809
# single non-unicode encoding. We use the characters
3810
# - greek small letter alpha (U+03B1) and
3811
# - braille pattern dots-123456 (U+283F).
3812
os.stat(u'\u03b1\u283f')
3813
except UnicodeEncodeError:
3815
except (IOError, OSError):
3816
# The filesystem allows the Unicode filename but the file doesn't
3820
# The filesystem allows the Unicode filename and the file exists,
3824
UnicodeFilenameFeature = _UnicodeFilenameFeature()
3827
def probe_unicode_in_user_encoding():
3828
"""Try to encode several unicode strings to use in unicode-aware tests.
3829
Return first successfull match.
3831
:return: (unicode value, encoded plain string value) or (None, None)
3833
possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
3834
for uni_val in possible_vals:
3836
str_val = uni_val.encode(osutils.get_user_encoding())
3837
except UnicodeEncodeError:
3838
# Try a different character
3841
return uni_val, str_val
3845
def probe_bad_non_ascii(encoding):
3846
"""Try to find [bad] character with code [128..255]
3847
that cannot be decoded to unicode in some encoding.
3848
Return None if all non-ascii characters is valid
3851
for i in xrange(128, 256):
3854
char.decode(encoding)
3855
except UnicodeDecodeError:
3860
class _HTTPSServerFeature(Feature):
3861
"""Some tests want an https Server, check if one is available.
3863
Right now, the only way this is available is under python2.6 which provides
3874
def feature_name(self):
3875
return 'HTTPSServer'
3878
HTTPSServerFeature = _HTTPSServerFeature()
3881
class _UnicodeFilename(Feature):
3882
"""Does the filesystem support Unicode filenames?"""
3887
except UnicodeEncodeError:
3889
except (IOError, OSError):
3890
# The filesystem allows the Unicode filename but the file doesn't
3894
# The filesystem allows the Unicode filename and the file exists,
3898
UnicodeFilename = _UnicodeFilename()
3901
class _UTF8Filesystem(Feature):
3902
"""Is the filesystem UTF-8?"""
3905
if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
3909
UTF8Filesystem = _UTF8Filesystem()
3912
class _CaseInsCasePresFilenameFeature(Feature):
3913
"""Is the file-system case insensitive, but case-preserving?"""
3916
fileno, name = tempfile.mkstemp(prefix='MixedCase')
3918
# first check truly case-preserving for created files, then check
3919
# case insensitive when opening existing files.
3920
name = osutils.normpath(name)
3921
base, rel = osutils.split(name)
3922
found_rel = osutils.canonical_relpath(base, name)
3923
return (found_rel == rel
3924
and os.path.isfile(name.upper())
3925
and os.path.isfile(name.lower()))
3930
def feature_name(self):
3931
return "case-insensitive case-preserving filesystem"
3933
CaseInsCasePresFilenameFeature = _CaseInsCasePresFilenameFeature()
3936
class _CaseInsensitiveFilesystemFeature(Feature):
3937
"""Check if underlying filesystem is case-insensitive but *not* case
3940
# Note that on Windows, Cygwin, MacOS etc, the file-systems are far
3941
# more likely to be case preserving, so this case is rare.
3944
if CaseInsCasePresFilenameFeature.available():
3947
if TestCaseWithMemoryTransport.TEST_ROOT is None:
3948
root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
3949
TestCaseWithMemoryTransport.TEST_ROOT = root
3951
root = TestCaseWithMemoryTransport.TEST_ROOT
3952
tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
3954
name_a = osutils.pathjoin(tdir, 'a')
3955
name_A = osutils.pathjoin(tdir, 'A')
3957
result = osutils.isdir(name_A)
3958
_rmtree_temp_dir(tdir)
3961
def feature_name(self):
3962
return 'case-insensitive filesystem'
3964
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
3967
class _SubUnitFeature(Feature):
3968
"""Check if subunit is available."""
3977
def feature_name(self):
3980
SubUnitFeature = _SubUnitFeature()
3981
# Only define SubUnitBzrRunner if subunit is available.
3983
from subunit import TestProtocolClient
3984
class SubUnitBzrRunner(TextTestRunner):
3985
def run(self, test):
3986
result = TestProtocolClient(self.stream)