1
# Copyright (C) 2005 by Canonical Ltd
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
11
# GNU General Public License for more details.
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
# TODO: Perhaps there should be an API to find out if bzr running under the
19
# test suite -- some plugins might want to avoid making intrusive changes if
20
# this is the case. However, we want behaviour under to test to diverge as
21
# little as possible, so this should be used rarely if it's added at all.
22
# (Suggestion from j-a-meinel, 2005-11-24)
24
# NOTE: Some classes in here use camelCaseNaming() rather than
25
# underscore_naming(). That's for consistency with unittest; it's not the
26
# general style of bzrlib. Please continue that consistency when adding e.g.
27
# new assertFoo() methods.
31
from cStringIO import StringIO
38
from pprint import pformat
43
from subprocess import Popen, PIPE, STDOUT
25
from testsweet import run_suite
26
68
import bzrlib.commands
69
import bzrlib.timestamp
71
import bzrlib.inventory
72
import bzrlib.iterablefile
77
# lsprof not available
79
from bzrlib.merge import merge_inner
82
from bzrlib.smart import client, request, server
84
from bzrlib import symbol_versioning
85
from bzrlib.symbol_versioning import (
28
91
import bzrlib.trace
33
MODULES_TO_DOCTEST = []
35
from logging import debug, warning, error
92
from bzrlib.transport import get_transport
93
import bzrlib.transport
94
from bzrlib.transport.local import LocalURLServer
95
from bzrlib.transport.memory import MemoryServer
96
from bzrlib.transport.readonly import ReadonlyServer
97
from bzrlib.trace import mutter, note
98
from bzrlib.tests import TestUtil
99
from bzrlib.tests.http_server import HttpServer
100
from bzrlib.tests.TestUtil import (
104
from bzrlib.tests.treeshape import build_tree_contents
105
import bzrlib.version_info_formats.format_custom
106
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
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.
134
def __init__(self, stream, descriptions, verbosity,
139
"""Construct new TestResult.
141
:param bench_history: Optionally, a writable file object to accumulate
144
unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
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):
188
"""Add a benchmark time for the current test case."""
189
return getattr(testCase, "_benchtime", None)
191
def _elapsedTestTimeString(self):
192
"""Return a time string for the overall time the current test has taken."""
193
return self._formatTime(time.time() - self._start_time)
195
def _testTimeString(self, testCase):
196
benchmark_time = self._extractBenchmarkTime(testCase)
197
if benchmark_time is not None:
199
self._formatTime(benchmark_time),
200
self._elapsedTestTimeString())
202
return " %s" % self._elapsedTestTimeString()
204
def _formatTime(self, seconds):
205
"""Format seconds as milliseconds with leading spaces."""
206
# some benchmarks can take thousands of seconds to run, so we need 8
208
return "%8dms" % (1000 * seconds)
210
def _shortened_test_description(self, test):
212
what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
215
def startTest(self, test):
216
unittest.TestResult.startTest(self, test)
219
self.report_test_start(test)
220
test.number = self.count
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')
234
def _recordTestStartTime(self):
235
"""Record that a test has started."""
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:
245
def addError(self, test, err):
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)
264
def addFailure(self, test, err):
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)
281
def addSuccess(self, test):
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)
295
unittest.TestResult.addSuccess(self, test)
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)
333
except KeyboardInterrupt:
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 :)
340
unittest.TestResult.addSuccess(self, test)
341
test._log_contents = ''
343
def printErrorList(self, flavour, errors):
344
for test, err in errors:
345
self.stream.writeln(self.separator1)
346
self.stream.write("%s: " % flavour)
347
self.stream.writeln(self.getDescription(test))
348
if getattr(test, '_get_log', None) is not None:
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')
358
self.stream.writeln(self.separator2)
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))
539
class TextTestRunner(object):
540
stop_on_failure = False
550
self.stream = unittest._WritelnDecorator(stream)
551
self.descriptions = descriptions
552
self.verbosity = verbosity
553
self._bench_history = bench_history
554
self.list_only = list_only
555
self._strict = strict
558
"Run the given test case or test suite."
559
startTime = time.time()
560
if self.verbosity == 1:
561
result_class = TextTestResult
562
elif self.verbosity >= 2:
563
result_class = VerboseTestResult
564
result = result_class(self.stream,
567
bench_history=self._bench_history,
568
num_tests=test.countTestCases(),
571
result.stop_early = self.stop_on_failure
572
result.report_starting()
574
if self.verbosity >= 2:
575
self.stream.writeln("Listing tests only ...\n")
577
for t in iter_suite_tests(test):
578
self.stream.writeln("%s" % (t.id()))
587
if isinstance(test, testtools.ConcurrentTestSuite):
588
# We need to catch bzr specific behaviors
589
test.run(BZRTransformingResult(result))
592
run = result.testsRun
594
stopTime = time.time()
595
timeTaken = stopTime - startTime
597
self.stream.writeln(result.separator2)
598
self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
599
run, run != 1 and "s" or "", timeTaken))
600
self.stream.writeln()
601
if not result.wasSuccessful():
602
self.stream.write("FAILED (")
603
failed, errored = map(len, (result.failures, result.errors))
605
self.stream.write("failures=%d" % failed)
607
if failed: self.stream.write(", ")
608
self.stream.write("errors=%d" % errored)
609
if result.known_failure_count:
610
if failed or errored: self.stream.write(", ")
611
self.stream.write("known_failure_count=%d" %
612
result.known_failure_count)
613
self.stream.writeln(")")
615
if result.known_failure_count:
616
self.stream.writeln("OK (known_failures=%d)" %
617
result.known_failure_count)
619
self.stream.writeln("OK")
620
if result.skip_count > 0:
621
skipped = result.skip_count
622
self.stream.writeln('%d test%s skipped' %
623
(skipped, skipped != 1 and "s" or ""))
624
if result.unsupported:
625
for feature, count in sorted(result.unsupported.items()):
626
self.stream.writeln("Missing feature '%s' skipped %d tests." %
632
def iter_suite_tests(suite):
633
"""Return all tests in a suite, recursing through nested suites"""
634
if isinstance(suite, unittest.TestCase):
636
elif isinstance(suite, unittest.TestSuite):
638
for r in iter_suite_tests(item):
641
raise Exception('unknown type %r for object %r'
642
% (type(suite), suite))
645
class TestSkipped(Exception):
646
"""Indicates that a test was intentionally skipped, rather than failing."""
649
class TestNotApplicable(TestSkipped):
650
"""A test is not applicable to the situation where it was run.
652
This is only normally raised by parameterized tests, if they find that
653
the instance they're constructed upon does not support one aspect
658
class KnownFailure(AssertionError):
659
"""Indicates that a test failed in a precisely expected manner.
661
Such failures dont block the whole test suite from passing because they are
662
indicators of partially completed code or of future work. We have an
663
explicit error for them so that we can ensure that they are always visible:
664
KnownFailures are always shown in the output of bzr selftest.
668
class UnavailableFeature(Exception):
669
"""A feature required for this test was not available.
671
The feature should be used to construct the exception.
37
675
class CommandFailed(Exception):
679
class StringIOWrapper(object):
680
"""A wrapper around cStringIO which just adds an encoding attribute.
682
Internally we can check sys.stdout to see what the output encoding
683
should be. However, cStringIO has no encoding attribute that we can
684
set. So we wrap it instead.
689
def __init__(self, s=None):
691
self.__dict__['_cstring'] = StringIO(s)
693
self.__dict__['_cstring'] = StringIO()
695
def __getattr__(self, name, getattr=getattr):
696
return getattr(self.__dict__['_cstring'], name)
698
def __setattr__(self, name, val):
699
if name == 'encoding':
700
self.__dict__['encoding'] = val
702
return setattr(self._cstring, name, val)
705
class TestUIFactory(ui.CLIUIFactory):
706
"""A UI Factory for testing.
708
Hide the progress bar but emit note()s.
710
Allows get_password to be tested without real tty attached.
713
def __init__(self, stdout=None, stderr=None, stdin=None):
714
if stdin is not None:
715
# We use a StringIOWrapper to be able to test various
716
# encodings, but the user is still responsible to
717
# encode the string and to set the encoding attribute
718
# of StringIOWrapper.
719
stdin = StringIOWrapper(stdin)
720
super(TestUIFactory, self).__init__(stdin, stdout, stderr)
723
"""See progress.ProgressBar.clear()."""
725
def clear_term(self):
726
"""See progress.ProgressBar.clear_term()."""
729
"""See progress.ProgressBar.finished()."""
731
def note(self, fmt_string, *args):
732
"""See progress.ProgressBar.note()."""
734
fmt_string = fmt_string % args
735
self.stdout.write(fmt_string + "\n")
737
def progress_bar(self):
740
def nested_progress_bar(self):
743
def update(self, message, count=None, total=None):
744
"""See progress.ProgressBar.update()."""
746
def get_non_echoed_password(self):
747
"""Get password from stdin without trying to handle the echo mode"""
748
password = self.stdin.readline()
751
if password[-1] == '\n':
752
password = password[:-1]
40
756
class TestCase(unittest.TestCase):
41
757
"""Base class for bzr unit tests.
43
Tests that need access to disk resources should subclass
759
Tests that need access to disk resources should subclass
44
760
TestCaseInTempDir not TestCase.
46
762
Error and debug log messages are redirected from their usual
47
763
location into a temporary file, the contents of which can be
48
retrieved by _get_log().
764
retrieved by _get_log(). We use a real OS file, not an in-memory object,
765
so that it can also capture file IO. When the test completes this file
766
is read into memory and removed from disk.
50
768
There are also convenience functions to invoke bzr's command-line
51
routine, and to build and check bzr trees."""
769
routine, and to build and check bzr trees.
771
In addition to the usual method of overriding tearDown(), this class also
772
allows subclasses to register functions into the _cleanups list, which is
773
run in order as the object is torn down. It's less likely this will be
774
accidentally overlooked.
777
_active_threads = None
778
_leaking_threads_tests = 0
779
_first_thread_leaker_id = None
780
_log_file_name = None
782
_keep_log_file = False
783
# record lsprof data when performing benchmark calls.
784
_gather_lsprof_in_benchmarks = False
785
attrs_to_keep = ('id', '_testMethodName', '_testMethodDoc',
786
'_log_contents', '_log_file_name', '_benchtime',
787
'_TestCase__testMethodName', '_TestCase__testMethodDoc',)
789
def __init__(self, methodName='testMethod'):
790
super(TestCase, self).__init__(methodName)
792
self._bzr_test_setUp_run = False
793
self._bzr_test_tearDown_run = False
56
# this replaces the default testsweet.TestCase; we don't want logging changed
57
796
unittest.TestCase.setUp(self)
58
bzrlib.trace.disable_default_logging()
59
self._enable_file_logging()
62
def _enable_file_logging(self):
797
self._bzr_test_setUp_run = True
798
self._cleanEnvironment()
801
self._benchcalls = []
802
self._benchtime = None
804
# Track locks - needs to be called before _clear_debug_flags.
806
self._clear_debug_flags()
807
TestCase._active_threads = threading.activeCount()
808
self.addCleanup(self._check_leaked_threads)
813
pdb.Pdb().set_trace(sys._getframe().f_back)
815
def _check_leaked_threads(self):
816
active = threading.activeCount()
817
leaked_threads = active - TestCase._active_threads
818
TestCase._active_threads = active
820
TestCase._leaking_threads_tests += 1
821
if TestCase._first_thread_leaker_id is None:
822
TestCase._first_thread_leaker_id = self.id()
824
def _clear_debug_flags(self):
825
"""Prevent externally set debug flags affecting tests.
827
Tests that want to use debug flags can just set them in the
828
debug_flags set during setup/teardown.
830
self._preserved_debug_flags = set(debug.debug_flags)
831
if 'allow_debug' not in selftest_debug_flags:
832
debug.debug_flags.clear()
833
self.addCleanup(self._restore_debug_flags)
835
def _clear_hooks(self):
836
# prevent hooks affecting tests
837
self._preserved_hooks = {}
838
for key, factory in hooks.known_hooks.items():
839
parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
840
current_hooks = hooks.known_hooks_key_to_object(key)
841
self._preserved_hooks[parent] = (name, current_hooks)
842
self.addCleanup(self._restoreHooks)
843
for key, factory in hooks.known_hooks.items():
844
parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
845
setattr(parent, name, factory())
846
# this hook should always be installed
847
request._install_hook()
849
def _silenceUI(self):
850
"""Turn off UI for duration of test"""
851
# by default the UI is off; tests can turn it on if they want it.
852
saved = ui.ui_factory
854
ui.ui_factory = saved
855
ui.ui_factory = ui.SilentUIFactory()
856
self.addCleanup(_restore)
858
def _check_locks(self):
859
"""Check that all lock take/release actions have been paired."""
860
# once we have fixed all the current lock problems, we can change the
861
# following code to always check for mismatched locks, but only do
862
# traceback showing with -Dlock (self._lock_check_thorough is True).
863
# For now, because the test suite will fail, we only assert that lock
864
# matching has occured with -Dlock.
866
acquired_locks = [lock for action, lock in self._lock_actions
867
if action == 'acquired']
868
released_locks = [lock for action, lock in self._lock_actions
869
if action == 'released']
870
broken_locks = [lock for action, lock in self._lock_actions
871
if action == 'broken']
872
# trivially, given the tests for lock acquistion and release, if we
873
# have as many in each list, it should be ok. Some lock tests also
874
# break some locks on purpose and should be taken into account by
875
# considering that breaking a lock is just a dirty way of releasing it.
876
if len(acquired_locks) != (len(released_locks) + len(broken_locks)):
877
message = ('Different number of acquired and '
878
'released or broken locks. (%s, %s + %s)' %
879
(acquired_locks, released_locks, broken_locks))
880
if not self._lock_check_thorough:
881
# Rather than fail, just warn
882
print "Broken test %s: %s" % (self, message)
886
def _track_locks(self):
887
"""Track lock activity during tests."""
888
self._lock_actions = []
889
self._lock_check_thorough = 'lock' not in debug.debug_flags
890
self.addCleanup(self._check_locks)
891
_mod_lock.Lock.hooks.install_named_hook('lock_acquired',
892
self._lock_acquired, None)
893
_mod_lock.Lock.hooks.install_named_hook('lock_released',
894
self._lock_released, None)
895
_mod_lock.Lock.hooks.install_named_hook('lock_broken',
896
self._lock_broken, None)
898
def _lock_acquired(self, result):
899
self._lock_actions.append(('acquired', result))
901
def _lock_released(self, result):
902
self._lock_actions.append(('released', result))
904
def _lock_broken(self, result):
905
self._lock_actions.append(('broken', result))
907
def _ndiff_strings(self, a, b):
908
"""Return ndiff between two strings containing lines.
910
A trailing newline is added if missing to make the strings
912
if b and b[-1] != '\n':
914
if a and a[-1] != '\n':
916
difflines = difflib.ndiff(a.splitlines(True),
918
linejunk=lambda x: False,
919
charjunk=lambda x: False)
920
return ''.join(difflines)
922
def assertEqual(self, a, b, message=''):
926
except UnicodeError, e:
927
# If we can't compare without getting a UnicodeError, then
928
# obviously they are different
929
mutter('UnicodeError: %s', e)
932
raise AssertionError("%snot equal:\na = %s\nb = %s\n"
934
pformat(a), pformat(b)))
936
assertEquals = assertEqual
938
def assertEqualDiff(self, a, b, message=None):
939
"""Assert two texts are equal, if not raise an exception.
941
This is intended for use with multi-line strings where it can
942
be hard to find the differences by eye.
944
# TODO: perhaps override assertEquals to call this for strings?
948
message = "texts not equal:\n"
950
message = 'first string is missing a final newline.\n'
952
message = 'second string is missing a final newline.\n'
953
raise AssertionError(message +
954
self._ndiff_strings(a, b))
956
def assertEqualMode(self, mode, mode_test):
957
self.assertEqual(mode, mode_test,
958
'mode mismatch %o != %o' % (mode, mode_test))
960
def assertEqualStat(self, expected, actual):
961
"""assert that expected and actual are the same stat result.
963
:param expected: A stat result.
964
:param actual: A stat result.
965
:raises AssertionError: If the expected and actual stat values differ
968
self.assertEqual(expected.st_size, actual.st_size)
969
self.assertEqual(expected.st_mtime, actual.st_mtime)
970
self.assertEqual(expected.st_ctime, actual.st_ctime)
971
self.assertEqual(expected.st_dev, actual.st_dev)
972
self.assertEqual(expected.st_ino, actual.st_ino)
973
self.assertEqual(expected.st_mode, actual.st_mode)
975
def assertLength(self, length, obj_with_len):
976
"""Assert that obj_with_len is of length length."""
977
if len(obj_with_len) != length:
978
self.fail("Incorrect length: wanted %d, got %d for %r" % (
979
length, len(obj_with_len), obj_with_len))
981
def assertPositive(self, val):
982
"""Assert that val is greater than 0."""
983
self.assertTrue(val > 0, 'expected a positive value, but got %s' % val)
985
def assertNegative(self, val):
986
"""Assert that val is less than 0."""
987
self.assertTrue(val < 0, 'expected a negative value, but got %s' % val)
989
def assertStartsWith(self, s, prefix):
990
if not s.startswith(prefix):
991
raise AssertionError('string %r does not start with %r' % (s, prefix))
993
def assertEndsWith(self, s, suffix):
994
"""Asserts that s ends with suffix."""
995
if not s.endswith(suffix):
996
raise AssertionError('string %r does not end with %r' % (s, suffix))
998
def assertContainsRe(self, haystack, needle_re, flags=0):
999
"""Assert that a contains something matching a regular expression."""
1000
if not re.search(needle_re, haystack, flags):
1001
if '\n' in haystack or len(haystack) > 60:
1002
# a long string, format it in a more readable way
1003
raise AssertionError(
1004
'pattern "%s" not found in\n"""\\\n%s"""\n'
1005
% (needle_re, haystack))
1007
raise AssertionError('pattern "%s" not found in "%s"'
1008
% (needle_re, haystack))
1010
def assertNotContainsRe(self, haystack, needle_re, flags=0):
1011
"""Assert that a does not match a regular expression"""
1012
if re.search(needle_re, haystack, flags):
1013
raise AssertionError('pattern "%s" found in "%s"'
1014
% (needle_re, haystack))
1016
def assertSubset(self, sublist, superlist):
1017
"""Assert that every entry in sublist is present in superlist."""
1018
missing = set(sublist) - set(superlist)
1019
if len(missing) > 0:
1020
raise AssertionError("value(s) %r not present in container %r" %
1021
(missing, superlist))
1023
def assertListRaises(self, excClass, func, *args, **kwargs):
1024
"""Fail unless excClass is raised when the iterator from func is used.
1026
Many functions can return generators this makes sure
1027
to wrap them in a list() call to make sure the whole generator
1028
is run, and that the proper exception is raised.
1031
list(func(*args, **kwargs))
1035
if getattr(excClass,'__name__', None) is not None:
1036
excName = excClass.__name__
1038
excName = str(excClass)
1039
raise self.failureException, "%s not raised" % excName
1041
def assertRaises(self, excClass, callableObj, *args, **kwargs):
1042
"""Assert that a callable raises a particular exception.
1044
:param excClass: As for the except statement, this may be either an
1045
exception class, or a tuple of classes.
1046
:param callableObj: A callable, will be passed ``*args`` and
1049
Returns the exception so that you can examine it.
1052
callableObj(*args, **kwargs)
1056
if getattr(excClass,'__name__', None) is not None:
1057
excName = excClass.__name__
1060
excName = str(excClass)
1061
raise self.failureException, "%s not raised" % excName
1063
def assertIs(self, left, right, message=None):
1064
if not (left is right):
1065
if message is not None:
1066
raise AssertionError(message)
1068
raise AssertionError("%r is not %r." % (left, right))
1070
def assertIsNot(self, left, right, message=None):
1072
if message is not None:
1073
raise AssertionError(message)
1075
raise AssertionError("%r is %r." % (left, right))
1077
def assertTransportMode(self, transport, path, mode):
1078
"""Fail if a path does not have mode "mode".
1080
If modes are not supported on this transport, the assertion is ignored.
1082
if not transport._can_roundtrip_unix_modebits():
1084
path_stat = transport.stat(path)
1085
actual_mode = stat.S_IMODE(path_stat.st_mode)
1086
self.assertEqual(mode, actual_mode,
1087
'mode of %r incorrect (%s != %s)'
1088
% (path, oct(mode), oct(actual_mode)))
1090
def assertIsSameRealPath(self, path1, path2):
1091
"""Fail if path1 and path2 points to different files"""
1092
self.assertEqual(osutils.realpath(path1),
1093
osutils.realpath(path2),
1094
"apparent paths:\na = %s\nb = %s\n," % (path1, path2))
1096
def assertIsInstance(self, obj, kls):
1097
"""Fail if obj is not an instance of kls"""
1098
if not isinstance(obj, kls):
1099
self.fail("%r is an instance of %s rather than %s" % (
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)
1276
def _startLogFile(self):
1277
"""Send bzr and test log messages to a temporary file.
1279
The file is removed as the test is torn down.
63
1281
fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
65
1282
self._log_file = os.fdopen(fileno, 'w+')
67
hdlr = logging.StreamHandler(self._log_file)
68
hdlr.setLevel(logging.DEBUG)
69
hdlr.setFormatter(logging.Formatter('%(levelname)8s %(message)s'))
70
logging.getLogger('').addHandler(hdlr)
71
logging.getLogger('').setLevel(logging.DEBUG)
73
debug('opened log file %s', name)
1283
self._log_memento = bzrlib.trace.push_log_file(self._log_file)
75
1284
self._log_file_name = name
79
logging.getLogger('').removeHandler(self._log_hdlr)
80
bzrlib.trace.enable_default_logging()
81
logging.debug('%s teardown', self.id())
1285
self.addCleanup(self._finishLogFile)
1287
def _finishLogFile(self):
1288
"""Finished with the log file.
1290
Close the file and delete it, unless setKeepLogfile was called.
1292
if self._log_file is None:
1294
bzrlib.trace.pop_log_file(self._log_memento)
82
1295
self._log_file.close()
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):
1306
"""Arrange to run a callable when this case is torn down.
1308
Callables are run in the reverse of the order they are registered,
1309
ie last-in first-out.
1311
self._cleanups.append((callable, args, kwargs))
1313
def _cleanEnvironment(self):
1315
'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
1316
'HOME': 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
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,
1347
self.addCleanup(self._restoreEnvironment)
1348
for name, value in new_env.iteritems():
1349
self._captureVar(name, value)
1351
def _captureVar(self, name, newvalue):
1352
"""Set an environment variable, and reset it when finished."""
1353
self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
1355
def _restore_debug_flags(self):
1356
debug.debug_flags.clear()
1357
debug.debug_flags.update(self._preserved_debug_flags)
1359
def _restoreEnvironment(self):
1360
for name, value in self.__old_env.iteritems():
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
1469
self._log_contents = ''
1470
self._bzr_test_tearDown_run = True
83
1471
unittest.TestCase.tearDown(self)
1473
def time(self, callable, *args, **kwargs):
1474
"""Run callable and accrue the time it takes to the benchmark time.
1476
If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
1477
this will cause lsprofile statistics to be gathered and stored in
1480
if self._benchtime is None:
1484
if not self._gather_lsprof_in_benchmarks:
1485
return callable(*args, **kwargs)
1487
# record this benchmark
1488
ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
1490
self._benchcalls.append(((callable, args, kwargs), stats))
1493
self._benchtime += time.time() - start
1495
def _runCleanups(self):
1496
"""Run registered cleanup functions.
1498
This should only be called from TestCase.tearDown.
1500
# TODO: Perhaps this should keep running cleanups even if
1501
# one of them fails?
1503
# Actually pop the cleanups from the list so tearDown running
1504
# twice is safe (this happens for skipped tests).
1505
while self._cleanups:
1506
cleanup, args, kwargs = self._cleanups.pop()
1507
cleanup(*args, **kwargs)
86
1509
def log(self, *args):
90
"""Return as a string the log for this test"""
91
return open(self._log_file_name).read()
93
def run_bzr(self, *args, **kwargs):
1512
def _get_log(self, keep_log_file=False):
1513
"""Get the log from bzrlib.trace calls from this test.
1515
:param keep_log_file: When True, if the log is still a file on disk
1516
leave it as a file on disk. When False, if the log is still a file
1517
on disk, the log file is deleted and the log preserved as
1519
:return: A string containing the log.
1521
# flush the log file, to get all content
1523
if bzrlib.trace._trace_file:
1524
bzrlib.trace._trace_file.flush()
1525
if self._log_contents:
1526
# XXX: this can hardly contain the content flushed above --vila
1528
return self._log_contents
1529
if self._log_file_name is not None:
1530
logfile = open(self._log_file_name)
1532
log_contents = logfile.read()
1535
if not keep_log_file:
1536
self._log_contents = log_contents
1538
os.remove(self._log_file_name)
1540
if sys.platform == 'win32' and e.errno == errno.EACCES:
1541
sys.stderr.write(('Unable to delete log file '
1542
' %r\n' % self._log_file_name))
1547
return "DELETED log file to reduce memory footprint"
1549
def requireFeature(self, feature):
1550
"""This test requires a specific feature is available.
1552
:raises UnavailableFeature: When feature is not available.
1554
if not feature.available():
1555
raise UnavailableFeature(feature)
1557
def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
1559
"""Run bazaar command line, splitting up a string command line."""
1560
if isinstance(args, basestring):
1561
# shlex don't understand unicode strings,
1562
# so args should be plain string (bialix 20070906)
1563
args = list(shlex.split(str(args)))
1564
return self._run_bzr_core(args, retcode=retcode,
1565
encoding=encoding, stdin=stdin, working_dir=working_dir,
1568
def _run_bzr_core(self, args, retcode, encoding, stdin,
1570
if encoding is None:
1571
encoding = osutils.get_user_encoding()
1572
stdout = StringIOWrapper()
1573
stderr = StringIOWrapper()
1574
stdout.encoding = encoding
1575
stderr.encoding = encoding
1577
self.log('run bzr: %r', args)
1578
# FIXME: don't call into logging here
1579
handler = logging.StreamHandler(stderr)
1580
handler.setLevel(logging.INFO)
1581
logger = logging.getLogger('')
1582
logger.addHandler(handler)
1583
old_ui_factory = ui.ui_factory
1584
ui.ui_factory = TestUIFactory(stdin=stdin, stdout=stdout, stderr=stderr)
1587
if working_dir is not None:
1588
cwd = osutils.getcwd()
1589
os.chdir(working_dir)
1592
result = self.apply_redirected(ui.ui_factory.stdin,
1594
bzrlib.commands.run_bzr_catch_user_errors,
1597
logger.removeHandler(handler)
1598
ui.ui_factory = old_ui_factory
1602
out = stdout.getvalue()
1603
err = stderr.getvalue()
1605
self.log('output:\n%r', out)
1607
self.log('errors:\n%r', err)
1608
if retcode is not None:
1609
self.assertEquals(retcode, result,
1610
message='Unexpected return code')
1613
def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
1614
working_dir=None, error_regexes=[], output_encoding=None):
94
1615
"""Invoke bzr, as if it were run from the command line.
1617
The argument list should not include the bzr program name - the
1618
first argument is normally the bzr command. Arguments may be
1619
passed in three ways:
1621
1- A list of strings, eg ["commit", "a"]. This is recommended
1622
when the command contains whitespace or metacharacters, or
1623
is built up at run time.
1625
2- A single string, eg "add a". This is the most convenient
1626
for hardcoded commands.
1628
This runs bzr through the interface that catches and reports
1629
errors, and with logging set to something approximating the
1630
default, so that error reporting can be checked.
96
1632
This should be the main method for tests that want to exercise the
97
1633
overall behavior of the bzr application (rather than a unit test
98
1634
or a functional test of the library.)
100
Much of the old code runs bzr by forking a new copy of Python, but
101
that is slower, harder to debug, and generally not necessary.
103
retcode = kwargs.get('retcode', 0)
104
result = self.apply_redirected(None, None, None,
105
bzrlib.commands.run_bzr, args)
106
self.assertEquals(result, retcode)
1636
This sends the stdout/stderr results into the test's log,
1637
where it may be useful for debugging. See also run_captured.
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.
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)
1658
def run_bzr_error(self, error_regexes, *args, **kwargs):
1659
"""Run bzr, and check that stderr contains the supplied regexes
1661
:param error_regexes: Sequence of regular expressions which
1662
must each be found in the error output. The relative ordering
1664
:param args: command-line arguments for bzr
1665
:param kwargs: Keyword arguments which are interpreted by run_bzr
1666
This function changes the default value of retcode to be 3,
1667
since in most cases this is run when you expect bzr to fail.
1669
:return: (out, err) The actual output of running the command (in case
1670
you want to do more inspection)
1674
# Make sure that commit is failing because there is nothing to do
1675
self.run_bzr_error(['no changes to commit'],
1676
['commit', '-m', 'my commit comment'])
1677
# Make sure --strict is handling an unknown file, rather than
1678
# giving us the 'nothing to do' error
1679
self.build_tree(['unknown'])
1680
self.run_bzr_error(['Commit refused because there are unknown files'],
1681
['commit', --strict', '-m', 'my commit comment'])
1683
kwargs.setdefault('retcode', 3)
1684
kwargs['error_regexes'] = error_regexes
1685
out, err = self.run_bzr(*args, **kwargs)
1688
def run_bzr_subprocess(self, *args, **kwargs):
1689
"""Run bzr in a subprocess for testing.
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.
1816
:param retcode: The status code that is expected. Defaults to 0. If
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)
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))
109
1839
def check_inventory_shape(self, inv, shape):
111
Compare an inventory to a list of expected names.
1840
"""Compare an inventory to a list of expected names.
113
1842
Fail if they are not precisely equal.
154
1888
sys.stderr = real_stderr
155
1889
sys.stdin = real_stdin
158
BzrTestBase = TestCase
161
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):
162
2256
"""Derived class that runs a test within a temporary directory.
164
2258
This is useful for tests that need to create a branch, etc.
181
2280
if contents != expect:
182
2281
self.log("expected: %r" % expect)
183
2282
self.log("actually: %r" % contents)
184
self.fail("contents of %s not as expected")
186
def _make_test_root(self):
191
if TestCaseInTempDir.TEST_ROOT is not None:
193
TestCaseInTempDir.TEST_ROOT = os.path.abspath(
194
tempfile.mkdtemp(suffix='.tmp',
195
prefix=self._TEST_NAME + '-',
198
# make a fake bzr directory there to prevent any tests propagating
199
# up onto the source directory's real branch
200
os.mkdir(os.path.join(TestCaseInTempDir.TEST_ROOT, '.bzr'))
203
super(TestCaseInTempDir, self).setUp()
205
self._make_test_root()
206
self._currentdir = os.getcwdu()
207
short_id = self.id().replace('bzrlib.selftest.', '')
208
self.test_dir = os.path.join(self.TEST_ROOT, short_id)
2283
self.fail("contents of %s not as expected" % filename)
2285
def _getTestDirPrefix(self):
2286
# create a directory within the top level test directory
2287
if sys.platform == 'win32':
2288
name_prefix = re.sub('[<>*=+",:;_/\\-]', '_', self.id())
2289
# windows is likely to have path-length limits so use a short name
2290
name_prefix = name_prefix[-30:]
2292
name_prefix = re.sub('[/]', '_', self.id())
2295
def makeAndChdirToTestDir(self):
2296
"""See TestCaseWithMemoryTransport.makeAndChdirToTestDir().
2298
For TestCaseInTempDir we create a temporary directory based on the test
2299
name and then create two subdirs - test and home under it.
2301
name_prefix = osutils.pathjoin(TestCaseWithMemoryTransport.TEST_ROOT,
2302
self._getTestDirPrefix())
2304
for i in range(100):
2305
if os.path.exists(name):
2306
name = name_prefix + '_' + str(i)
2310
# now create test and home directories within this dir
2311
self.test_base_dir = name
2312
self.test_home_dir = self.test_base_dir + '/home'
2313
os.mkdir(self.test_home_dir)
2314
self.test_dir = self.test_base_dir + '/work'
209
2315
os.mkdir(self.test_dir)
210
2316
os.chdir(self.test_dir)
214
os.chdir(self._currentdir)
215
super(TestCaseInTempDir, self).tearDown()
217
def _formcmd(self, cmd):
218
if isinstance(cmd, basestring):
221
cmd[0] = self.BZRPATH
222
if self.OVERRIDE_PYTHON:
223
cmd.insert(0, self.OVERRIDE_PYTHON)
224
self.log('$ %r' % cmd)
227
def runcmd(self, cmd, retcode=0):
228
"""Run one command and check the return code.
230
Returns a tuple of (stdout,stderr) strings.
232
If a single string is based, it is split into words.
233
For commands that are not simple space-separated words, please
234
pass a list instead."""
235
cmd = self._formcmd(cmd)
236
self.log('$ ' + ' '.join(cmd))
237
actual_retcode = subprocess.call(cmd, stdout=self._log_file,
238
stderr=self._log_file)
239
if retcode != actual_retcode:
240
raise CommandFailed("test failed: %r returned %d, expected %d"
241
% (cmd, actual_retcode, retcode))
243
def backtick(self, cmd, retcode=0):
244
"""Run a command and return its output"""
245
cmd = self._formcmd(cmd)
246
child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=self._log_file)
247
outd, errd = child.communicate()
249
actual_retcode = child.wait()
251
outd = outd.replace('\r', '')
253
if retcode != actual_retcode:
254
raise CommandFailed("test failed: %r returned %d, expected %d"
255
% (cmd, actual_retcode, retcode))
261
def build_tree(self, shape):
2317
# put name of test inside
2318
f = file(self.test_base_dir + '/name', 'w')
2323
self.addCleanup(self.deleteTestDir)
2325
def deleteTestDir(self):
2326
os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2327
_rmtree_temp_dir(self.test_base_dir)
2329
def build_tree(self, shape, line_endings='binary', transport=None):
262
2330
"""Build a test tree according to a pattern.
264
2332
shape is a sequence of file specifications. If the final
265
2333
character is '/', a directory is created.
2335
This assumes that all the elements in the tree being built are new.
267
2337
This doesn't add anything to a branch.
2339
:type shape: list or tuple.
2340
:param line_endings: Either 'binary' or 'native'
2341
in binary mode, exact contents are written in native mode, the
2342
line endings match the default platform endings.
2343
:param transport: A transport to write to, for building trees on VFS's.
2344
If the transport is readonly or None, "." is opened automatically.
269
# XXX: It's OK to just create them using forward slashes on windows?
2347
if type(shape) not in (list, tuple):
2348
raise AssertionError("Parameter 'shape' should be "
2349
"a list or a tuple. Got %r instead" % (shape,))
2350
# It's OK to just create them using forward slashes on windows.
2351
if transport is None or transport.is_readonly():
2352
transport = get_transport(".")
271
2353
for name in shape:
272
assert isinstance(name, basestring)
2354
self.assertIsInstance(name, basestring)
273
2355
if name[-1] == '/':
277
print >>f, "contents of", name
282
class MetaTestLog(TestCase):
283
def test_logging(self):
284
"""Test logs are captured when a test fails."""
285
logging.info('an info message')
286
warning('something looks dodgy...')
287
logging.debug('hello, test is running')
291
def selftest(verbose=False, pattern=".*"):
2356
transport.mkdir(urlutils.escape(name[:-1]))
2358
if line_endings == 'binary':
2360
elif line_endings == 'native':
2363
raise errors.BzrError(
2364
'Invalid line ending request %r' % line_endings)
2365
content = "contents of %s%s" % (name.encode('utf-8'), end)
2366
transport.put_bytes_non_atomic(urlutils.escape(name), content)
2368
def build_tree_contents(self, shape):
2369
build_tree_contents(shape)
2371
def assertInWorkingTree(self, path, root_path='.', tree=None):
2372
"""Assert whether path or paths are in the WorkingTree"""
2374
tree = workingtree.WorkingTree.open(root_path)
2375
if not isinstance(path, basestring):
2377
self.assertInWorkingTree(p, tree=tree)
2379
self.assertIsNot(tree.path2id(path), None,
2380
path+' not in working tree.')
2382
def assertNotInWorkingTree(self, path, root_path='.', tree=None):
2383
"""Assert whether path or paths are not in the WorkingTree"""
2385
tree = workingtree.WorkingTree.open(root_path)
2386
if not isinstance(path, basestring):
2388
self.assertNotInWorkingTree(p,tree=tree)
2390
self.assertIs(tree.path2id(path), None, path+' in working tree.')
2393
class TestCaseWithTransport(TestCaseInTempDir):
2394
"""A test case that provides get_url and get_readonly_url facilities.
2396
These back onto two transport servers, one for readonly access and one for
2399
If no explicit class is provided for readonly access, a
2400
ReadonlyTransportDecorator is used instead which allows the use of non disk
2401
based read write transports.
2403
If an explicit class is provided for readonly access, that server and the
2404
readwrite one must both define get_url() as resolving to os.getcwd().
2407
def get_vfs_only_server(self):
2408
"""See TestCaseWithMemoryTransport.
2410
This is useful for some tests with specific servers that need
2413
if self.__vfs_server is None:
2414
self.__vfs_server = self.vfs_transport_factory()
2415
self.__vfs_server.setUp()
2416
self.addCleanup(self.__vfs_server.tearDown)
2417
return self.__vfs_server
2419
def make_branch_and_tree(self, relpath, format=None):
2420
"""Create a branch on the transport and a tree locally.
2422
If the transport is not a LocalTransport, the Tree can't be created on
2423
the transport. In that case if the vfs_transport_factory is
2424
LocalURLServer the working tree is created in the local
2425
directory backing the transport, and the returned tree's branch and
2426
repository will also be accessed locally. Otherwise a lightweight
2427
checkout is created and returned.
2429
:param format: The BzrDirFormat.
2430
:returns: the WorkingTree.
2432
# TODO: always use the local disk path for the working tree,
2433
# this obviously requires a format that supports branch references
2434
# so check for that by checking bzrdir.BzrDirFormat.get_default_format()
2436
b = self.make_branch(relpath, format=format)
2438
return b.bzrdir.create_workingtree()
2439
except errors.NotLocalUrl:
2440
# We can only make working trees locally at the moment. If the
2441
# transport can't support them, then we keep the non-disk-backed
2442
# branch and create a local checkout.
2443
if self.vfs_transport_factory is LocalURLServer:
2444
# the branch is colocated on disk, we cannot create a checkout.
2445
# hopefully callers will expect this.
2446
local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
2447
wt = local_controldir.create_workingtree()
2448
if wt.branch._format != b._format:
2450
# Make sure that assigning to wt._branch fixes wt.branch,
2451
# in case the implementation details of workingtree objects
2453
self.assertIs(b, wt.branch)
2456
return b.create_checkout(relpath, lightweight=True)
2458
def assertIsDirectory(self, relpath, transport):
2459
"""Assert that relpath within transport is a directory.
2461
This may not be possible on all transports; in that case it propagates
2462
a TransportNotPossible.
2465
mode = transport.stat(relpath).st_mode
2466
except errors.NoSuchFile:
2467
self.fail("path %s is not a directory; no such file"
2469
if not stat.S_ISDIR(mode):
2470
self.fail("path %s is not a directory; has mode %#o"
2473
def assertTreesEqual(self, left, right):
2474
"""Check that left and right have the same content and properties."""
2475
# we use a tree delta to check for equality of the content, and we
2476
# manually check for equality of other things such as the parents list.
2477
self.assertEqual(left.get_parent_ids(), right.get_parent_ids())
2478
differences = left.changes_from(right)
2479
self.assertFalse(differences.has_changed(),
2480
"Trees %r and %r are different: %r" % (left, right, differences))
2483
super(TestCaseWithTransport, self).setUp()
2484
self.__vfs_server = None
2487
class ChrootedTestCase(TestCaseWithTransport):
2488
"""A support class that provides readonly urls outside the local namespace.
2490
This is done by checking if self.transport_server is a MemoryServer. if it
2491
is then we are chrooted already, if it is not then an HttpServer is used
2494
TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
2495
be used without needed to redo it when a different
2496
subclass is in use ?
2500
super(ChrootedTestCase, self).setUp()
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)
2588
def filter_suite_by_re(suite, 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
2672
for test in iter_suite_tests(suite):
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))
2695
def run_suite(suite, name='test', verbose=False, pattern=".*",
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.
2713
TestCase._gather_lsprof_in_benchmarks = lsprof_timed
2718
if runner_class is None:
2719
runner_class = TextTestRunner
2722
runner = runner_class(stream=stream,
2724
verbosity=verbosity,
2725
bench_history=bench_history,
2726
list_only=list_only,
2729
runner.stop_on_failure=stop_on_failure
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)
2743
result = runner.run(suite)
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 TestProtocolClient, 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()
3108
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
3110
test_suite_factory=None,
3113
matching_tests_first=None,
3116
exclude_pattern=None,
3122
suite_decorators=None,
292
3124
"""Run the whole test suite under the enhanced runner"""
293
return run_suite(test_suite(), 'testbzr', verbose=verbose, pattern=pattern)
297
"""Build and return TestSuite for the whole program."""
298
from bzrlib.selftest.TestUtil import TestLoader, TestSuite
299
import bzrlib, bzrlib.store, bzrlib.inventory, bzrlib.branch
300
import bzrlib.osutils, bzrlib.commands, bzrlib.merge3, bzrlib.plugin
301
from doctest import DocTestSuite
307
global MODULES_TO_TEST, MODULES_TO_DOCTEST
310
['bzrlib.selftest.MetaTestLog',
311
'bzrlib.selftest.testinv',
312
'bzrlib.selftest.versioning',
313
'bzrlib.selftest.testmerge3',
314
'bzrlib.selftest.testhashcache',
315
'bzrlib.selftest.teststatus',
316
'bzrlib.selftest.testlog',
317
'bzrlib.selftest.testrevisionnamespaces',
318
'bzrlib.selftest.testbranch',
319
'bzrlib.selftest.testrevision',
320
'bzrlib.selftest.test_merge_core',
321
'bzrlib.selftest.test_smart_add',
322
'bzrlib.selftest.testdiff',
323
'bzrlib.selftest.test_parent',
324
'bzrlib.selftest.test_xml',
325
'bzrlib.selftest.testfetch',
326
'bzrlib.selftest.whitebox',
327
'bzrlib.selftest.teststore',
328
'bzrlib.selftest.blackbox',
3125
# XXX: Very ugly way to do this...
3126
# Disable warning about old formats because we don't want it to disturb
3127
# any blackbox tests.
3128
from bzrlib import repository
3129
repository._deprecation_warning_done = True
3131
global default_transport
3132
if transport is None:
3133
transport = default_transport
3134
old_transport = default_transport
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)
3145
if test_suite_factory is None:
3146
suite = test_suite(keep_only, starting_with)
3148
suite = test_suite_factory()
3149
return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
3150
stop_on_failure=stop_on_failure,
3151
transport=transport,
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,
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):
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
3330
This function can be replaced if you need to change the default test
3331
suite on a global basis, but it is not encouraged.
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__chk_map',
3348
'bzrlib.tests.test__dirstate_helpers',
3349
'bzrlib.tests.test__groupcompress',
3350
'bzrlib.tests.test__known_graph',
3351
'bzrlib.tests.test__rio',
3352
'bzrlib.tests.test__walkdirs_win32',
3353
'bzrlib.tests.test_ancestry',
3354
'bzrlib.tests.test_annotate',
3355
'bzrlib.tests.test_api',
3356
'bzrlib.tests.test_atomicfile',
3357
'bzrlib.tests.test_bad_files',
3358
'bzrlib.tests.test_bencode',
3359
'bzrlib.tests.test_bisect_multi',
3360
'bzrlib.tests.test_branch',
3361
'bzrlib.tests.test_branchbuilder',
3362
'bzrlib.tests.test_btree_index',
3363
'bzrlib.tests.test_bugtracker',
3364
'bzrlib.tests.test_bundle',
3365
'bzrlib.tests.test_bzrdir',
3366
'bzrlib.tests.test__chunks_to_lines',
3367
'bzrlib.tests.test_cache_utf8',
3368
'bzrlib.tests.test_chk_map',
3369
'bzrlib.tests.test_chk_serializer',
3370
'bzrlib.tests.test_chunk_writer',
3371
'bzrlib.tests.test_clean_tree',
3372
'bzrlib.tests.test_commands',
3373
'bzrlib.tests.test_commit',
3374
'bzrlib.tests.test_commit_merge',
3375
'bzrlib.tests.test_config',
3376
'bzrlib.tests.test_conflicts',
3377
'bzrlib.tests.test_counted_lock',
3378
'bzrlib.tests.test_decorators',
3379
'bzrlib.tests.test_delta',
3380
'bzrlib.tests.test_debug',
3381
'bzrlib.tests.test_deprecated_graph',
3382
'bzrlib.tests.test_diff',
3383
'bzrlib.tests.test_directory_service',
3384
'bzrlib.tests.test_dirstate',
3385
'bzrlib.tests.test_email_message',
3386
'bzrlib.tests.test_eol_filters',
3387
'bzrlib.tests.test_errors',
3388
'bzrlib.tests.test_export',
3389
'bzrlib.tests.test_extract',
3390
'bzrlib.tests.test_fetch',
3391
'bzrlib.tests.test_fifo_cache',
3392
'bzrlib.tests.test_filters',
3393
'bzrlib.tests.test_ftp_transport',
3394
'bzrlib.tests.test_foreign',
3395
'bzrlib.tests.test_generate_docs',
3396
'bzrlib.tests.test_generate_ids',
3397
'bzrlib.tests.test_globbing',
3398
'bzrlib.tests.test_gpg',
3399
'bzrlib.tests.test_graph',
3400
'bzrlib.tests.test_groupcompress',
3401
'bzrlib.tests.test_hashcache',
3402
'bzrlib.tests.test_help',
3403
'bzrlib.tests.test_hooks',
3404
'bzrlib.tests.test_http',
3405
'bzrlib.tests.test_http_response',
3406
'bzrlib.tests.test_https_ca_bundle',
3407
'bzrlib.tests.test_identitymap',
3408
'bzrlib.tests.test_ignores',
3409
'bzrlib.tests.test_index',
3410
'bzrlib.tests.test_info',
3411
'bzrlib.tests.test_inv',
3412
'bzrlib.tests.test_inventory_delta',
3413
'bzrlib.tests.test_knit',
3414
'bzrlib.tests.test_lazy_import',
3415
'bzrlib.tests.test_lazy_regex',
3416
'bzrlib.tests.test_lockable_files',
3417
'bzrlib.tests.test_lockdir',
3418
'bzrlib.tests.test_log',
3419
'bzrlib.tests.test_lru_cache',
3420
'bzrlib.tests.test_lsprof',
3421
'bzrlib.tests.test_mail_client',
3422
'bzrlib.tests.test_memorytree',
3423
'bzrlib.tests.test_merge',
3424
'bzrlib.tests.test_merge3',
3425
'bzrlib.tests.test_merge_core',
3426
'bzrlib.tests.test_merge_directive',
3427
'bzrlib.tests.test_missing',
3428
'bzrlib.tests.test_msgeditor',
3429
'bzrlib.tests.test_multiparent',
3430
'bzrlib.tests.test_mutabletree',
3431
'bzrlib.tests.test_nonascii',
3432
'bzrlib.tests.test_options',
3433
'bzrlib.tests.test_osutils',
3434
'bzrlib.tests.test_osutils_encodings',
3435
'bzrlib.tests.test_pack',
3436
'bzrlib.tests.test_pack_repository',
3437
'bzrlib.tests.test_patch',
3438
'bzrlib.tests.test_patches',
3439
'bzrlib.tests.test_permissions',
3440
'bzrlib.tests.test_plugins',
3441
'bzrlib.tests.test_progress',
3442
'bzrlib.tests.test_read_bundle',
3443
'bzrlib.tests.test_reconcile',
3444
'bzrlib.tests.test_reconfigure',
3445
'bzrlib.tests.test_registry',
3446
'bzrlib.tests.test_remote',
3447
'bzrlib.tests.test_rename_map',
3448
'bzrlib.tests.test_repository',
3449
'bzrlib.tests.test_revert',
3450
'bzrlib.tests.test_revision',
3451
'bzrlib.tests.test_revisionspec',
3452
'bzrlib.tests.test_revisiontree',
3453
'bzrlib.tests.test_rio',
3454
'bzrlib.tests.test_rules',
3455
'bzrlib.tests.test_sampler',
3456
'bzrlib.tests.test_selftest',
3457
'bzrlib.tests.test_serializer',
3458
'bzrlib.tests.test_setup',
3459
'bzrlib.tests.test_sftp_transport',
3460
'bzrlib.tests.test_shelf',
3461
'bzrlib.tests.test_shelf_ui',
3462
'bzrlib.tests.test_smart',
3463
'bzrlib.tests.test_smart_add',
3464
'bzrlib.tests.test_smart_request',
3465
'bzrlib.tests.test_smart_transport',
3466
'bzrlib.tests.test_smtp_connection',
3467
'bzrlib.tests.test_source',
3468
'bzrlib.tests.test_ssh_transport',
3469
'bzrlib.tests.test_status',
3470
'bzrlib.tests.test_store',
3471
'bzrlib.tests.test_strace',
3472
'bzrlib.tests.test_subsume',
3473
'bzrlib.tests.test_switch',
3474
'bzrlib.tests.test_symbol_versioning',
3475
'bzrlib.tests.test_tag',
3476
'bzrlib.tests.test_testament',
3477
'bzrlib.tests.test_textfile',
3478
'bzrlib.tests.test_textmerge',
3479
'bzrlib.tests.test_timestamp',
3480
'bzrlib.tests.test_trace',
3481
'bzrlib.tests.test_transactions',
3482
'bzrlib.tests.test_transform',
3483
'bzrlib.tests.test_transport',
3484
'bzrlib.tests.test_transport_implementations',
3485
'bzrlib.tests.test_transport_log',
3486
'bzrlib.tests.test_tree',
3487
'bzrlib.tests.test_treebuilder',
3488
'bzrlib.tests.test_tsort',
3489
'bzrlib.tests.test_tuned_gzip',
3490
'bzrlib.tests.test_ui',
3491
'bzrlib.tests.test_uncommit',
3492
'bzrlib.tests.test_upgrade',
3493
'bzrlib.tests.test_upgrade_stacked',
3494
'bzrlib.tests.test_urlutils',
3495
'bzrlib.tests.test_version',
3496
'bzrlib.tests.test_version_info',
3497
'bzrlib.tests.test_versionedfile',
3498
'bzrlib.tests.test_weave',
3499
'bzrlib.tests.test_whitebox',
3500
'bzrlib.tests.test_win32utils',
3501
'bzrlib.tests.test_workingtree',
3502
'bzrlib.tests.test_workingtree_4',
3503
'bzrlib.tests.test_wsgi',
3504
'bzrlib.tests.test_xml',
3505
'bzrlib.tests.tree_implementations',
3506
'bzrlib.tests.workingtree_implementations',
331
for m in (bzrlib.store, bzrlib.inventory, bzrlib.branch,
332
bzrlib.osutils, bzrlib.commands, bzrlib.merge3):
333
if m not in MODULES_TO_DOCTEST:
334
MODULES_TO_DOCTEST.append(m)
336
TestCase.BZRPATH = os.path.join(os.path.realpath(os.path.dirname(bzrlib.__path__[0])), 'bzr')
337
print '%-30s %s' % ('bzr binary', TestCase.BZRPATH)
340
suite.addTest(TestLoader().loadTestsFromNames(testmod_names))
341
for m in MODULES_TO_TEST:
342
suite.addTest(TestLoader().loadTestsFromModule(m))
343
for m in (MODULES_TO_DOCTEST):
344
suite.addTest(DocTestSuite(m))
345
for p in bzrlib.plugin.all_plugins:
346
if hasattr(p, 'test_suite'):
347
suite.addTest(p.test_suite())
3509
loader = TestUtil.TestLoader()
3512
starting_with = [test_prefix_alias_registry.resolve_alias(start)
3513
for start in starting_with]
3514
# We take precedence over keep_only because *at loading time* using
3515
# both options means we will load less tests for the same final result.
3516
def interesting_module(name):
3517
for start in starting_with:
3519
# Either the module name starts with the specified string
3520
name.startswith(start)
3521
# or it may contain tests starting with the specified string
3522
or start.startswith(name)
3526
loader = TestUtil.FilteredByModuleTestLoader(interesting_module)
3528
elif keep_only is not None:
3529
id_filter = TestIdList(keep_only)
3530
loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
3531
def interesting_module(name):
3532
return id_filter.refers_to(name)
3535
loader = TestUtil.TestLoader()
3536
def interesting_module(name):
3537
# No filtering, all modules are interesting
3540
suite = loader.suiteClass()
3542
# modules building their suite with loadTestsFromModuleNames
3543
suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
3545
modules_to_doctest = [
3547
'bzrlib.branchbuilder',
3550
'bzrlib.iterablefile',
3554
'bzrlib.symbol_versioning',
3557
'bzrlib.version_info_formats.format_custom',
3560
for mod in modules_to_doctest:
3561
if not interesting_module(mod):
3562
# No tests to keep here, move along
3565
# note that this really does mean "report only" -- doctest
3566
# still runs the rest of the examples
3567
doc_suite = doctest.DocTestSuite(mod,
3568
optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
3569
except ValueError, e:
3570
print '**failed to get doctest for: %s\n%s' % (mod, e)
3572
if len(doc_suite._tests) == 0:
3573
raise errors.BzrError("no doctests found in %s" % (mod,))
3574
suite.addTest(doc_suite)
3576
default_encoding = sys.getdefaultencoding()
3577
for name, plugin in bzrlib.plugin.plugins().items():
3578
if not interesting_module(plugin.module.__name__):
3580
plugin_suite = plugin.test_suite()
3581
# We used to catch ImportError here and turn it into just a warning,
3582
# but really if you don't have --no-plugins this should be a failure.
3583
# mbp 20080213 - see http://bugs.launchpad.net/bugs/189771
3584
if plugin_suite is None:
3585
plugin_suite = plugin.load_plugin_tests(loader)
3586
if plugin_suite is not None:
3587
suite.addTest(plugin_suite)
3588
if default_encoding != sys.getdefaultencoding():
3589
bzrlib.trace.warning(
3590
'Plugin "%s" tried to reset default encoding to: %s', name,
3591
sys.getdefaultencoding())
3593
sys.setdefaultencoding(default_encoding)
3596
suite = filter_suite_by_id_startswith(suite, starting_with)
3598
if keep_only is not None:
3599
# Now that the referred modules have loaded their tests, keep only the
3601
suite = filter_suite_by_id_list(suite, id_filter)
3602
# Do some sanity checks on the id_list filtering
3603
not_found, duplicates = suite_matches_id_list(suite, keep_only)
3605
# The tester has used both keep_only and starting_with, so he is
3606
# already aware that some tests are excluded from the list, there
3607
# is no need to tell him which.
3610
# Some tests mentioned in the list are not in the test suite. The
3611
# list may be out of date, report to the tester.
3612
for id in not_found:
3613
bzrlib.trace.warning('"%s" not found in the test suite', id)
3614
for id in duplicates:
3615
bzrlib.trace.warning('"%s" is used as an id by several tests', id)
3620
def multiply_scenarios(scenarios_left, scenarios_right):
3621
"""Multiply two sets of scenarios.
3623
:returns: the cartesian product of the two sets of scenarios, that is
3624
a scenario for every possible combination of a left scenario and a
3628
('%s,%s' % (left_name, right_name),
3629
dict(left_dict.items() + right_dict.items()))
3630
for left_name, left_dict in scenarios_left
3631
for right_name, right_dict in scenarios_right]
3634
def multiply_tests(tests, scenarios, result):
3635
"""Multiply tests_list by scenarios into result.
3637
This is the core workhorse for test parameterisation.
3639
Typically the load_tests() method for a per-implementation test suite will
3640
call multiply_tests and return the result.
3642
:param tests: The tests to parameterise.
3643
:param scenarios: The scenarios to apply: pairs of (scenario_name,
3644
scenario_param_dict).
3645
:param result: A TestSuite to add created tests to.
3647
This returns the passed in result TestSuite with the cross product of all
3648
the tests repeated once for each scenario. Each test is adapted by adding
3649
the scenario name at the end of its id(), and updating the test object's
3650
__dict__ with the scenario_param_dict.
3652
>>> import bzrlib.tests.test_sampler
3653
>>> r = multiply_tests(
3654
... bzrlib.tests.test_sampler.DemoTest('test_nothing'),
3655
... [('one', dict(param=1)),
3656
... ('two', dict(param=2))],
3658
>>> tests = list(iter_suite_tests(r))
3662
'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
3668
for test in iter_suite_tests(tests):
3669
apply_scenarios(test, scenarios, result)
3673
def apply_scenarios(test, scenarios, result):
3674
"""Apply the scenarios in scenarios to test and add to result.
3676
:param test: The test to apply scenarios to.
3677
:param scenarios: An iterable of scenarios to apply to test.
3679
:seealso: apply_scenario
3681
for scenario in scenarios:
3682
result.addTest(apply_scenario(test, scenario))
3686
def apply_scenario(test, scenario):
3687
"""Copy test and apply scenario to it.
3689
:param test: A test to adapt.
3690
:param scenario: A tuple describing the scenarion.
3691
The first element of the tuple is the new test id.
3692
The second element is a dict containing attributes to set on the
3694
:return: The adapted test.
3696
new_id = "%s(%s)" % (test.id(), scenario[0])
3697
new_test = clone_test(test, new_id)
3698
for name, value in scenario[1].items():
3699
setattr(new_test, name, value)
3703
def clone_test(test, new_id):
3704
"""Clone a test giving it a new id.
3706
:param test: The test to clone.
3707
:param new_id: The id to assign to it.
3708
:return: The new test.
3710
from copy import deepcopy
3711
new_test = deepcopy(test)
3712
new_test.id = lambda: new_id
3716
def _rmtree_temp_dir(dirname):
3717
# If LANG=C we probably have created some bogus paths
3718
# which rmtree(unicode) will fail to delete
3719
# so make sure we are using rmtree(str) to delete everything
3720
# except on win32, where rmtree(str) will fail
3721
# since it doesn't have the property of byte-stream paths
3722
# (they are either ascii or mbcs)
3723
if sys.platform == 'win32':
3724
# make sure we are using the unicode win32 api
3725
dirname = unicode(dirname)
3727
dirname = dirname.encode(sys.getfilesystemencoding())
3729
osutils.rmtree(dirname)
3731
if sys.platform == 'win32' and e.errno == errno.EACCES:
3732
sys.stderr.write('Permission denied: '
3733
'unable to remove testing dir '
3735
% (os.path.basename(dirname), e))
3740
class Feature(object):
3741
"""An operating system Feature."""
3744
self._available = None
3746
def available(self):
3747
"""Is the feature available?
3749
:return: True if the feature is available.
3751
if self._available is None:
3752
self._available = self._probe()
3753
return self._available
3756
"""Implement this method in concrete features.
3758
:return: True if the feature is available.
3760
raise NotImplementedError
3763
if getattr(self, 'feature_name', None):
3764
return self.feature_name()
3765
return self.__class__.__name__
3768
class _SymlinkFeature(Feature):
3771
return osutils.has_symlinks()
3773
def feature_name(self):
3776
SymlinkFeature = _SymlinkFeature()
3779
class _HardlinkFeature(Feature):
3782
return osutils.has_hardlinks()
3784
def feature_name(self):
3787
HardlinkFeature = _HardlinkFeature()
3790
class _OsFifoFeature(Feature):
3793
return getattr(os, 'mkfifo', None)
3795
def feature_name(self):
3796
return 'filesystem fifos'
3798
OsFifoFeature = _OsFifoFeature()
3801
class _UnicodeFilenameFeature(Feature):
3802
"""Does the filesystem support Unicode filenames?"""
3806
# Check for character combinations unlikely to be covered by any
3807
# single non-unicode encoding. We use the characters
3808
# - greek small letter alpha (U+03B1) and
3809
# - braille pattern dots-123456 (U+283F).
3810
os.stat(u'\u03b1\u283f')
3811
except UnicodeEncodeError:
3813
except (IOError, OSError):
3814
# The filesystem allows the Unicode filename but the file doesn't
3818
# The filesystem allows the Unicode filename and the file exists,
3822
UnicodeFilenameFeature = _UnicodeFilenameFeature()
3825
def probe_unicode_in_user_encoding():
3826
"""Try to encode several unicode strings to use in unicode-aware tests.
3827
Return first successfull match.
3829
:return: (unicode value, encoded plain string value) or (None, None)
3831
possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
3832
for uni_val in possible_vals:
3834
str_val = uni_val.encode(osutils.get_user_encoding())
3835
except UnicodeEncodeError:
3836
# Try a different character
3839
return uni_val, str_val
3843
def probe_bad_non_ascii(encoding):
3844
"""Try to find [bad] character with code [128..255]
3845
that cannot be decoded to unicode in some encoding.
3846
Return None if all non-ascii characters is valid
3849
for i in xrange(128, 256):
3852
char.decode(encoding)
3853
except UnicodeDecodeError:
3858
class _HTTPSServerFeature(Feature):
3859
"""Some tests want an https Server, check if one is available.
3861
Right now, the only way this is available is under python2.6 which provides
3872
def feature_name(self):
3873
return 'HTTPSServer'
3876
HTTPSServerFeature = _HTTPSServerFeature()
3879
class _UnicodeFilename(Feature):
3880
"""Does the filesystem support Unicode filenames?"""
3885
except UnicodeEncodeError:
3887
except (IOError, OSError):
3888
# The filesystem allows the Unicode filename but the file doesn't
3892
# The filesystem allows the Unicode filename and the file exists,
3896
UnicodeFilename = _UnicodeFilename()
3899
class _UTF8Filesystem(Feature):
3900
"""Is the filesystem UTF-8?"""
3903
if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
3907
UTF8Filesystem = _UTF8Filesystem()
3910
class _CaseInsCasePresFilenameFeature(Feature):
3911
"""Is the file-system case insensitive, but case-preserving?"""
3914
fileno, name = tempfile.mkstemp(prefix='MixedCase')
3916
# first check truly case-preserving for created files, then check
3917
# case insensitive when opening existing files.
3918
name = osutils.normpath(name)
3919
base, rel = osutils.split(name)
3920
found_rel = osutils.canonical_relpath(base, name)
3921
return (found_rel == rel
3922
and os.path.isfile(name.upper())
3923
and os.path.isfile(name.lower()))
3928
def feature_name(self):
3929
return "case-insensitive case-preserving filesystem"
3931
CaseInsCasePresFilenameFeature = _CaseInsCasePresFilenameFeature()
3934
class _CaseInsensitiveFilesystemFeature(Feature):
3935
"""Check if underlying filesystem is case-insensitive but *not* case
3938
# Note that on Windows, Cygwin, MacOS etc, the file-systems are far
3939
# more likely to be case preserving, so this case is rare.
3942
if CaseInsCasePresFilenameFeature.available():
3945
if TestCaseWithMemoryTransport.TEST_ROOT is None:
3946
root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
3947
TestCaseWithMemoryTransport.TEST_ROOT = root
3949
root = TestCaseWithMemoryTransport.TEST_ROOT
3950
tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
3952
name_a = osutils.pathjoin(tdir, 'a')
3953
name_A = osutils.pathjoin(tdir, 'A')
3955
result = osutils.isdir(name_A)
3956
_rmtree_temp_dir(tdir)
3959
def feature_name(self):
3960
return 'case-insensitive filesystem'
3962
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
3965
class _SubUnitFeature(Feature):
3966
"""Check if subunit is available."""
3975
def feature_name(self):
3978
SubUnitFeature = _SubUnitFeature()
3979
# Only define SubUnitBzrRunner if subunit is available.
3981
from subunit import TestProtocolClient
3982
class SubUnitBzrRunner(TextTestRunner):
3983
def run(self, test):
3984
result = TestProtocolClient(self.stream)