1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 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.
32
from cStringIO import StringIO
39
from pprint import pformat
44
from subprocess import Popen, PIPE, STDOUT
70
import bzrlib.commands
71
import bzrlib.timestamp
73
import bzrlib.inventory
74
import bzrlib.iterablefile
79
# lsprof not available
81
from bzrlib.merge import merge_inner
84
from bzrlib.smart import client, request, server
86
from bzrlib import symbol_versioning
87
from bzrlib.symbol_versioning import (
94
from bzrlib.transport import get_transport, pathfilter
95
import bzrlib.transport
96
from bzrlib.transport.local import LocalURLServer
97
from bzrlib.transport.memory import MemoryServer
98
from bzrlib.transport.readonly import ReadonlyServer
99
from bzrlib.trace import mutter, note
100
from bzrlib.tests import TestUtil
101
from bzrlib.tests.http_server import HttpServer
102
from bzrlib.tests.TestUtil import (
106
from bzrlib.tests.treeshape import build_tree_contents
107
from bzrlib.ui import NullProgressView
108
from bzrlib.ui.text import TextUIFactory
109
import bzrlib.version_info_formats.format_custom
110
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
112
# Mark this python module as being part of the implementation
113
# of unittest: this gives us better tracebacks where the last
114
# shown frame is the test code, not our assertXYZ.
117
default_transport = LocalURLServer
119
# Subunit result codes, defined here to prevent a hard dependency on subunit.
124
class ExtendedTestResult(unittest._TextTestResult):
125
"""Accepts, reports and accumulates the results of running tests.
127
Compared to the unittest version this class adds support for
128
profiling, benchmarking, stopping as soon as a test fails, and
129
skipping tests. There are further-specialized subclasses for
130
different types of display.
132
When a test finishes, in whatever way, it calls one of the addSuccess,
133
addFailure or addError classes. These in turn may redirect to a more
134
specific case for the special test results supported by our extended
137
Note that just one of these objects is fed the results from many tests.
142
def __init__(self, stream, descriptions, verbosity,
146
"""Construct new TestResult.
148
:param bench_history: Optionally, a writable file object to accumulate
151
unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
152
if bench_history is not None:
153
from bzrlib.version import _get_bzr_source_tree
154
src_tree = _get_bzr_source_tree()
157
revision_id = src_tree.get_parent_ids()[0]
159
# XXX: if this is a brand new tree, do the same as if there
163
# XXX: If there's no branch, what should we do?
165
bench_history.write("--date %s %s\n" % (time.time(), revision_id))
166
self._bench_history = bench_history
167
self.ui = ui.ui_factory
170
self.failure_count = 0
171
self.known_failure_count = 0
173
self.not_applicable_count = 0
174
self.unsupported = {}
176
self._overall_start_time = time.time()
177
self._strict = strict
179
def stopTestRun(self):
182
stopTime = time.time()
183
timeTaken = stopTime - self.startTime
185
self.stream.writeln(self.separator2)
186
self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
187
run, run != 1 and "s" or "", timeTaken))
188
self.stream.writeln()
189
if not self.wasSuccessful():
190
self.stream.write("FAILED (")
191
failed, errored = map(len, (self.failures, self.errors))
193
self.stream.write("failures=%d" % failed)
195
if failed: self.stream.write(", ")
196
self.stream.write("errors=%d" % errored)
197
if self.known_failure_count:
198
if failed or errored: self.stream.write(", ")
199
self.stream.write("known_failure_count=%d" %
200
self.known_failure_count)
201
self.stream.writeln(")")
203
if self.known_failure_count:
204
self.stream.writeln("OK (known_failures=%d)" %
205
self.known_failure_count)
207
self.stream.writeln("OK")
208
if self.skip_count > 0:
209
skipped = self.skip_count
210
self.stream.writeln('%d test%s skipped' %
211
(skipped, skipped != 1 and "s" or ""))
213
for feature, count in sorted(self.unsupported.items()):
214
self.stream.writeln("Missing feature '%s' skipped %d tests." %
217
ok = self.wasStrictlySuccessful()
219
ok = self.wasSuccessful()
220
if TestCase._first_thread_leaker_id:
222
'%s is leaking threads among %d leaking tests.\n' % (
223
TestCase._first_thread_leaker_id,
224
TestCase._leaking_threads_tests))
226
def _extractBenchmarkTime(self, testCase):
227
"""Add a benchmark time for the current test case."""
228
return getattr(testCase, "_benchtime", None)
230
def _elapsedTestTimeString(self):
231
"""Return a time string for the overall time the current test has taken."""
232
return self._formatTime(time.time() - self._start_time)
234
def _testTimeString(self, testCase):
235
benchmark_time = self._extractBenchmarkTime(testCase)
236
if benchmark_time is not None:
237
return self._formatTime(benchmark_time) + "*"
239
return self._elapsedTestTimeString()
241
def _formatTime(self, seconds):
242
"""Format seconds as milliseconds with leading spaces."""
243
# some benchmarks can take thousands of seconds to run, so we need 8
245
return "%8dms" % (1000 * seconds)
247
def _shortened_test_description(self, test):
249
what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
252
def startTest(self, test):
253
unittest.TestResult.startTest(self, test)
256
self.report_test_start(test)
257
test.number = self.count
258
self._recordTestStartTime()
260
def startTests(self):
262
if getattr(sys, 'frozen', None) is None:
263
bzr_path = osutils.realpath(sys.argv[0])
265
bzr_path = sys.executable
267
'testing: %s\n' % (bzr_path,))
270
bzrlib.__path__[0],))
272
' bzr-%s python-%s %s\n' % (
273
bzrlib.version_string,
274
bzrlib._format_version_tuple(sys.version_info),
275
platform.platform(aliased=1),
277
self.stream.write('\n')
279
def _recordTestStartTime(self):
280
"""Record that a test has started."""
281
self._start_time = time.time()
283
def _cleanupLogFile(self, test):
284
# We can only do this if we have one of our TestCases, not if
286
setKeepLogfile = getattr(test, 'setKeepLogfile', None)
287
if setKeepLogfile is not None:
290
def addError(self, test, err):
291
"""Tell result that test finished with an error.
293
Called from the TestCase run() method when the test
294
fails with an unexpected error.
296
self._testConcluded(test)
297
if isinstance(err[1], TestNotApplicable):
298
return self._addNotApplicable(test, err)
299
elif isinstance(err[1], UnavailableFeature):
300
return self.addNotSupported(test, err[1].args[0])
303
unittest.TestResult.addError(self, test, err)
304
self.error_count += 1
305
self.report_error(test, err)
308
self._cleanupLogFile(test)
310
def addFailure(self, test, err):
311
"""Tell result that test failed.
313
Called from the TestCase run() method when the test
314
fails because e.g. an assert() method failed.
316
self._testConcluded(test)
317
if isinstance(err[1], KnownFailure):
318
return self._addKnownFailure(test, err)
321
unittest.TestResult.addFailure(self, test, err)
322
self.failure_count += 1
323
self.report_failure(test, err)
326
self._cleanupLogFile(test)
328
def addSuccess(self, test):
329
"""Tell result that test completed successfully.
331
Called from the TestCase run()
333
self._testConcluded(test)
334
if self._bench_history is not None:
335
benchmark_time = self._extractBenchmarkTime(test)
336
if benchmark_time is not None:
337
self._bench_history.write("%s %s\n" % (
338
self._formatTime(benchmark_time),
340
self.report_success(test)
341
self._cleanupLogFile(test)
342
unittest.TestResult.addSuccess(self, test)
343
test._log_contents = ''
345
def _testConcluded(self, test):
346
"""Common code when a test has finished.
348
Called regardless of whether it succeded, failed, etc.
352
def _addKnownFailure(self, test, err):
353
self.known_failure_count += 1
354
self.report_known_failure(test, err)
356
def addNotSupported(self, test, feature):
357
"""The test will not be run because of a missing feature.
359
# this can be called in two different ways: it may be that the
360
# test started running, and then raised (through addError)
361
# UnavailableFeature. Alternatively this method can be called
362
# while probing for features before running the tests; in that
363
# case we will see startTest and stopTest, but the test will never
365
self.unsupported.setdefault(str(feature), 0)
366
self.unsupported[str(feature)] += 1
367
self.report_unsupported(test, feature)
369
def addSkip(self, test, reason):
370
"""A test has not run for 'reason'."""
372
self.report_skip(test, reason)
374
def _addNotApplicable(self, test, skip_excinfo):
375
if isinstance(skip_excinfo[1], TestNotApplicable):
376
self.not_applicable_count += 1
377
self.report_not_applicable(test, skip_excinfo)
380
except KeyboardInterrupt:
383
self.addError(test, test.exc_info())
385
# seems best to treat this as success from point-of-view of unittest
386
# -- it actually does nothing so it barely matters :)
387
unittest.TestResult.addSuccess(self, test)
388
test._log_contents = ''
390
def printErrorList(self, flavour, errors):
391
for test, err in errors:
392
self.stream.writeln(self.separator1)
393
self.stream.write("%s: " % flavour)
394
self.stream.writeln(self.getDescription(test))
395
if getattr(test, '_get_log', None) is not None:
396
log_contents = test._get_log()
398
self.stream.write('\n')
400
('vvvv[log from %s]' % test.id()).ljust(78,'-'))
401
self.stream.write('\n')
402
self.stream.write(log_contents)
403
self.stream.write('\n')
405
('^^^^[log from %s]' % test.id()).ljust(78,'-'))
406
self.stream.write('\n')
407
self.stream.writeln(self.separator2)
408
self.stream.writeln("%s" % err)
410
def _post_mortem(self):
411
"""Start a PDB post mortem session."""
412
if os.environ.get('BZR_TEST_PDB', None):
413
import pdb;pdb.post_mortem()
415
def progress(self, offset, whence):
416
"""The test is adjusting the count of tests to run."""
417
if whence == SUBUNIT_SEEK_SET:
418
self.num_tests = offset
419
elif whence == SUBUNIT_SEEK_CUR:
420
self.num_tests += offset
422
raise errors.BzrError("Unknown whence %r" % whence)
424
def report_cleaning_up(self):
427
def startTestRun(self):
428
self.startTime = time.time()
430
def report_success(self, test):
433
def wasStrictlySuccessful(self):
434
if self.unsupported or self.known_failure_count:
436
return self.wasSuccessful()
439
class TextTestResult(ExtendedTestResult):
440
"""Displays progress and results of tests in text form"""
442
def __init__(self, stream, descriptions, verbosity,
447
ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
448
bench_history, strict)
449
# We no longer pass them around, but just rely on the UIFactory stack
452
warnings.warn("Passing pb to TextTestResult is deprecated")
453
self.pb = self.ui.nested_progress_bar()
454
self.pb.show_pct = False
455
self.pb.show_spinner = False
456
self.pb.show_eta = False,
457
self.pb.show_count = False
458
self.pb.show_bar = False
459
self.pb.update_latency = 0
460
self.pb.show_transport_activity = False
462
def stopTestRun(self):
463
# called when the tests that are going to run have run
466
super(TextTestResult, self).stopTestRun()
468
def startTestRun(self):
469
super(TextTestResult, self).startTestRun()
470
self.pb.update('[test 0/%d] Starting' % (self.num_tests))
472
def printErrors(self):
473
# clear the pb to make room for the error listing
475
super(TextTestResult, self).printErrors()
477
def _progress_prefix_text(self):
478
# the longer this text, the less space we have to show the test
480
a = '[%d' % self.count # total that have been run
481
# tests skipped as known not to be relevant are not important enough
483
## if self.skip_count:
484
## a += ', %d skip' % self.skip_count
485
## if self.known_failure_count:
486
## a += '+%dX' % self.known_failure_count
488
a +='/%d' % self.num_tests
490
runtime = time.time() - self._overall_start_time
492
a += '%dm%ds' % (runtime / 60, runtime % 60)
496
a += ', %d err' % self.error_count
497
if self.failure_count:
498
a += ', %d fail' % self.failure_count
499
# if self.unsupported:
500
# a += ', %d missing' % len(self.unsupported)
504
def report_test_start(self, test):
507
self._progress_prefix_text()
509
+ self._shortened_test_description(test))
511
def _test_description(self, test):
512
return self._shortened_test_description(test)
514
def report_error(self, test, err):
515
ui.ui_factory.note('ERROR: %s\n %s\n' % (
516
self._test_description(test),
520
def report_failure(self, test, err):
521
ui.ui_factory.note('FAIL: %s\n %s\n' % (
522
self._test_description(test),
526
def report_known_failure(self, test, err):
527
ui.ui_factory.note('XFAIL: %s\n%s\n' % (
528
self._test_description(test), err[1]))
530
def report_skip(self, test, reason):
533
def report_not_applicable(self, test, skip_excinfo):
536
def report_unsupported(self, test, feature):
537
"""test cannot be run because feature is missing."""
539
def report_cleaning_up(self):
540
self.pb.update('Cleaning up')
543
class VerboseTestResult(ExtendedTestResult):
544
"""Produce long output, with one line per test run plus times"""
546
def _ellipsize_to_right(self, a_string, final_width):
547
"""Truncate and pad a string, keeping the right hand side"""
548
if len(a_string) > final_width:
549
result = '...' + a_string[3-final_width:]
552
return result.ljust(final_width)
554
def startTestRun(self):
555
super(VerboseTestResult, self).startTestRun()
556
self.stream.write('running %d tests...\n' % self.num_tests)
558
def report_test_start(self, test):
560
name = self._shortened_test_description(test)
561
# width needs space for 6 char status, plus 1 for slash, plus an
562
# 11-char time string, plus a trailing blank
563
# when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on space
564
self.stream.write(self._ellipsize_to_right(name,
565
osutils.terminal_width()-18))
568
def _error_summary(self, err):
570
return '%s%s' % (indent, err[1])
572
def report_error(self, test, err):
573
self.stream.writeln('ERROR %s\n%s'
574
% (self._testTimeString(test),
575
self._error_summary(err)))
577
def report_failure(self, test, err):
578
self.stream.writeln(' FAIL %s\n%s'
579
% (self._testTimeString(test),
580
self._error_summary(err)))
582
def report_known_failure(self, test, err):
583
self.stream.writeln('XFAIL %s\n%s'
584
% (self._testTimeString(test),
585
self._error_summary(err)))
587
def report_success(self, test):
588
self.stream.writeln(' OK %s' % self._testTimeString(test))
589
for bench_called, stats in getattr(test, '_benchcalls', []):
590
self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
591
stats.pprint(file=self.stream)
592
# flush the stream so that we get smooth output. This verbose mode is
593
# used to show the output in PQM.
596
def report_skip(self, test, reason):
597
self.stream.writeln(' SKIP %s\n%s'
598
% (self._testTimeString(test), reason))
600
def report_not_applicable(self, test, skip_excinfo):
601
self.stream.writeln(' N/A %s\n%s'
602
% (self._testTimeString(test),
603
self._error_summary(skip_excinfo)))
605
def report_unsupported(self, test, feature):
606
"""test cannot be run because feature is missing."""
607
self.stream.writeln("NODEP %s\n The feature '%s' is not available."
608
%(self._testTimeString(test), feature))
611
class TextTestRunner(object):
612
stop_on_failure = False
620
result_decorators=None,
622
"""Create a TextTestRunner.
624
:param result_decorators: An optional list of decorators to apply
625
to the result object being used by the runner. Decorators are
626
applied left to right - the first element in the list is the
629
self.stream = unittest._WritelnDecorator(stream)
630
self.descriptions = descriptions
631
self.verbosity = verbosity
632
self._bench_history = bench_history
633
self._strict = strict
634
self._result_decorators = result_decorators or []
637
"Run the given test case or test suite."
638
if self.verbosity == 1:
639
result_class = TextTestResult
640
elif self.verbosity >= 2:
641
result_class = VerboseTestResult
642
original_result = result_class(self.stream,
645
bench_history=self._bench_history,
648
# Signal to result objects that look at stop early policy to stop,
649
original_result.stop_early = self.stop_on_failure
650
result = original_result
651
for decorator in self._result_decorators:
652
result = decorator(result)
653
result.stop_early = self.stop_on_failure
659
if isinstance(test, testtools.ConcurrentTestSuite):
660
# We need to catch bzr specific behaviors
661
result = BZRTransformingResult(result)
662
result.startTestRun()
667
# higher level code uses our extended protocol to determine
668
# what exit code to give.
669
return original_result
672
def iter_suite_tests(suite):
673
"""Return all tests in a suite, recursing through nested suites"""
674
if isinstance(suite, unittest.TestCase):
676
elif isinstance(suite, unittest.TestSuite):
678
for r in iter_suite_tests(item):
681
raise Exception('unknown type %r for object %r'
682
% (type(suite), suite))
685
class TestSkipped(Exception):
686
"""Indicates that a test was intentionally skipped, rather than failing."""
689
class TestNotApplicable(TestSkipped):
690
"""A test is not applicable to the situation where it was run.
692
This is only normally raised by parameterized tests, if they find that
693
the instance they're constructed upon does not support one aspect
698
class KnownFailure(AssertionError):
699
"""Indicates that a test failed in a precisely expected manner.
701
Such failures dont block the whole test suite from passing because they are
702
indicators of partially completed code or of future work. We have an
703
explicit error for them so that we can ensure that they are always visible:
704
KnownFailures are always shown in the output of bzr selftest.
708
class UnavailableFeature(Exception):
709
"""A feature required for this test was not available.
711
The feature should be used to construct the exception.
715
class CommandFailed(Exception):
719
class StringIOWrapper(object):
720
"""A wrapper around cStringIO which just adds an encoding attribute.
722
Internally we can check sys.stdout to see what the output encoding
723
should be. However, cStringIO has no encoding attribute that we can
724
set. So we wrap it instead.
729
def __init__(self, s=None):
731
self.__dict__['_cstring'] = StringIO(s)
733
self.__dict__['_cstring'] = StringIO()
735
def __getattr__(self, name, getattr=getattr):
736
return getattr(self.__dict__['_cstring'], name)
738
def __setattr__(self, name, val):
739
if name == 'encoding':
740
self.__dict__['encoding'] = val
742
return setattr(self._cstring, name, val)
745
class TestUIFactory(TextUIFactory):
746
"""A UI Factory for testing.
748
Hide the progress bar but emit note()s.
750
Allows get_password to be tested without real tty attached.
752
See also CannedInputUIFactory which lets you provide programmatic input in
755
# TODO: Capture progress events at the model level and allow them to be
756
# observed by tests that care.
758
# XXX: Should probably unify more with CannedInputUIFactory or a
759
# particular configuration of TextUIFactory, or otherwise have a clearer
760
# idea of how they're supposed to be different.
761
# See https://bugs.edge.launchpad.net/bzr/+bug/408213
763
def __init__(self, stdout=None, stderr=None, stdin=None):
764
if stdin is not None:
765
# We use a StringIOWrapper to be able to test various
766
# encodings, but the user is still responsible to
767
# encode the string and to set the encoding attribute
768
# of StringIOWrapper.
769
stdin = StringIOWrapper(stdin)
770
super(TestUIFactory, self).__init__(stdin, stdout, stderr)
772
def get_non_echoed_password(self):
773
"""Get password from stdin without trying to handle the echo mode"""
774
password = self.stdin.readline()
777
if password[-1] == '\n':
778
password = password[:-1]
781
def make_progress_view(self):
782
return NullProgressView()
785
class TestCase(unittest.TestCase):
786
"""Base class for bzr unit tests.
788
Tests that need access to disk resources should subclass
789
TestCaseInTempDir not TestCase.
791
Error and debug log messages are redirected from their usual
792
location into a temporary file, the contents of which can be
793
retrieved by _get_log(). We use a real OS file, not an in-memory object,
794
so that it can also capture file IO. When the test completes this file
795
is read into memory and removed from disk.
797
There are also convenience functions to invoke bzr's command-line
798
routine, and to build and check bzr trees.
800
In addition to the usual method of overriding tearDown(), this class also
801
allows subclasses to register functions into the _cleanups list, which is
802
run in order as the object is torn down. It's less likely this will be
803
accidentally overlooked.
806
_active_threads = None
807
_leaking_threads_tests = 0
808
_first_thread_leaker_id = None
809
_log_file_name = None
811
_keep_log_file = False
812
# record lsprof data when performing benchmark calls.
813
_gather_lsprof_in_benchmarks = False
814
attrs_to_keep = ('id', '_testMethodName', '_testMethodDoc',
815
'_log_contents', '_log_file_name', '_benchtime',
816
'_TestCase__testMethodName', '_TestCase__testMethodDoc',)
818
def __init__(self, methodName='testMethod'):
819
super(TestCase, self).__init__(methodName)
821
self._bzr_test_setUp_run = False
822
self._bzr_test_tearDown_run = False
823
self._directory_isolation = True
826
unittest.TestCase.setUp(self)
827
self._bzr_test_setUp_run = True
828
self._cleanEnvironment()
831
self._benchcalls = []
832
self._benchtime = None
834
self._track_transports()
836
self._clear_debug_flags()
837
TestCase._active_threads = threading.activeCount()
838
self.addCleanup(self._check_leaked_threads)
843
pdb.Pdb().set_trace(sys._getframe().f_back)
845
def _check_leaked_threads(self):
846
active = threading.activeCount()
847
leaked_threads = active - TestCase._active_threads
848
TestCase._active_threads = active
850
TestCase._leaking_threads_tests += 1
851
if TestCase._first_thread_leaker_id is None:
852
TestCase._first_thread_leaker_id = self.id()
854
def _clear_debug_flags(self):
855
"""Prevent externally set debug flags affecting tests.
857
Tests that want to use debug flags can just set them in the
858
debug_flags set during setup/teardown.
860
self._preserved_debug_flags = set(debug.debug_flags)
861
if 'allow_debug' not in selftest_debug_flags:
862
debug.debug_flags.clear()
863
if 'disable_lock_checks' not in selftest_debug_flags:
864
debug.debug_flags.add('strict_locks')
865
self.addCleanup(self._restore_debug_flags)
867
def _clear_hooks(self):
868
# prevent hooks affecting tests
869
self._preserved_hooks = {}
870
for key, factory in hooks.known_hooks.items():
871
parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
872
current_hooks = hooks.known_hooks_key_to_object(key)
873
self._preserved_hooks[parent] = (name, current_hooks)
874
self.addCleanup(self._restoreHooks)
875
for key, factory in hooks.known_hooks.items():
876
parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
877
setattr(parent, name, factory())
878
# this hook should always be installed
879
request._install_hook()
881
def disable_directory_isolation(self):
882
"""Turn off directory isolation checks."""
883
self._directory_isolation = False
885
def enable_directory_isolation(self):
886
"""Enable directory isolation checks."""
887
self._directory_isolation = True
889
def _silenceUI(self):
890
"""Turn off UI for duration of test"""
891
# by default the UI is off; tests can turn it on if they want it.
892
saved = ui.ui_factory
894
ui.ui_factory = saved
895
ui.ui_factory = ui.SilentUIFactory()
896
self.addCleanup(_restore)
898
def _check_locks(self):
899
"""Check that all lock take/release actions have been paired."""
900
# We always check for mismatched locks. If a mismatch is found, we
901
# fail unless -Edisable_lock_checks is supplied to selftest, in which
902
# case we just print a warning.
904
acquired_locks = [lock for action, lock in self._lock_actions
905
if action == 'acquired']
906
released_locks = [lock for action, lock in self._lock_actions
907
if action == 'released']
908
broken_locks = [lock for action, lock in self._lock_actions
909
if action == 'broken']
910
# trivially, given the tests for lock acquistion and release, if we
911
# have as many in each list, it should be ok. Some lock tests also
912
# break some locks on purpose and should be taken into account by
913
# considering that breaking a lock is just a dirty way of releasing it.
914
if len(acquired_locks) != (len(released_locks) + len(broken_locks)):
915
message = ('Different number of acquired and '
916
'released or broken locks. (%s, %s + %s)' %
917
(acquired_locks, released_locks, broken_locks))
918
if not self._lock_check_thorough:
919
# Rather than fail, just warn
920
print "Broken test %s: %s" % (self, message)
924
def _track_locks(self):
925
"""Track lock activity during tests."""
926
self._lock_actions = []
927
if 'disable_lock_checks' in selftest_debug_flags:
928
self._lock_check_thorough = False
930
self._lock_check_thorough = True
932
self.addCleanup(self._check_locks)
933
_mod_lock.Lock.hooks.install_named_hook('lock_acquired',
934
self._lock_acquired, None)
935
_mod_lock.Lock.hooks.install_named_hook('lock_released',
936
self._lock_released, None)
937
_mod_lock.Lock.hooks.install_named_hook('lock_broken',
938
self._lock_broken, None)
940
def _lock_acquired(self, result):
941
self._lock_actions.append(('acquired', result))
943
def _lock_released(self, result):
944
self._lock_actions.append(('released', result))
946
def _lock_broken(self, result):
947
self._lock_actions.append(('broken', result))
949
def permit_dir(self, name):
950
"""Permit a directory to be used by this test. See permit_url."""
951
name_transport = get_transport(name)
952
self.permit_url(name)
953
self.permit_url(name_transport.base)
955
def permit_url(self, url):
956
"""Declare that url is an ok url to use in this test.
958
Do this for memory transports, temporary test directory etc.
960
Do not do this for the current working directory, /tmp, or any other
961
preexisting non isolated url.
963
if not url.endswith('/'):
965
self._bzr_selftest_roots.append(url)
967
def permit_source_tree_branch_repo(self):
968
"""Permit the source tree bzr is running from to be opened.
970
Some code such as bzrlib.version attempts to read from the bzr branch
971
that bzr is executing from (if any). This method permits that directory
972
to be used in the test suite.
974
path = self.get_source_path()
975
self.record_directory_isolation()
978
workingtree.WorkingTree.open(path)
979
except (errors.NotBranchError, errors.NoWorkingTree):
982
self.enable_directory_isolation()
984
def _preopen_isolate_transport(self, transport):
985
"""Check that all transport openings are done in the test work area."""
986
while isinstance(transport, pathfilter.PathFilteringTransport):
987
# Unwrap pathfiltered transports
988
transport = transport.server.backing_transport.clone(
989
transport._filter('.'))
991
# ReadonlySmartTCPServer_for_testing decorates the backing transport
992
# urls it is given by prepending readonly+. This is appropriate as the
993
# client shouldn't know that the server is readonly (or not readonly).
994
# We could register all servers twice, with readonly+ prepending, but
995
# that makes for a long list; this is about the same but easier to
997
if url.startswith('readonly+'):
998
url = url[len('readonly+'):]
999
self._preopen_isolate_url(url)
1001
def _preopen_isolate_url(self, url):
1002
if not self._directory_isolation:
1004
if self._directory_isolation == 'record':
1005
self._bzr_selftest_roots.append(url)
1007
# This prevents all transports, including e.g. sftp ones backed on disk
1008
# from working unless they are explicitly granted permission. We then
1009
# depend on the code that sets up test transports to check that they are
1010
# appropriately isolated and enable their use by calling
1011
# self.permit_transport()
1012
if not osutils.is_inside_any(self._bzr_selftest_roots, url):
1013
raise errors.BzrError("Attempt to escape test isolation: %r %r"
1014
% (url, self._bzr_selftest_roots))
1016
def record_directory_isolation(self):
1017
"""Gather accessed directories to permit later access.
1019
This is used for tests that access the branch bzr is running from.
1021
self._directory_isolation = "record"
1023
def start_server(self, transport_server, backing_server=None):
1024
"""Start transport_server for this test.
1026
This starts the server, registers a cleanup for it and permits the
1027
server's urls to be used.
1029
if backing_server is None:
1030
transport_server.setUp()
1032
transport_server.setUp(backing_server)
1033
self.addCleanup(transport_server.tearDown)
1034
# Obtain a real transport because if the server supplies a password, it
1035
# will be hidden from the base on the client side.
1036
t = get_transport(transport_server.get_url())
1037
# Some transport servers effectively chroot the backing transport;
1038
# others like SFTPServer don't - users of the transport can walk up the
1039
# transport to read the entire backing transport. This wouldn't matter
1040
# except that the workdir tests are given - and that they expect the
1041
# server's url to point at - is one directory under the safety net. So
1042
# Branch operations into the transport will attempt to walk up one
1043
# directory. Chrooting all servers would avoid this but also mean that
1044
# we wouldn't be testing directly against non-root urls. Alternatively
1045
# getting the test framework to start the server with a backing server
1046
# at the actual safety net directory would work too, but this then
1047
# means that the self.get_url/self.get_transport methods would need
1048
# to transform all their results. On balance its cleaner to handle it
1049
# here, and permit a higher url when we have one of these transports.
1050
if t.base.endswith('/work/'):
1051
# we have safety net/test root/work
1052
t = t.clone('../..')
1053
elif isinstance(transport_server, server.SmartTCPServer_for_testing):
1054
# The smart server adds a path similar to work, which is traversed
1055
# up from by the client. But the server is chrooted - the actual
1056
# backing transport is not escaped from, and VFS requests to the
1057
# root will error (because they try to escape the chroot).
1059
while t2.base != t.base:
1062
self.permit_url(t.base)
1064
def _track_transports(self):
1065
"""Install checks for transport usage."""
1066
# TestCase has no safe place it can write to.
1067
self._bzr_selftest_roots = []
1068
# Currently the easiest way to be sure that nothing is going on is to
1069
# hook into bzr dir opening. This leaves a small window of error for
1070
# transport tests, but they are well known, and we can improve on this
1072
bzrdir.BzrDir.hooks.install_named_hook("pre_open",
1073
self._preopen_isolate_transport, "Check bzr directories are safe.")
1075
def _ndiff_strings(self, a, b):
1076
"""Return ndiff between two strings containing lines.
1078
A trailing newline is added if missing to make the strings
1080
if b and b[-1] != '\n':
1082
if a and a[-1] != '\n':
1084
difflines = difflib.ndiff(a.splitlines(True),
1086
linejunk=lambda x: False,
1087
charjunk=lambda x: False)
1088
return ''.join(difflines)
1090
def assertEqual(self, a, b, message=''):
1094
except UnicodeError, e:
1095
# If we can't compare without getting a UnicodeError, then
1096
# obviously they are different
1097
mutter('UnicodeError: %s', e)
1100
raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1102
pformat(a), pformat(b)))
1104
assertEquals = assertEqual
1106
def assertEqualDiff(self, a, b, message=None):
1107
"""Assert two texts are equal, if not raise an exception.
1109
This is intended for use with multi-line strings where it can
1110
be hard to find the differences by eye.
1112
# TODO: perhaps override assertEquals to call this for strings?
1116
message = "texts not equal:\n"
1118
message = 'first string is missing a final newline.\n'
1120
message = 'second string is missing a final newline.\n'
1121
raise AssertionError(message +
1122
self._ndiff_strings(a, b))
1124
def assertEqualMode(self, mode, mode_test):
1125
self.assertEqual(mode, mode_test,
1126
'mode mismatch %o != %o' % (mode, mode_test))
1128
def assertEqualStat(self, expected, actual):
1129
"""assert that expected and actual are the same stat result.
1131
:param expected: A stat result.
1132
:param actual: A stat result.
1133
:raises AssertionError: If the expected and actual stat values differ
1134
other than by atime.
1136
self.assertEqual(expected.st_size, actual.st_size)
1137
self.assertEqual(expected.st_mtime, actual.st_mtime)
1138
self.assertEqual(expected.st_ctime, actual.st_ctime)
1139
self.assertEqual(expected.st_dev, actual.st_dev)
1140
self.assertEqual(expected.st_ino, actual.st_ino)
1141
self.assertEqual(expected.st_mode, actual.st_mode)
1143
def assertLength(self, length, obj_with_len):
1144
"""Assert that obj_with_len is of length length."""
1145
if len(obj_with_len) != length:
1146
self.fail("Incorrect length: wanted %d, got %d for %r" % (
1147
length, len(obj_with_len), obj_with_len))
1149
def assertLogsError(self, exception_class, func, *args, **kwargs):
1150
"""Assert that func(*args, **kwargs) quietly logs a specific exception.
1152
from bzrlib import trace
1154
orig_log_exception_quietly = trace.log_exception_quietly
1157
orig_log_exception_quietly()
1158
captured.append(sys.exc_info())
1159
trace.log_exception_quietly = capture
1160
func(*args, **kwargs)
1162
trace.log_exception_quietly = orig_log_exception_quietly
1163
self.assertLength(1, captured)
1164
err = captured[0][1]
1165
self.assertIsInstance(err, exception_class)
1168
def assertPositive(self, val):
1169
"""Assert that val is greater than 0."""
1170
self.assertTrue(val > 0, 'expected a positive value, but got %s' % val)
1172
def assertNegative(self, val):
1173
"""Assert that val is less than 0."""
1174
self.assertTrue(val < 0, 'expected a negative value, but got %s' % val)
1176
def assertStartsWith(self, s, prefix):
1177
if not s.startswith(prefix):
1178
raise AssertionError('string %r does not start with %r' % (s, prefix))
1180
def assertEndsWith(self, s, suffix):
1181
"""Asserts that s ends with suffix."""
1182
if not s.endswith(suffix):
1183
raise AssertionError('string %r does not end with %r' % (s, suffix))
1185
def assertContainsRe(self, haystack, needle_re, flags=0):
1186
"""Assert that a contains something matching a regular expression."""
1187
if not re.search(needle_re, haystack, flags):
1188
if '\n' in haystack or len(haystack) > 60:
1189
# a long string, format it in a more readable way
1190
raise AssertionError(
1191
'pattern "%s" not found in\n"""\\\n%s"""\n'
1192
% (needle_re, haystack))
1194
raise AssertionError('pattern "%s" not found in "%s"'
1195
% (needle_re, haystack))
1197
def assertNotContainsRe(self, haystack, needle_re, flags=0):
1198
"""Assert that a does not match a regular expression"""
1199
if re.search(needle_re, haystack, flags):
1200
raise AssertionError('pattern "%s" found in "%s"'
1201
% (needle_re, haystack))
1203
def assertSubset(self, sublist, superlist):
1204
"""Assert that every entry in sublist is present in superlist."""
1205
missing = set(sublist) - set(superlist)
1206
if len(missing) > 0:
1207
raise AssertionError("value(s) %r not present in container %r" %
1208
(missing, superlist))
1210
def assertListRaises(self, excClass, func, *args, **kwargs):
1211
"""Fail unless excClass is raised when the iterator from func is used.
1213
Many functions can return generators this makes sure
1214
to wrap them in a list() call to make sure the whole generator
1215
is run, and that the proper exception is raised.
1218
list(func(*args, **kwargs))
1222
if getattr(excClass,'__name__', None) is not None:
1223
excName = excClass.__name__
1225
excName = str(excClass)
1226
raise self.failureException, "%s not raised" % excName
1228
def assertRaises(self, excClass, callableObj, *args, **kwargs):
1229
"""Assert that a callable raises a particular exception.
1231
:param excClass: As for the except statement, this may be either an
1232
exception class, or a tuple of classes.
1233
:param callableObj: A callable, will be passed ``*args`` and
1236
Returns the exception so that you can examine it.
1239
callableObj(*args, **kwargs)
1243
if getattr(excClass,'__name__', None) is not None:
1244
excName = excClass.__name__
1247
excName = str(excClass)
1248
raise self.failureException, "%s not raised" % excName
1250
def assertIs(self, left, right, message=None):
1251
if not (left is right):
1252
if message is not None:
1253
raise AssertionError(message)
1255
raise AssertionError("%r is not %r." % (left, right))
1257
def assertIsNot(self, left, right, message=None):
1259
if message is not None:
1260
raise AssertionError(message)
1262
raise AssertionError("%r is %r." % (left, right))
1264
def assertTransportMode(self, transport, path, mode):
1265
"""Fail if a path does not have mode "mode".
1267
If modes are not supported on this transport, the assertion is ignored.
1269
if not transport._can_roundtrip_unix_modebits():
1271
path_stat = transport.stat(path)
1272
actual_mode = stat.S_IMODE(path_stat.st_mode)
1273
self.assertEqual(mode, actual_mode,
1274
'mode of %r incorrect (%s != %s)'
1275
% (path, oct(mode), oct(actual_mode)))
1277
def assertIsSameRealPath(self, path1, path2):
1278
"""Fail if path1 and path2 points to different files"""
1279
self.assertEqual(osutils.realpath(path1),
1280
osutils.realpath(path2),
1281
"apparent paths:\na = %s\nb = %s\n," % (path1, path2))
1283
def assertIsInstance(self, obj, kls, msg=None):
1284
"""Fail if obj is not an instance of kls
1286
:param msg: Supplementary message to show if the assertion fails.
1288
if not isinstance(obj, kls):
1289
m = "%r is an instance of %s rather than %s" % (
1290
obj, obj.__class__, kls)
1295
def expectFailure(self, reason, assertion, *args, **kwargs):
1296
"""Invoke a test, expecting it to fail for the given reason.
1298
This is for assertions that ought to succeed, but currently fail.
1299
(The failure is *expected* but not *wanted*.) Please be very precise
1300
about the failure you're expecting. If a new bug is introduced,
1301
AssertionError should be raised, not KnownFailure.
1303
Frequently, expectFailure should be followed by an opposite assertion.
1306
Intended to be used with a callable that raises AssertionError as the
1307
'assertion' parameter. args and kwargs are passed to the 'assertion'.
1309
Raises KnownFailure if the test fails. Raises AssertionError if the
1314
self.expectFailure('Math is broken', self.assertNotEqual, 54,
1316
self.assertEqual(42, dynamic_val)
1318
This means that a dynamic_val of 54 will cause the test to raise
1319
a KnownFailure. Once math is fixed and the expectFailure is removed,
1320
only a dynamic_val of 42 will allow the test to pass. Anything other
1321
than 54 or 42 will cause an AssertionError.
1324
assertion(*args, **kwargs)
1325
except AssertionError:
1326
raise KnownFailure(reason)
1328
self.fail('Unexpected success. Should have failed: %s' % reason)
1330
def assertFileEqual(self, content, path):
1331
"""Fail if path does not contain 'content'."""
1332
self.failUnlessExists(path)
1333
f = file(path, 'rb')
1338
self.assertEqualDiff(content, s)
1340
def failUnlessExists(self, path):
1341
"""Fail unless path or paths, which may be abs or relative, exist."""
1342
if not isinstance(path, basestring):
1344
self.failUnlessExists(p)
1346
self.failUnless(osutils.lexists(path),path+" does not exist")
1348
def failIfExists(self, path):
1349
"""Fail if path or paths, which may be abs or relative, exist."""
1350
if not isinstance(path, basestring):
1352
self.failIfExists(p)
1354
self.failIf(osutils.lexists(path),path+" exists")
1356
def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1357
"""A helper for callDeprecated and applyDeprecated.
1359
:param a_callable: A callable to call.
1360
:param args: The positional arguments for the callable
1361
:param kwargs: The keyword arguments for the callable
1362
:return: A tuple (warnings, result). result is the result of calling
1363
a_callable(``*args``, ``**kwargs``).
1366
def capture_warnings(msg, cls=None, stacklevel=None):
1367
# we've hooked into a deprecation specific callpath,
1368
# only deprecations should getting sent via it.
1369
self.assertEqual(cls, DeprecationWarning)
1370
local_warnings.append(msg)
1371
original_warning_method = symbol_versioning.warn
1372
symbol_versioning.set_warning_method(capture_warnings)
1374
result = a_callable(*args, **kwargs)
1376
symbol_versioning.set_warning_method(original_warning_method)
1377
return (local_warnings, result)
1379
def applyDeprecated(self, deprecation_format, a_callable, *args, **kwargs):
1380
"""Call a deprecated callable without warning the user.
1382
Note that this only captures warnings raised by symbol_versioning.warn,
1383
not other callers that go direct to the warning module.
1385
To test that a deprecated method raises an error, do something like
1388
self.assertRaises(errors.ReservedId,
1389
self.applyDeprecated,
1390
deprecated_in((1, 5, 0)),
1394
:param deprecation_format: The deprecation format that the callable
1395
should have been deprecated with. This is the same type as the
1396
parameter to deprecated_method/deprecated_function. If the
1397
callable is not deprecated with this format, an assertion error
1399
:param a_callable: A callable to call. This may be a bound method or
1400
a regular function. It will be called with ``*args`` and
1402
:param args: The positional arguments for the callable
1403
:param kwargs: The keyword arguments for the callable
1404
:return: The result of a_callable(``*args``, ``**kwargs``)
1406
call_warnings, result = self._capture_deprecation_warnings(a_callable,
1408
expected_first_warning = symbol_versioning.deprecation_string(
1409
a_callable, deprecation_format)
1410
if len(call_warnings) == 0:
1411
self.fail("No deprecation warning generated by call to %s" %
1413
self.assertEqual(expected_first_warning, call_warnings[0])
1416
def callCatchWarnings(self, fn, *args, **kw):
1417
"""Call a callable that raises python warnings.
1419
The caller's responsible for examining the returned warnings.
1421
If the callable raises an exception, the exception is not
1422
caught and propagates up to the caller. In that case, the list
1423
of warnings is not available.
1425
:returns: ([warning_object, ...], fn_result)
1427
# XXX: This is not perfect, because it completely overrides the
1428
# warnings filters, and some code may depend on suppressing particular
1429
# warnings. It's the easiest way to insulate ourselves from -Werror,
1430
# though. -- Andrew, 20071062
1432
def _catcher(message, category, filename, lineno, file=None, line=None):
1433
# despite the name, 'message' is normally(?) a Warning subclass
1435
wlist.append(message)
1436
saved_showwarning = warnings.showwarning
1437
saved_filters = warnings.filters
1439
warnings.showwarning = _catcher
1440
warnings.filters = []
1441
result = fn(*args, **kw)
1443
warnings.showwarning = saved_showwarning
1444
warnings.filters = saved_filters
1445
return wlist, result
1447
def callDeprecated(self, expected, callable, *args, **kwargs):
1448
"""Assert that a callable is deprecated in a particular way.
1450
This is a very precise test for unusual requirements. The
1451
applyDeprecated helper function is probably more suited for most tests
1452
as it allows you to simply specify the deprecation format being used
1453
and will ensure that that is issued for the function being called.
1455
Note that this only captures warnings raised by symbol_versioning.warn,
1456
not other callers that go direct to the warning module. To catch
1457
general warnings, use callCatchWarnings.
1459
:param expected: a list of the deprecation warnings expected, in order
1460
:param callable: The callable to call
1461
:param args: The positional arguments for the callable
1462
:param kwargs: The keyword arguments for the callable
1464
call_warnings, result = self._capture_deprecation_warnings(callable,
1466
self.assertEqual(expected, call_warnings)
1469
def _startLogFile(self):
1470
"""Send bzr and test log messages to a temporary file.
1472
The file is removed as the test is torn down.
1474
fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
1475
self._log_file = os.fdopen(fileno, 'w+')
1476
self._log_memento = bzrlib.trace.push_log_file(self._log_file)
1477
self._log_file_name = name
1478
self.addCleanup(self._finishLogFile)
1480
def _finishLogFile(self):
1481
"""Finished with the log file.
1483
Close the file and delete it, unless setKeepLogfile was called.
1485
if self._log_file is None:
1487
bzrlib.trace.pop_log_file(self._log_memento)
1488
self._log_file.close()
1489
self._log_file = None
1490
if not self._keep_log_file:
1491
os.remove(self._log_file_name)
1492
self._log_file_name = None
1494
def setKeepLogfile(self):
1495
"""Make the logfile not be deleted when _finishLogFile is called."""
1496
self._keep_log_file = True
1498
def thisFailsStrictLockCheck(self):
1499
"""It is known that this test would fail with -Dstrict_locks.
1501
By default, all tests are run with strict lock checking unless
1502
-Edisable_lock_checks is supplied. However there are some tests which
1503
we know fail strict locks at this point that have not been fixed.
1504
They should call this function to disable the strict checking.
1506
This should be used sparingly, it is much better to fix the locking
1507
issues rather than papering over the problem by calling this function.
1509
debug.debug_flags.discard('strict_locks')
1511
def addCleanup(self, callable, *args, **kwargs):
1512
"""Arrange to run a callable when this case is torn down.
1514
Callables are run in the reverse of the order they are registered,
1515
ie last-in first-out.
1517
self._cleanups.append((callable, args, kwargs))
1519
def _cleanEnvironment(self):
1521
'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
1522
'HOME': os.getcwd(),
1523
# bzr now uses the Win32 API and doesn't rely on APPDATA, but the
1524
# tests do check our impls match APPDATA
1525
'BZR_EDITOR': None, # test_msgeditor manipulates this variable
1529
'BZREMAIL': None, # may still be present in the environment
1531
'BZR_PROGRESS_BAR': None,
1533
'BZR_PLUGIN_PATH': None,
1534
# Make sure that any text ui tests are consistent regardless of
1535
# the environment the test case is run in; you may want tests that
1536
# test other combinations. 'dumb' is a reasonable guess for tests
1537
# going to a pipe or a StringIO.
1542
'SSH_AUTH_SOCK': None,
1546
'https_proxy': None,
1547
'HTTPS_PROXY': None,
1552
# Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
1553
# least. If you do (care), please update this comment
1557
'BZR_REMOTE_PATH': None,
1560
self.addCleanup(self._restoreEnvironment)
1561
for name, value in new_env.iteritems():
1562
self._captureVar(name, value)
1564
def _captureVar(self, name, newvalue):
1565
"""Set an environment variable, and reset it when finished."""
1566
self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
1568
def _restore_debug_flags(self):
1569
debug.debug_flags.clear()
1570
debug.debug_flags.update(self._preserved_debug_flags)
1572
def _restoreEnvironment(self):
1573
for name, value in self.__old_env.iteritems():
1574
osutils.set_or_unset_env(name, value)
1576
def _restoreHooks(self):
1577
for klass, (name, hooks) in self._preserved_hooks.items():
1578
setattr(klass, name, hooks)
1580
def knownFailure(self, reason):
1581
"""This test has failed for some known reason."""
1582
raise KnownFailure(reason)
1584
def _do_skip(self, result, reason):
1585
addSkip = getattr(result, 'addSkip', None)
1586
if not callable(addSkip):
1587
result.addError(self, sys.exc_info())
1589
addSkip(self, reason)
1591
def run(self, result=None):
1592
if result is None: result = self.defaultTestResult()
1593
for feature in getattr(self, '_test_needs_features', []):
1594
if not feature.available():
1595
result.startTest(self)
1596
if getattr(result, 'addNotSupported', None):
1597
result.addNotSupported(self, feature)
1599
result.addSuccess(self)
1600
result.stopTest(self)
1604
result.startTest(self)
1605
absent_attr = object()
1607
method_name = getattr(self, '_testMethodName', absent_attr)
1608
if method_name is absent_attr:
1610
method_name = getattr(self, '_TestCase__testMethodName')
1611
testMethod = getattr(self, method_name)
1615
if not self._bzr_test_setUp_run:
1617
"test setUp did not invoke "
1618
"bzrlib.tests.TestCase's setUp")
1619
except KeyboardInterrupt:
1622
except TestSkipped, e:
1623
self._do_skip(result, e.args[0])
1627
result.addError(self, sys.exc_info())
1635
except self.failureException:
1636
result.addFailure(self, sys.exc_info())
1637
except TestSkipped, e:
1639
reason = "No reason given."
1642
self._do_skip(result, reason)
1643
except KeyboardInterrupt:
1647
result.addError(self, sys.exc_info())
1651
if not self._bzr_test_tearDown_run:
1653
"test tearDown did not invoke "
1654
"bzrlib.tests.TestCase's tearDown")
1655
except KeyboardInterrupt:
1659
result.addError(self, sys.exc_info())
1662
if ok: result.addSuccess(self)
1664
result.stopTest(self)
1666
except TestNotApplicable:
1667
# Not moved from the result [yet].
1670
except KeyboardInterrupt:
1675
for attr_name in self.attrs_to_keep:
1676
if attr_name in self.__dict__:
1677
saved_attrs[attr_name] = self.__dict__[attr_name]
1678
self.__dict__ = saved_attrs
1682
self._log_contents = ''
1683
self._bzr_test_tearDown_run = True
1684
unittest.TestCase.tearDown(self)
1686
def time(self, callable, *args, **kwargs):
1687
"""Run callable and accrue the time it takes to the benchmark time.
1689
If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
1690
this will cause lsprofile statistics to be gathered and stored in
1693
if self._benchtime is None:
1697
if not self._gather_lsprof_in_benchmarks:
1698
return callable(*args, **kwargs)
1700
# record this benchmark
1701
ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
1703
self._benchcalls.append(((callable, args, kwargs), stats))
1706
self._benchtime += time.time() - start
1708
def _runCleanups(self):
1709
"""Run registered cleanup functions.
1711
This should only be called from TestCase.tearDown.
1713
# TODO: Perhaps this should keep running cleanups even if
1714
# one of them fails?
1716
# Actually pop the cleanups from the list so tearDown running
1717
# twice is safe (this happens for skipped tests).
1718
while self._cleanups:
1719
cleanup, args, kwargs = self._cleanups.pop()
1720
cleanup(*args, **kwargs)
1722
def log(self, *args):
1725
def _get_log(self, keep_log_file=False):
1726
"""Get the log from bzrlib.trace calls from this test.
1728
:param keep_log_file: When True, if the log is still a file on disk
1729
leave it as a file on disk. When False, if the log is still a file
1730
on disk, the log file is deleted and the log preserved as
1732
:return: A string containing the log.
1734
# flush the log file, to get all content
1736
if bzrlib.trace._trace_file:
1737
bzrlib.trace._trace_file.flush()
1738
if self._log_contents:
1739
# XXX: this can hardly contain the content flushed above --vila
1741
return self._log_contents
1742
if self._log_file_name is not None:
1743
logfile = open(self._log_file_name)
1745
log_contents = logfile.read()
1748
if not keep_log_file:
1749
self._log_contents = log_contents
1751
os.remove(self._log_file_name)
1753
if sys.platform == 'win32' and e.errno == errno.EACCES:
1754
sys.stderr.write(('Unable to delete log file '
1755
' %r\n' % self._log_file_name))
1760
return "DELETED log file to reduce memory footprint"
1762
def requireFeature(self, feature):
1763
"""This test requires a specific feature is available.
1765
:raises UnavailableFeature: When feature is not available.
1767
if not feature.available():
1768
raise UnavailableFeature(feature)
1770
def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
1772
"""Run bazaar command line, splitting up a string command line."""
1773
if isinstance(args, basestring):
1774
# shlex don't understand unicode strings,
1775
# so args should be plain string (bialix 20070906)
1776
args = list(shlex.split(str(args)))
1777
return self._run_bzr_core(args, retcode=retcode,
1778
encoding=encoding, stdin=stdin, working_dir=working_dir,
1781
def _run_bzr_core(self, args, retcode, encoding, stdin,
1783
if encoding is None:
1784
encoding = osutils.get_user_encoding()
1785
stdout = StringIOWrapper()
1786
stderr = StringIOWrapper()
1787
stdout.encoding = encoding
1788
stderr.encoding = encoding
1790
self.log('run bzr: %r', args)
1791
# FIXME: don't call into logging here
1792
handler = logging.StreamHandler(stderr)
1793
handler.setLevel(logging.INFO)
1794
logger = logging.getLogger('')
1795
logger.addHandler(handler)
1796
old_ui_factory = ui.ui_factory
1797
ui.ui_factory = TestUIFactory(stdin=stdin, stdout=stdout, stderr=stderr)
1800
if working_dir is not None:
1801
cwd = osutils.getcwd()
1802
os.chdir(working_dir)
1805
result = self.apply_redirected(ui.ui_factory.stdin,
1807
bzrlib.commands.run_bzr_catch_user_errors,
1810
logger.removeHandler(handler)
1811
ui.ui_factory = old_ui_factory
1815
out = stdout.getvalue()
1816
err = stderr.getvalue()
1818
self.log('output:\n%r', out)
1820
self.log('errors:\n%r', err)
1821
if retcode is not None:
1822
self.assertEquals(retcode, result,
1823
message='Unexpected return code')
1824
return result, out, err
1826
def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
1827
working_dir=None, error_regexes=[], output_encoding=None):
1828
"""Invoke bzr, as if it were run from the command line.
1830
The argument list should not include the bzr program name - the
1831
first argument is normally the bzr command. Arguments may be
1832
passed in three ways:
1834
1- A list of strings, eg ["commit", "a"]. This is recommended
1835
when the command contains whitespace or metacharacters, or
1836
is built up at run time.
1838
2- A single string, eg "add a". This is the most convenient
1839
for hardcoded commands.
1841
This runs bzr through the interface that catches and reports
1842
errors, and with logging set to something approximating the
1843
default, so that error reporting can be checked.
1845
This should be the main method for tests that want to exercise the
1846
overall behavior of the bzr application (rather than a unit test
1847
or a functional test of the library.)
1849
This sends the stdout/stderr results into the test's log,
1850
where it may be useful for debugging. See also run_captured.
1852
:keyword stdin: A string to be used as stdin for the command.
1853
:keyword retcode: The status code the command should return;
1855
:keyword working_dir: The directory to run the command in
1856
:keyword error_regexes: A list of expected error messages. If
1857
specified they must be seen in the error output of the command.
1859
retcode, out, err = self._run_bzr_autosplit(
1864
working_dir=working_dir,
1866
self.assertIsInstance(error_regexes, (list, tuple))
1867
for regex in error_regexes:
1868
self.assertContainsRe(err, regex)
1871
def run_bzr_error(self, error_regexes, *args, **kwargs):
1872
"""Run bzr, and check that stderr contains the supplied regexes
1874
:param error_regexes: Sequence of regular expressions which
1875
must each be found in the error output. The relative ordering
1877
:param args: command-line arguments for bzr
1878
:param kwargs: Keyword arguments which are interpreted by run_bzr
1879
This function changes the default value of retcode to be 3,
1880
since in most cases this is run when you expect bzr to fail.
1882
:return: (out, err) The actual output of running the command (in case
1883
you want to do more inspection)
1887
# Make sure that commit is failing because there is nothing to do
1888
self.run_bzr_error(['no changes to commit'],
1889
['commit', '-m', 'my commit comment'])
1890
# Make sure --strict is handling an unknown file, rather than
1891
# giving us the 'nothing to do' error
1892
self.build_tree(['unknown'])
1893
self.run_bzr_error(['Commit refused because there are unknown files'],
1894
['commit', --strict', '-m', 'my commit comment'])
1896
kwargs.setdefault('retcode', 3)
1897
kwargs['error_regexes'] = error_regexes
1898
out, err = self.run_bzr(*args, **kwargs)
1901
def run_bzr_subprocess(self, *args, **kwargs):
1902
"""Run bzr in a subprocess for testing.
1904
This starts a new Python interpreter and runs bzr in there.
1905
This should only be used for tests that have a justifiable need for
1906
this isolation: e.g. they are testing startup time, or signal
1907
handling, or early startup code, etc. Subprocess code can't be
1908
profiled or debugged so easily.
1910
:keyword retcode: The status code that is expected. Defaults to 0. If
1911
None is supplied, the status code is not checked.
1912
:keyword env_changes: A dictionary which lists changes to environment
1913
variables. A value of None will unset the env variable.
1914
The values must be strings. The change will only occur in the
1915
child, so you don't need to fix the environment after running.
1916
:keyword universal_newlines: Convert CRLF => LF
1917
:keyword allow_plugins: By default the subprocess is run with
1918
--no-plugins to ensure test reproducibility. Also, it is possible
1919
for system-wide plugins to create unexpected output on stderr,
1920
which can cause unnecessary test failures.
1922
env_changes = kwargs.get('env_changes', {})
1923
working_dir = kwargs.get('working_dir', None)
1924
allow_plugins = kwargs.get('allow_plugins', False)
1926
if isinstance(args[0], list):
1928
elif isinstance(args[0], basestring):
1929
args = list(shlex.split(args[0]))
1931
raise ValueError("passing varargs to run_bzr_subprocess")
1932
process = self.start_bzr_subprocess(args, env_changes=env_changes,
1933
working_dir=working_dir,
1934
allow_plugins=allow_plugins)
1935
# We distinguish between retcode=None and retcode not passed.
1936
supplied_retcode = kwargs.get('retcode', 0)
1937
return self.finish_bzr_subprocess(process, retcode=supplied_retcode,
1938
universal_newlines=kwargs.get('universal_newlines', False),
1941
def start_bzr_subprocess(self, process_args, env_changes=None,
1942
skip_if_plan_to_signal=False,
1944
allow_plugins=False):
1945
"""Start bzr in a subprocess for testing.
1947
This starts a new Python interpreter and runs bzr in there.
1948
This should only be used for tests that have a justifiable need for
1949
this isolation: e.g. they are testing startup time, or signal
1950
handling, or early startup code, etc. Subprocess code can't be
1951
profiled or debugged so easily.
1953
:param process_args: a list of arguments to pass to the bzr executable,
1954
for example ``['--version']``.
1955
:param env_changes: A dictionary which lists changes to environment
1956
variables. A value of None will unset the env variable.
1957
The values must be strings. The change will only occur in the
1958
child, so you don't need to fix the environment after running.
1959
:param skip_if_plan_to_signal: raise TestSkipped when true and os.kill
1961
:param allow_plugins: If False (default) pass --no-plugins to bzr.
1963
:returns: Popen object for the started process.
1965
if skip_if_plan_to_signal:
1966
if not getattr(os, 'kill', None):
1967
raise TestSkipped("os.kill not available.")
1969
if env_changes is None:
1973
def cleanup_environment():
1974
for env_var, value in env_changes.iteritems():
1975
old_env[env_var] = osutils.set_or_unset_env(env_var, value)
1977
def restore_environment():
1978
for env_var, value in old_env.iteritems():
1979
osutils.set_or_unset_env(env_var, value)
1981
bzr_path = self.get_bzr_path()
1984
if working_dir is not None:
1985
cwd = osutils.getcwd()
1986
os.chdir(working_dir)
1989
# win32 subprocess doesn't support preexec_fn
1990
# so we will avoid using it on all platforms, just to
1991
# make sure the code path is used, and we don't break on win32
1992
cleanup_environment()
1993
command = [sys.executable]
1994
# frozen executables don't need the path to bzr
1995
if getattr(sys, "frozen", None) is None:
1996
command.append(bzr_path)
1997
if not allow_plugins:
1998
command.append('--no-plugins')
1999
command.extend(process_args)
2000
process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
2002
restore_environment()
2008
def _popen(self, *args, **kwargs):
2009
"""Place a call to Popen.
2011
Allows tests to override this method to intercept the calls made to
2012
Popen for introspection.
2014
return Popen(*args, **kwargs)
2016
def get_source_path(self):
2017
"""Return the path of the directory containing bzrlib."""
2018
return os.path.dirname(os.path.dirname(bzrlib.__file__))
2020
def get_bzr_path(self):
2021
"""Return the path of the 'bzr' executable for this test suite."""
2022
bzr_path = self.get_source_path()+'/bzr'
2023
if not os.path.isfile(bzr_path):
2024
# We are probably installed. Assume sys.argv is the right file
2025
bzr_path = sys.argv[0]
2028
def finish_bzr_subprocess(self, process, retcode=0, send_signal=None,
2029
universal_newlines=False, process_args=None):
2030
"""Finish the execution of process.
2032
:param process: the Popen object returned from start_bzr_subprocess.
2033
:param retcode: The status code that is expected. Defaults to 0. If
2034
None is supplied, the status code is not checked.
2035
:param send_signal: an optional signal to send to the process.
2036
:param universal_newlines: Convert CRLF => LF
2037
:returns: (stdout, stderr)
2039
if send_signal is not None:
2040
os.kill(process.pid, send_signal)
2041
out, err = process.communicate()
2043
if universal_newlines:
2044
out = out.replace('\r\n', '\n')
2045
err = err.replace('\r\n', '\n')
2047
if retcode is not None and retcode != process.returncode:
2048
if process_args is None:
2049
process_args = "(unknown args)"
2050
mutter('Output of bzr %s:\n%s', process_args, out)
2051
mutter('Error for bzr %s:\n%s', process_args, err)
2052
self.fail('Command bzr %s failed with retcode %s != %s'
2053
% (process_args, retcode, process.returncode))
2056
def check_inventory_shape(self, inv, shape):
2057
"""Compare an inventory to a list of expected names.
2059
Fail if they are not precisely equal.
2062
shape = list(shape) # copy
2063
for path, ie in inv.entries():
2064
name = path.replace('\\', '/')
2065
if ie.kind == 'directory':
2072
self.fail("expected paths not found in inventory: %r" % shape)
2074
self.fail("unexpected paths found in inventory: %r" % extras)
2076
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2077
a_callable=None, *args, **kwargs):
2078
"""Call callable with redirected std io pipes.
2080
Returns the return code."""
2081
if not callable(a_callable):
2082
raise ValueError("a_callable must be callable.")
2084
stdin = StringIO("")
2086
if getattr(self, "_log_file", None) is not None:
2087
stdout = self._log_file
2091
if getattr(self, "_log_file", None is not None):
2092
stderr = self._log_file
2095
real_stdin = sys.stdin
2096
real_stdout = sys.stdout
2097
real_stderr = sys.stderr
2102
return a_callable(*args, **kwargs)
2104
sys.stdout = real_stdout
2105
sys.stderr = real_stderr
2106
sys.stdin = real_stdin
2108
def reduceLockdirTimeout(self):
2109
"""Reduce the default lock timeout for the duration of the test, so that
2110
if LockContention occurs during a test, it does so quickly.
2112
Tests that expect to provoke LockContention errors should call this.
2114
orig_timeout = bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS
2116
bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = orig_timeout
2117
self.addCleanup(resetTimeout)
2118
bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = 0
2120
def make_utf8_encoded_stringio(self, encoding_type=None):
2121
"""Return a StringIOWrapper instance, that will encode Unicode
2124
if encoding_type is None:
2125
encoding_type = 'strict'
2127
output_encoding = 'utf-8'
2128
sio = codecs.getwriter(output_encoding)(sio, errors=encoding_type)
2129
sio.encoding = output_encoding
2132
def disable_verb(self, verb):
2133
"""Disable a smart server verb for one test."""
2134
from bzrlib.smart import request
2135
request_handlers = request.request_handlers
2136
orig_method = request_handlers.get(verb)
2137
request_handlers.remove(verb)
2139
request_handlers.register(verb, orig_method)
2140
self.addCleanup(restoreVerb)
2143
class CapturedCall(object):
2144
"""A helper for capturing smart server calls for easy debug analysis."""
2146
def __init__(self, params, prefix_length):
2147
"""Capture the call with params and skip prefix_length stack frames."""
2150
# The last 5 frames are the __init__, the hook frame, and 3 smart
2151
# client frames. Beyond this we could get more clever, but this is good
2153
stack = traceback.extract_stack()[prefix_length:-5]
2154
self.stack = ''.join(traceback.format_list(stack))
2157
return self.call.method
2160
return self.call.method
2166
class TestCaseWithMemoryTransport(TestCase):
2167
"""Common test class for tests that do not need disk resources.
2169
Tests that need disk resources should derive from TestCaseWithTransport.
2171
TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
2173
For TestCaseWithMemoryTransport the test_home_dir is set to the name of
2174
a directory which does not exist. This serves to help ensure test isolation
2175
is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
2176
must exist. However, TestCaseWithMemoryTransport does not offer local
2177
file defaults for the transport in tests, nor does it obey the command line
2178
override, so tests that accidentally write to the common directory should
2181
:cvar TEST_ROOT: Directory containing all temporary directories, plus
2182
a .bzr directory that stops us ascending higher into the filesystem.
2188
def __init__(self, methodName='runTest'):
2189
# allow test parameterization after test construction and before test
2190
# execution. Variables that the parameterizer sets need to be
2191
# ones that are not set by setUp, or setUp will trash them.
2192
super(TestCaseWithMemoryTransport, self).__init__(methodName)
2193
self.vfs_transport_factory = default_transport
2194
self.transport_server = None
2195
self.transport_readonly_server = None
2196
self.__vfs_server = None
2198
def get_transport(self, relpath=None):
2199
"""Return a writeable transport.
2201
This transport is for the test scratch space relative to
2204
:param relpath: a path relative to the base url.
2206
t = get_transport(self.get_url(relpath))
2207
self.assertFalse(t.is_readonly())
2210
def get_readonly_transport(self, relpath=None):
2211
"""Return a readonly transport for the test scratch space
2213
This can be used to test that operations which should only need
2214
readonly access in fact do not try to write.
2216
:param relpath: a path relative to the base url.
2218
t = get_transport(self.get_readonly_url(relpath))
2219
self.assertTrue(t.is_readonly())
2222
def create_transport_readonly_server(self):
2223
"""Create a transport server from class defined at init.
2225
This is mostly a hook for daughter classes.
2227
return self.transport_readonly_server()
2229
def get_readonly_server(self):
2230
"""Get the server instance for the readonly transport
2232
This is useful for some tests with specific servers to do diagnostics.
2234
if self.__readonly_server is None:
2235
if self.transport_readonly_server is None:
2236
# readonly decorator requested
2237
self.__readonly_server = ReadonlyServer()
2239
# explicit readonly transport.
2240
self.__readonly_server = self.create_transport_readonly_server()
2241
self.start_server(self.__readonly_server,
2242
self.get_vfs_only_server())
2243
return self.__readonly_server
2245
def get_readonly_url(self, relpath=None):
2246
"""Get a URL for the readonly transport.
2248
This will either be backed by '.' or a decorator to the transport
2249
used by self.get_url()
2250
relpath provides for clients to get a path relative to the base url.
2251
These should only be downwards relative, not upwards.
2253
base = self.get_readonly_server().get_url()
2254
return self._adjust_url(base, relpath)
2256
def get_vfs_only_server(self):
2257
"""Get the vfs only read/write server instance.
2259
This is useful for some tests with specific servers that need
2262
For TestCaseWithMemoryTransport this is always a MemoryServer, and there
2263
is no means to override it.
2265
if self.__vfs_server is None:
2266
self.__vfs_server = MemoryServer()
2267
self.start_server(self.__vfs_server)
2268
return self.__vfs_server
2270
def get_server(self):
2271
"""Get the read/write server instance.
2273
This is useful for some tests with specific servers that need
2276
This is built from the self.transport_server factory. If that is None,
2277
then the self.get_vfs_server is returned.
2279
if self.__server is None:
2280
if (self.transport_server is None or self.transport_server is
2281
self.vfs_transport_factory):
2282
self.__server = self.get_vfs_only_server()
2284
# bring up a decorated means of access to the vfs only server.
2285
self.__server = self.transport_server()
2286
self.start_server(self.__server, self.get_vfs_only_server())
2287
return self.__server
2289
def _adjust_url(self, base, relpath):
2290
"""Get a URL (or maybe a path) for the readwrite transport.
2292
This will either be backed by '.' or to an equivalent non-file based
2294
relpath provides for clients to get a path relative to the base url.
2295
These should only be downwards relative, not upwards.
2297
if relpath is not None and relpath != '.':
2298
if not base.endswith('/'):
2300
# XXX: Really base should be a url; we did after all call
2301
# get_url()! But sometimes it's just a path (from
2302
# LocalAbspathServer), and it'd be wrong to append urlescaped data
2303
# to a non-escaped local path.
2304
if base.startswith('./') or base.startswith('/'):
2307
base += urlutils.escape(relpath)
2310
def get_url(self, relpath=None):
2311
"""Get a URL (or maybe a path) for the readwrite transport.
2313
This will either be backed by '.' or to an equivalent non-file based
2315
relpath provides for clients to get a path relative to the base url.
2316
These should only be downwards relative, not upwards.
2318
base = self.get_server().get_url()
2319
return self._adjust_url(base, relpath)
2321
def get_vfs_only_url(self, relpath=None):
2322
"""Get a URL (or maybe a path for the plain old vfs transport.
2324
This will never be a smart protocol. It always has all the
2325
capabilities of the local filesystem, but it might actually be a
2326
MemoryTransport or some other similar virtual filesystem.
2328
This is the backing transport (if any) of the server returned by
2329
get_url and get_readonly_url.
2331
:param relpath: provides for clients to get a path relative to the base
2332
url. These should only be downwards relative, not upwards.
2335
base = self.get_vfs_only_server().get_url()
2336
return self._adjust_url(base, relpath)
2338
def _create_safety_net(self):
2339
"""Make a fake bzr directory.
2341
This prevents any tests propagating up onto the TEST_ROOT directory's
2344
root = TestCaseWithMemoryTransport.TEST_ROOT
2345
bzrdir.BzrDir.create_standalone_workingtree(root)
2347
def _check_safety_net(self):
2348
"""Check that the safety .bzr directory have not been touched.
2350
_make_test_root have created a .bzr directory to prevent tests from
2351
propagating. This method ensures than a test did not leaked.
2353
root = TestCaseWithMemoryTransport.TEST_ROOT
2354
self.permit_url(get_transport(root).base)
2355
wt = workingtree.WorkingTree.open(root)
2356
last_rev = wt.last_revision()
2357
if last_rev != 'null:':
2358
# The current test have modified the /bzr directory, we need to
2359
# recreate a new one or all the followng tests will fail.
2360
# If you need to inspect its content uncomment the following line
2361
# import pdb; pdb.set_trace()
2362
_rmtree_temp_dir(root + '/.bzr')
2363
self._create_safety_net()
2364
raise AssertionError('%s/.bzr should not be modified' % root)
2366
def _make_test_root(self):
2367
if TestCaseWithMemoryTransport.TEST_ROOT is None:
2368
# Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
2369
root = osutils.realpath(osutils.mkdtemp(prefix='testbzr-',
2371
TestCaseWithMemoryTransport.TEST_ROOT = root
2373
self._create_safety_net()
2375
# The same directory is used by all tests, and we're not
2376
# specifically told when all tests are finished. This will do.
2377
atexit.register(_rmtree_temp_dir, root)
2379
self.permit_dir(TestCaseWithMemoryTransport.TEST_ROOT)
2380
self.addCleanup(self._check_safety_net)
2382
def makeAndChdirToTestDir(self):
2383
"""Create a temporary directories for this one test.
2385
This must set self.test_home_dir and self.test_dir and chdir to
2388
For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this test.
2390
os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2391
self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
2392
self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
2393
self.permit_dir(self.test_dir)
2395
def make_branch(self, relpath, format=None):
2396
"""Create a branch on the transport at relpath."""
2397
repo = self.make_repository(relpath, format=format)
2398
return repo.bzrdir.create_branch()
2400
def make_bzrdir(self, relpath, format=None):
2402
# might be a relative or absolute path
2403
maybe_a_url = self.get_url(relpath)
2404
segments = maybe_a_url.rsplit('/', 1)
2405
t = get_transport(maybe_a_url)
2406
if len(segments) > 1 and segments[-1] not in ('', '.'):
2410
if isinstance(format, basestring):
2411
format = bzrdir.format_registry.make_bzrdir(format)
2412
return format.initialize_on_transport(t)
2413
except errors.UninitializableFormat:
2414
raise TestSkipped("Format %s is not initializable." % format)
2416
def make_repository(self, relpath, shared=False, format=None):
2417
"""Create a repository on our default transport at relpath.
2419
Note that relpath must be a relative path, not a full url.
2421
# FIXME: If you create a remoterepository this returns the underlying
2422
# real format, which is incorrect. Actually we should make sure that
2423
# RemoteBzrDir returns a RemoteRepository.
2424
# maybe mbp 20070410
2425
made_control = self.make_bzrdir(relpath, format=format)
2426
return made_control.create_repository(shared=shared)
2428
def make_smart_server(self, path):
2429
smart_server = server.SmartTCPServer_for_testing()
2430
self.start_server(smart_server, self.get_server())
2431
remote_transport = get_transport(smart_server.get_url()).clone(path)
2432
return remote_transport
2434
def make_branch_and_memory_tree(self, relpath, format=None):
2435
"""Create a branch on the default transport and a MemoryTree for it."""
2436
b = self.make_branch(relpath, format=format)
2437
return memorytree.MemoryTree.create_on_branch(b)
2439
def make_branch_builder(self, relpath, format=None):
2440
branch = self.make_branch(relpath, format=format)
2441
return branchbuilder.BranchBuilder(branch=branch)
2443
def overrideEnvironmentForTesting(self):
2444
os.environ['HOME'] = self.test_home_dir
2445
os.environ['BZR_HOME'] = self.test_home_dir
2448
super(TestCaseWithMemoryTransport, self).setUp()
2449
self._make_test_root()
2450
_currentdir = os.getcwdu()
2451
def _leaveDirectory():
2452
os.chdir(_currentdir)
2453
self.addCleanup(_leaveDirectory)
2454
self.makeAndChdirToTestDir()
2455
self.overrideEnvironmentForTesting()
2456
self.__readonly_server = None
2457
self.__server = None
2458
self.reduceLockdirTimeout()
2460
def setup_smart_server_with_call_log(self):
2461
"""Sets up a smart server as the transport server with a call log."""
2462
self.transport_server = server.SmartTCPServer_for_testing
2463
self.hpss_calls = []
2465
# Skip the current stack down to the caller of
2466
# setup_smart_server_with_call_log
2467
prefix_length = len(traceback.extract_stack()) - 2
2468
def capture_hpss_call(params):
2469
self.hpss_calls.append(
2470
CapturedCall(params, prefix_length))
2471
client._SmartClient.hooks.install_named_hook(
2472
'call', capture_hpss_call, None)
2474
def reset_smart_call_log(self):
2475
self.hpss_calls = []
2478
class TestCaseInTempDir(TestCaseWithMemoryTransport):
2479
"""Derived class that runs a test within a temporary directory.
2481
This is useful for tests that need to create a branch, etc.
2483
The directory is created in a slightly complex way: for each
2484
Python invocation, a new temporary top-level directory is created.
2485
All test cases create their own directory within that. If the
2486
tests complete successfully, the directory is removed.
2488
:ivar test_base_dir: The path of the top-level directory for this
2489
test, which contains a home directory and a work directory.
2491
:ivar test_home_dir: An initially empty directory under test_base_dir
2492
which is used as $HOME for this test.
2494
:ivar test_dir: A directory under test_base_dir used as the current
2495
directory when the test proper is run.
2498
OVERRIDE_PYTHON = 'python'
2500
def check_file_contents(self, filename, expect):
2501
self.log("check contents of file %s" % filename)
2502
contents = file(filename, 'r').read()
2503
if contents != expect:
2504
self.log("expected: %r" % expect)
2505
self.log("actually: %r" % contents)
2506
self.fail("contents of %s not as expected" % filename)
2508
def _getTestDirPrefix(self):
2509
# create a directory within the top level test directory
2510
if sys.platform in ('win32', 'cygwin'):
2511
name_prefix = re.sub('[<>*=+",:;_/\\-]', '_', self.id())
2512
# windows is likely to have path-length limits so use a short name
2513
name_prefix = name_prefix[-30:]
2515
name_prefix = re.sub('[/]', '_', self.id())
2518
def makeAndChdirToTestDir(self):
2519
"""See TestCaseWithMemoryTransport.makeAndChdirToTestDir().
2521
For TestCaseInTempDir we create a temporary directory based on the test
2522
name and then create two subdirs - test and home under it.
2524
name_prefix = osutils.pathjoin(TestCaseWithMemoryTransport.TEST_ROOT,
2525
self._getTestDirPrefix())
2527
for i in range(100):
2528
if os.path.exists(name):
2529
name = name_prefix + '_' + str(i)
2531
# now create test and home directories within this dir
2532
self.test_base_dir = name
2533
self.addCleanup(self.deleteTestDir)
2534
os.mkdir(self.test_base_dir)
2536
self.permit_dir(self.test_base_dir)
2537
# 'sprouting' and 'init' of a branch both walk up the tree to find
2538
# stacking policy to honour; create a bzr dir with an unshared
2539
# repository (but not a branch - our code would be trying to escape
2540
# then!) to stop them, and permit it to be read.
2541
# control = bzrdir.BzrDir.create(self.test_base_dir)
2542
# control.create_repository()
2543
self.test_home_dir = self.test_base_dir + '/home'
2544
os.mkdir(self.test_home_dir)
2545
self.test_dir = self.test_base_dir + '/work'
2546
os.mkdir(self.test_dir)
2547
os.chdir(self.test_dir)
2548
# put name of test inside
2549
f = file(self.test_base_dir + '/name', 'w')
2555
def deleteTestDir(self):
2556
os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2557
_rmtree_temp_dir(self.test_base_dir)
2559
def build_tree(self, shape, line_endings='binary', transport=None):
2560
"""Build a test tree according to a pattern.
2562
shape is a sequence of file specifications. If the final
2563
character is '/', a directory is created.
2565
This assumes that all the elements in the tree being built are new.
2567
This doesn't add anything to a branch.
2569
:type shape: list or tuple.
2570
:param line_endings: Either 'binary' or 'native'
2571
in binary mode, exact contents are written in native mode, the
2572
line endings match the default platform endings.
2573
:param transport: A transport to write to, for building trees on VFS's.
2574
If the transport is readonly or None, "." is opened automatically.
2577
if type(shape) not in (list, tuple):
2578
raise AssertionError("Parameter 'shape' should be "
2579
"a list or a tuple. Got %r instead" % (shape,))
2580
# It's OK to just create them using forward slashes on windows.
2581
if transport is None or transport.is_readonly():
2582
transport = get_transport(".")
2584
self.assertIsInstance(name, basestring)
2586
transport.mkdir(urlutils.escape(name[:-1]))
2588
if line_endings == 'binary':
2590
elif line_endings == 'native':
2593
raise errors.BzrError(
2594
'Invalid line ending request %r' % line_endings)
2595
content = "contents of %s%s" % (name.encode('utf-8'), end)
2596
transport.put_bytes_non_atomic(urlutils.escape(name), content)
2598
def build_tree_contents(self, shape):
2599
build_tree_contents(shape)
2601
def assertInWorkingTree(self, path, root_path='.', tree=None):
2602
"""Assert whether path or paths are in the WorkingTree"""
2604
tree = workingtree.WorkingTree.open(root_path)
2605
if not isinstance(path, basestring):
2607
self.assertInWorkingTree(p, tree=tree)
2609
self.assertIsNot(tree.path2id(path), None,
2610
path+' not in working tree.')
2612
def assertNotInWorkingTree(self, path, root_path='.', tree=None):
2613
"""Assert whether path or paths are not in the WorkingTree"""
2615
tree = workingtree.WorkingTree.open(root_path)
2616
if not isinstance(path, basestring):
2618
self.assertNotInWorkingTree(p,tree=tree)
2620
self.assertIs(tree.path2id(path), None, path+' in working tree.')
2623
class TestCaseWithTransport(TestCaseInTempDir):
2624
"""A test case that provides get_url and get_readonly_url facilities.
2626
These back onto two transport servers, one for readonly access and one for
2629
If no explicit class is provided for readonly access, a
2630
ReadonlyTransportDecorator is used instead which allows the use of non disk
2631
based read write transports.
2633
If an explicit class is provided for readonly access, that server and the
2634
readwrite one must both define get_url() as resolving to os.getcwd().
2637
def get_vfs_only_server(self):
2638
"""See TestCaseWithMemoryTransport.
2640
This is useful for some tests with specific servers that need
2643
if self.__vfs_server is None:
2644
self.__vfs_server = self.vfs_transport_factory()
2645
self.start_server(self.__vfs_server)
2646
return self.__vfs_server
2648
def make_branch_and_tree(self, relpath, format=None):
2649
"""Create a branch on the transport and a tree locally.
2651
If the transport is not a LocalTransport, the Tree can't be created on
2652
the transport. In that case if the vfs_transport_factory is
2653
LocalURLServer the working tree is created in the local
2654
directory backing the transport, and the returned tree's branch and
2655
repository will also be accessed locally. Otherwise a lightweight
2656
checkout is created and returned.
2658
We do this because we can't physically create a tree in the local
2659
path, with a branch reference to the transport_factory url, and
2660
a branch + repository in the vfs_transport, unless the vfs_transport
2661
namespace is distinct from the local disk - the two branch objects
2662
would collide. While we could construct a tree with its branch object
2663
pointing at the transport_factory transport in memory, reopening it
2664
would behaving unexpectedly, and has in the past caused testing bugs
2665
when we tried to do it that way.
2667
:param format: The BzrDirFormat.
2668
:returns: the WorkingTree.
2670
# TODO: always use the local disk path for the working tree,
2671
# this obviously requires a format that supports branch references
2672
# so check for that by checking bzrdir.BzrDirFormat.get_default_format()
2674
b = self.make_branch(relpath, format=format)
2676
return b.bzrdir.create_workingtree()
2677
except errors.NotLocalUrl:
2678
# We can only make working trees locally at the moment. If the
2679
# transport can't support them, then we keep the non-disk-backed
2680
# branch and create a local checkout.
2681
if self.vfs_transport_factory is LocalURLServer:
2682
# the branch is colocated on disk, we cannot create a checkout.
2683
# hopefully callers will expect this.
2684
local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
2685
wt = local_controldir.create_workingtree()
2686
if wt.branch._format != b._format:
2688
# Make sure that assigning to wt._branch fixes wt.branch,
2689
# in case the implementation details of workingtree objects
2691
self.assertIs(b, wt.branch)
2694
return b.create_checkout(relpath, lightweight=True)
2696
def assertIsDirectory(self, relpath, transport):
2697
"""Assert that relpath within transport is a directory.
2699
This may not be possible on all transports; in that case it propagates
2700
a TransportNotPossible.
2703
mode = transport.stat(relpath).st_mode
2704
except errors.NoSuchFile:
2705
self.fail("path %s is not a directory; no such file"
2707
if not stat.S_ISDIR(mode):
2708
self.fail("path %s is not a directory; has mode %#o"
2711
def assertTreesEqual(self, left, right):
2712
"""Check that left and right have the same content and properties."""
2713
# we use a tree delta to check for equality of the content, and we
2714
# manually check for equality of other things such as the parents list.
2715
self.assertEqual(left.get_parent_ids(), right.get_parent_ids())
2716
differences = left.changes_from(right)
2717
self.assertFalse(differences.has_changed(),
2718
"Trees %r and %r are different: %r" % (left, right, differences))
2721
super(TestCaseWithTransport, self).setUp()
2722
self.__vfs_server = None
2724
def disable_missing_extensions_warning(self):
2725
"""Some tests expect a precise stderr content.
2727
There is no point in forcing them to duplicate the extension related
2730
config.GlobalConfig().set_user_option('ignore_missing_extensions', True)
2733
class ChrootedTestCase(TestCaseWithTransport):
2734
"""A support class that provides readonly urls outside the local namespace.
2736
This is done by checking if self.transport_server is a MemoryServer. if it
2737
is then we are chrooted already, if it is not then an HttpServer is used
2740
TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
2741
be used without needed to redo it when a different
2742
subclass is in use ?
2746
super(ChrootedTestCase, self).setUp()
2747
if not self.vfs_transport_factory == MemoryServer:
2748
self.transport_readonly_server = HttpServer
2751
def condition_id_re(pattern):
2752
"""Create a condition filter which performs a re check on a test's id.
2754
:param pattern: A regular expression string.
2755
:return: A callable that returns True if the re matches.
2757
filter_re = osutils.re_compile_checked(pattern, 0,
2759
def condition(test):
2761
return filter_re.search(test_id)
2765
def condition_isinstance(klass_or_klass_list):
2766
"""Create a condition filter which returns isinstance(param, klass).
2768
:return: A callable which when called with one parameter obj return the
2769
result of isinstance(obj, klass_or_klass_list).
2772
return isinstance(obj, klass_or_klass_list)
2776
def condition_id_in_list(id_list):
2777
"""Create a condition filter which verify that test's id in a list.
2779
:param id_list: A TestIdList object.
2780
:return: A callable that returns True if the test's id appears in the list.
2782
def condition(test):
2783
return id_list.includes(test.id())
2787
def condition_id_startswith(starts):
2788
"""Create a condition filter verifying that test's id starts with a string.
2790
:param starts: A list of string.
2791
:return: A callable that returns True if the test's id starts with one of
2794
def condition(test):
2795
for start in starts:
2796
if test.id().startswith(start):
2802
def exclude_tests_by_condition(suite, condition):
2803
"""Create a test suite which excludes some tests from suite.
2805
:param suite: The suite to get tests from.
2806
:param condition: A callable whose result evaluates True when called with a
2807
test case which should be excluded from the result.
2808
:return: A suite which contains the tests found in suite that fail
2812
for test in iter_suite_tests(suite):
2813
if not condition(test):
2815
return TestUtil.TestSuite(result)
2818
def filter_suite_by_condition(suite, condition):
2819
"""Create a test suite by filtering another one.
2821
:param suite: The source suite.
2822
:param condition: A callable whose result evaluates True when called with a
2823
test case which should be included in the result.
2824
:return: A suite which contains the tests found in suite that pass
2828
for test in iter_suite_tests(suite):
2831
return TestUtil.TestSuite(result)
2834
def filter_suite_by_re(suite, pattern):
2835
"""Create a test suite by filtering another one.
2837
:param suite: the source suite
2838
:param pattern: pattern that names must match
2839
:returns: the newly created suite
2841
condition = condition_id_re(pattern)
2842
result_suite = filter_suite_by_condition(suite, condition)
2846
def filter_suite_by_id_list(suite, test_id_list):
2847
"""Create a test suite by filtering another one.
2849
:param suite: The source suite.
2850
:param test_id_list: A list of the test ids to keep as strings.
2851
:returns: the newly created suite
2853
condition = condition_id_in_list(test_id_list)
2854
result_suite = filter_suite_by_condition(suite, condition)
2858
def filter_suite_by_id_startswith(suite, start):
2859
"""Create a test suite by filtering another one.
2861
:param suite: The source suite.
2862
:param start: A list of string the test id must start with one of.
2863
:returns: the newly created suite
2865
condition = condition_id_startswith(start)
2866
result_suite = filter_suite_by_condition(suite, condition)
2870
def exclude_tests_by_re(suite, pattern):
2871
"""Create a test suite which excludes some tests from suite.
2873
:param suite: The suite to get tests from.
2874
:param pattern: A regular expression string. Test ids that match this
2875
pattern will be excluded from the result.
2876
:return: A TestSuite that contains all the tests from suite without the
2877
tests that matched pattern. The order of tests is the same as it was in
2880
return exclude_tests_by_condition(suite, condition_id_re(pattern))
2883
def preserve_input(something):
2884
"""A helper for performing test suite transformation chains.
2886
:param something: Anything you want to preserve.
2892
def randomize_suite(suite):
2893
"""Return a new TestSuite with suite's tests in random order.
2895
The tests in the input suite are flattened into a single suite in order to
2896
accomplish this. Any nested TestSuites are removed to provide global
2899
tests = list(iter_suite_tests(suite))
2900
random.shuffle(tests)
2901
return TestUtil.TestSuite(tests)
2904
def split_suite_by_condition(suite, condition):
2905
"""Split a test suite into two by a condition.
2907
:param suite: The suite to split.
2908
:param condition: The condition to match on. Tests that match this
2909
condition are returned in the first test suite, ones that do not match
2910
are in the second suite.
2911
:return: A tuple of two test suites, where the first contains tests from
2912
suite matching the condition, and the second contains the remainder
2913
from suite. The order within each output suite is the same as it was in
2918
for test in iter_suite_tests(suite):
2920
matched.append(test)
2922
did_not_match.append(test)
2923
return TestUtil.TestSuite(matched), TestUtil.TestSuite(did_not_match)
2926
def split_suite_by_re(suite, pattern):
2927
"""Split a test suite into two by a regular expression.
2929
:param suite: The suite to split.
2930
:param pattern: A regular expression string. Test ids that match this
2931
pattern will be in the first test suite returned, and the others in the
2932
second test suite returned.
2933
:return: A tuple of two test suites, where the first contains tests from
2934
suite matching pattern, and the second contains the remainder from
2935
suite. The order within each output suite is the same as it was in
2938
return split_suite_by_condition(suite, condition_id_re(pattern))
2941
def run_suite(suite, name='test', verbose=False, pattern=".*",
2942
stop_on_failure=False,
2943
transport=None, lsprof_timed=None, bench_history=None,
2944
matching_tests_first=None,
2947
exclude_pattern=None,
2950
suite_decorators=None,
2952
result_decorators=None,
2954
"""Run a test suite for bzr selftest.
2956
:param runner_class: The class of runner to use. Must support the
2957
constructor arguments passed by run_suite which are more than standard
2959
:return: A boolean indicating success.
2961
TestCase._gather_lsprof_in_benchmarks = lsprof_timed
2966
if runner_class is None:
2967
runner_class = TextTestRunner
2970
runner = runner_class(stream=stream,
2972
verbosity=verbosity,
2973
bench_history=bench_history,
2975
result_decorators=result_decorators,
2977
runner.stop_on_failure=stop_on_failure
2978
# built in decorator factories:
2980
random_order(random_seed, runner),
2981
exclude_tests(exclude_pattern),
2983
if matching_tests_first:
2984
decorators.append(tests_first(pattern))
2986
decorators.append(filter_tests(pattern))
2987
if suite_decorators:
2988
decorators.extend(suite_decorators)
2989
# tell the result object how many tests will be running: (except if
2990
# --parallel=fork is being used. Robert said he will provide a better
2991
# progress design later -- vila 20090817)
2992
if fork_decorator not in decorators:
2993
decorators.append(CountingDecorator)
2994
for decorator in decorators:
2995
suite = decorator(suite)
2997
# Done after test suite decoration to allow randomisation etc
2998
# to take effect, though that is of marginal benefit.
3000
stream.write("Listing tests only ...\n")
3001
for t in iter_suite_tests(suite):
3002
stream.write("%s\n" % (t.id()))
3004
result = runner.run(suite)
3006
return result.wasStrictlySuccessful()
3008
return result.wasSuccessful()
3011
# A registry where get() returns a suite decorator.
3012
parallel_registry = registry.Registry()
3015
def fork_decorator(suite):
3016
concurrency = osutils.local_concurrency()
3017
if concurrency == 1:
3019
from testtools import ConcurrentTestSuite
3020
return ConcurrentTestSuite(suite, fork_for_tests)
3021
parallel_registry.register('fork', fork_decorator)
3024
def subprocess_decorator(suite):
3025
concurrency = osutils.local_concurrency()
3026
if concurrency == 1:
3028
from testtools import ConcurrentTestSuite
3029
return ConcurrentTestSuite(suite, reinvoke_for_tests)
3030
parallel_registry.register('subprocess', subprocess_decorator)
3033
def exclude_tests(exclude_pattern):
3034
"""Return a test suite decorator that excludes tests."""
3035
if exclude_pattern is None:
3036
return identity_decorator
3037
def decorator(suite):
3038
return ExcludeDecorator(suite, exclude_pattern)
3042
def filter_tests(pattern):
3044
return identity_decorator
3045
def decorator(suite):
3046
return FilterTestsDecorator(suite, pattern)
3050
def random_order(random_seed, runner):
3051
"""Return a test suite decorator factory for randomising tests order.
3053
:param random_seed: now, a string which casts to a long, or a long.
3054
:param runner: A test runner with a stream attribute to report on.
3056
if random_seed is None:
3057
return identity_decorator
3058
def decorator(suite):
3059
return RandomDecorator(suite, random_seed, runner.stream)
3063
def tests_first(pattern):
3065
return identity_decorator
3066
def decorator(suite):
3067
return TestFirstDecorator(suite, pattern)
3071
def identity_decorator(suite):
3076
class TestDecorator(TestSuite):
3077
"""A decorator for TestCase/TestSuite objects.
3079
Usually, subclasses should override __iter__(used when flattening test
3080
suites), which we do to filter, reorder, parallelise and so on, run() and
3084
def __init__(self, suite):
3085
TestSuite.__init__(self)
3088
def countTestCases(self):
3091
cases += test.countTestCases()
3098
def run(self, result):
3099
# Use iteration on self, not self._tests, to allow subclasses to hook
3102
if result.shouldStop:
3108
class CountingDecorator(TestDecorator):
3109
"""A decorator which calls result.progress(self.countTestCases)."""
3111
def run(self, result):
3112
progress_method = getattr(result, 'progress', None)
3113
if callable(progress_method):
3114
progress_method(self.countTestCases(), SUBUNIT_SEEK_SET)
3115
return super(CountingDecorator, self).run(result)
3118
class ExcludeDecorator(TestDecorator):
3119
"""A decorator which excludes test matching an exclude pattern."""
3121
def __init__(self, suite, exclude_pattern):
3122
TestDecorator.__init__(self, suite)
3123
self.exclude_pattern = exclude_pattern
3124
self.excluded = False
3128
return iter(self._tests)
3129
self.excluded = True
3130
suite = exclude_tests_by_re(self, self.exclude_pattern)
3132
self.addTests(suite)
3133
return iter(self._tests)
3136
class FilterTestsDecorator(TestDecorator):
3137
"""A decorator which filters tests to those matching a pattern."""
3139
def __init__(self, suite, pattern):
3140
TestDecorator.__init__(self, suite)
3141
self.pattern = pattern
3142
self.filtered = False
3146
return iter(self._tests)
3147
self.filtered = True
3148
suite = filter_suite_by_re(self, self.pattern)
3150
self.addTests(suite)
3151
return iter(self._tests)
3154
class RandomDecorator(TestDecorator):
3155
"""A decorator which randomises the order of its tests."""
3157
def __init__(self, suite, random_seed, stream):
3158
TestDecorator.__init__(self, suite)
3159
self.random_seed = random_seed
3160
self.randomised = False
3161
self.stream = stream
3165
return iter(self._tests)
3166
self.randomised = True
3167
self.stream.writeln("Randomizing test order using seed %s\n" %
3168
(self.actual_seed()))
3169
# Initialise the random number generator.
3170
random.seed(self.actual_seed())
3171
suite = randomize_suite(self)
3173
self.addTests(suite)
3174
return iter(self._tests)
3176
def actual_seed(self):
3177
if self.random_seed == "now":
3178
# We convert the seed to a long to make it reuseable across
3179
# invocations (because the user can reenter it).
3180
self.random_seed = long(time.time())
3182
# Convert the seed to a long if we can
3184
self.random_seed = long(self.random_seed)
3187
return self.random_seed
3190
class TestFirstDecorator(TestDecorator):
3191
"""A decorator which moves named tests to the front."""
3193
def __init__(self, suite, pattern):
3194
TestDecorator.__init__(self, suite)
3195
self.pattern = pattern
3196
self.filtered = False
3200
return iter(self._tests)
3201
self.filtered = True
3202
suites = split_suite_by_re(self, self.pattern)
3204
self.addTests(suites)
3205
return iter(self._tests)
3208
def partition_tests(suite, count):
3209
"""Partition suite into count lists of tests."""
3211
tests = list(iter_suite_tests(suite))
3212
tests_per_process = int(math.ceil(float(len(tests)) / count))
3213
for block in range(count):
3214
low_test = block * tests_per_process
3215
high_test = low_test + tests_per_process
3216
process_tests = tests[low_test:high_test]
3217
result.append(process_tests)
3221
def fork_for_tests(suite):
3222
"""Take suite and start up one runner per CPU by forking()
3224
:return: An iterable of TestCase-like objects which can each have
3225
run(result) called on them to feed tests to result.
3227
concurrency = osutils.local_concurrency()
3229
from subunit import TestProtocolClient, ProtocolTestCase
3231
from subunit.test_results import AutoTimingTestResultDecorator
3233
AutoTimingTestResultDecorator = lambda x:x
3234
class TestInOtherProcess(ProtocolTestCase):
3235
# Should be in subunit, I think. RBC.
3236
def __init__(self, stream, pid):
3237
ProtocolTestCase.__init__(self, stream)
3240
def run(self, result):
3242
ProtocolTestCase.run(self, result)
3244
os.waitpid(self.pid, os.WNOHANG)
3246
test_blocks = partition_tests(suite, concurrency)
3247
for process_tests in test_blocks:
3248
process_suite = TestSuite()
3249
process_suite.addTests(process_tests)
3250
c2pread, c2pwrite = os.pipe()
3255
# Leave stderr and stdout open so we can see test noise
3256
# Close stdin so that the child goes away if it decides to
3257
# read from stdin (otherwise its a roulette to see what
3258
# child actually gets keystrokes for pdb etc).
3261
stream = os.fdopen(c2pwrite, 'wb', 1)
3262
subunit_result = AutoTimingTestResultDecorator(
3263
TestProtocolClient(stream))
3264
process_suite.run(subunit_result)
3269
stream = os.fdopen(c2pread, 'rb', 1)
3270
test = TestInOtherProcess(stream, pid)
3275
def reinvoke_for_tests(suite):
3276
"""Take suite and start up one runner per CPU using subprocess().
3278
:return: An iterable of TestCase-like objects which can each have
3279
run(result) called on them to feed tests to result.
3281
concurrency = osutils.local_concurrency()
3283
from subunit import ProtocolTestCase
3284
class TestInSubprocess(ProtocolTestCase):
3285
def __init__(self, process, name):
3286
ProtocolTestCase.__init__(self, process.stdout)
3287
self.process = process
3288
self.process.stdin.close()
3291
def run(self, result):
3293
ProtocolTestCase.run(self, result)
3296
os.unlink(self.name)
3297
# print "pid %d finished" % finished_process
3298
test_blocks = partition_tests(suite, concurrency)
3299
for process_tests in test_blocks:
3300
# ugly; currently reimplement rather than reuses TestCase methods.
3301
bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
3302
if not os.path.isfile(bzr_path):
3303
# We are probably installed. Assume sys.argv is the right file
3304
bzr_path = sys.argv[0]
3305
fd, test_list_file_name = tempfile.mkstemp()
3306
test_list_file = os.fdopen(fd, 'wb', 1)
3307
for test in process_tests:
3308
test_list_file.write(test.id() + '\n')
3309
test_list_file.close()
3311
argv = [bzr_path, 'selftest', '--load-list', test_list_file_name,
3313
if '--no-plugins' in sys.argv:
3314
argv.append('--no-plugins')
3315
# stderr=STDOUT would be ideal, but until we prevent noise on
3316
# stderr it can interrupt the subunit protocol.
3317
process = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE,
3319
test = TestInSubprocess(process, test_list_file_name)
3322
os.unlink(test_list_file_name)
3327
class ForwardingResult(unittest.TestResult):
3329
def __init__(self, target):
3330
unittest.TestResult.__init__(self)
3331
self.result = target
3333
def startTest(self, test):
3334
self.result.startTest(test)
3336
def stopTest(self, test):
3337
self.result.stopTest(test)
3339
def startTestRun(self):
3340
self.result.startTestRun()
3342
def stopTestRun(self):
3343
self.result.stopTestRun()
3345
def addSkip(self, test, reason):
3346
self.result.addSkip(test, reason)
3348
def addSuccess(self, test):
3349
self.result.addSuccess(test)
3351
def addError(self, test, err):
3352
self.result.addError(test, err)
3354
def addFailure(self, test, err):
3355
self.result.addFailure(test, err)
3358
class BZRTransformingResult(ForwardingResult):
3360
def addError(self, test, err):
3361
feature = self._error_looks_like('UnavailableFeature: ', err)
3362
if feature is not None:
3363
self.result.addNotSupported(test, feature)
3365
self.result.addError(test, err)
3367
def addFailure(self, test, err):
3368
known = self._error_looks_like('KnownFailure: ', err)
3369
if known is not None:
3370
self.result._addKnownFailure(test, [KnownFailure,
3371
KnownFailure(known), None])
3373
self.result.addFailure(test, err)
3375
def _error_looks_like(self, prefix, err):
3376
"""Deserialize exception and returns the stringify value."""
3380
if isinstance(exc, subunit.RemoteException):
3381
# stringify the exception gives access to the remote traceback
3382
# We search the last line for 'prefix'
3383
lines = str(exc).split('\n')
3384
while lines and not lines[-1]:
3387
if lines[-1].startswith(prefix):
3388
value = lines[-1][len(prefix):]
3392
class ProfileResult(ForwardingResult):
3393
"""Generate profiling data for all activity between start and success.
3395
The profile data is appended to the test's _benchcalls attribute and can
3396
be accessed by the forwarded-to TestResult.
3398
While it might be cleaner do accumulate this in stopTest, addSuccess is
3399
where our existing output support for lsprof is, and this class aims to
3400
fit in with that: while it could be moved it's not necessary to accomplish
3401
test profiling, nor would it be dramatically cleaner.
3404
def startTest(self, test):
3405
self.profiler = bzrlib.lsprof.BzrProfiler()
3406
self.profiler.start()
3407
ForwardingResult.startTest(self, test)
3409
def addSuccess(self, test):
3410
stats = self.profiler.stop()
3412
calls = test._benchcalls
3413
except AttributeError:
3414
test._benchcalls = []
3415
calls = test._benchcalls
3416
calls.append(((test.id(), "", ""), stats))
3417
ForwardingResult.addSuccess(self, test)
3419
def stopTest(self, test):
3420
ForwardingResult.stopTest(self, test)
3421
self.profiler = None
3424
# Controlled by "bzr selftest -E=..." option
3425
# Currently supported:
3426
# -Eallow_debug Will no longer clear debug.debug_flags() so it
3427
# preserves any flags supplied at the command line.
3428
# -Edisable_lock_checks Turns errors in mismatched locks into simple prints
3429
# rather than failing tests. And no longer raise
3430
# LockContention when fctnl locks are not being used
3431
# with proper exclusion rules.
3432
selftest_debug_flags = set()
3435
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
3437
test_suite_factory=None,
3440
matching_tests_first=None,
3443
exclude_pattern=None,
3449
suite_decorators=None,
3453
"""Run the whole test suite under the enhanced runner"""
3454
# XXX: Very ugly way to do this...
3455
# Disable warning about old formats because we don't want it to disturb
3456
# any blackbox tests.
3457
from bzrlib import repository
3458
repository._deprecation_warning_done = True
3460
global default_transport
3461
if transport is None:
3462
transport = default_transport
3463
old_transport = default_transport
3464
default_transport = transport
3465
global selftest_debug_flags
3466
old_debug_flags = selftest_debug_flags
3467
if debug_flags is not None:
3468
selftest_debug_flags = set(debug_flags)
3470
if load_list is None:
3473
keep_only = load_test_id_list(load_list)
3475
starting_with = [test_prefix_alias_registry.resolve_alias(start)
3476
for start in starting_with]
3477
if test_suite_factory is None:
3478
# Reduce loading time by loading modules based on the starting_with
3480
suite = test_suite(keep_only, starting_with)
3482
suite = test_suite_factory()
3484
# But always filter as requested.
3485
suite = filter_suite_by_id_startswith(suite, starting_with)
3486
result_decorators = []
3488
result_decorators.append(ProfileResult)
3489
return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
3490
stop_on_failure=stop_on_failure,
3491
transport=transport,
3492
lsprof_timed=lsprof_timed,
3493
bench_history=bench_history,
3494
matching_tests_first=matching_tests_first,
3495
list_only=list_only,
3496
random_seed=random_seed,
3497
exclude_pattern=exclude_pattern,
3499
runner_class=runner_class,
3500
suite_decorators=suite_decorators,
3502
result_decorators=result_decorators,
3505
default_transport = old_transport
3506
selftest_debug_flags = old_debug_flags
3509
def load_test_id_list(file_name):
3510
"""Load a test id list from a text file.
3512
The format is one test id by line. No special care is taken to impose
3513
strict rules, these test ids are used to filter the test suite so a test id
3514
that do not match an existing test will do no harm. This allows user to add
3515
comments, leave blank lines, etc.
3519
ftest = open(file_name, 'rt')
3521
if e.errno != errno.ENOENT:
3524
raise errors.NoSuchFile(file_name)
3526
for test_name in ftest.readlines():
3527
test_list.append(test_name.strip())
3532
def suite_matches_id_list(test_suite, id_list):
3533
"""Warns about tests not appearing or appearing more than once.
3535
:param test_suite: A TestSuite object.
3536
:param test_id_list: The list of test ids that should be found in
3539
:return: (absents, duplicates) absents is a list containing the test found
3540
in id_list but not in test_suite, duplicates is a list containing the
3541
test found multiple times in test_suite.
3543
When using a prefined test id list, it may occurs that some tests do not
3544
exist anymore or that some tests use the same id. This function warns the
3545
tester about potential problems in his workflow (test lists are volatile)
3546
or in the test suite itself (using the same id for several tests does not
3547
help to localize defects).
3549
# Build a dict counting id occurrences
3551
for test in iter_suite_tests(test_suite):
3553
tests[id] = tests.get(id, 0) + 1
3558
occurs = tests.get(id, 0)
3560
not_found.append(id)
3562
duplicates.append(id)
3564
return not_found, duplicates
3567
class TestIdList(object):
3568
"""Test id list to filter a test suite.
3570
Relying on the assumption that test ids are built as:
3571
<module>[.<class>.<method>][(<param>+)], <module> being in python dotted
3572
notation, this class offers methods to :
3573
- avoid building a test suite for modules not refered to in the test list,
3574
- keep only the tests listed from the module test suite.
3577
def __init__(self, test_id_list):
3578
# When a test suite needs to be filtered against us we compare test ids
3579
# for equality, so a simple dict offers a quick and simple solution.
3580
self.tests = dict().fromkeys(test_id_list, True)
3582
# While unittest.TestCase have ids like:
3583
# <module>.<class>.<method>[(<param+)],
3584
# doctest.DocTestCase can have ids like:
3587
# <module>.<function>
3588
# <module>.<class>.<method>
3590
# Since we can't predict a test class from its name only, we settle on
3591
# a simple constraint: a test id always begins with its module name.
3594
for test_id in test_id_list:
3595
parts = test_id.split('.')
3596
mod_name = parts.pop(0)
3597
modules[mod_name] = True
3599
mod_name += '.' + part
3600
modules[mod_name] = True
3601
self.modules = modules
3603
def refers_to(self, module_name):
3604
"""Is there tests for the module or one of its sub modules."""
3605
return self.modules.has_key(module_name)
3607
def includes(self, test_id):
3608
return self.tests.has_key(test_id)
3611
class TestPrefixAliasRegistry(registry.Registry):
3612
"""A registry for test prefix aliases.
3614
This helps implement shorcuts for the --starting-with selftest
3615
option. Overriding existing prefixes is not allowed but not fatal (a
3616
warning will be emitted).
3619
def register(self, key, obj, help=None, info=None,
3620
override_existing=False):
3621
"""See Registry.register.
3623
Trying to override an existing alias causes a warning to be emitted,
3624
not a fatal execption.
3627
super(TestPrefixAliasRegistry, self).register(
3628
key, obj, help=help, info=info, override_existing=False)
3630
actual = self.get(key)
3631
note('Test prefix alias %s is already used for %s, ignoring %s'
3632
% (key, actual, obj))
3634
def resolve_alias(self, id_start):
3635
"""Replace the alias by the prefix in the given string.
3637
Using an unknown prefix is an error to help catching typos.
3639
parts = id_start.split('.')
3641
parts[0] = self.get(parts[0])
3643
raise errors.BzrCommandError(
3644
'%s is not a known test prefix alias' % parts[0])
3645
return '.'.join(parts)
3648
test_prefix_alias_registry = TestPrefixAliasRegistry()
3649
"""Registry of test prefix aliases."""
3652
# This alias allows to detect typos ('bzrlin.') by making all valid test ids
3653
# appear prefixed ('bzrlib.' is "replaced" by 'bzrlib.').
3654
test_prefix_alias_registry.register('bzrlib', 'bzrlib')
3656
# Obvious higest levels prefixes, feel free to add your own via a plugin
3657
test_prefix_alias_registry.register('bd', 'bzrlib.doc')
3658
test_prefix_alias_registry.register('bu', 'bzrlib.utils')
3659
test_prefix_alias_registry.register('bt', 'bzrlib.tests')
3660
test_prefix_alias_registry.register('bb', 'bzrlib.tests.blackbox')
3661
test_prefix_alias_registry.register('bp', 'bzrlib.plugins')
3664
def _test_suite_testmod_names():
3665
"""Return the standard list of test module names to test."""
3668
'bzrlib.tests.blackbox',
3669
'bzrlib.tests.commands',
3670
'bzrlib.tests.per_branch',
3671
'bzrlib.tests.per_bzrdir',
3672
'bzrlib.tests.per_interrepository',
3673
'bzrlib.tests.per_intertree',
3674
'bzrlib.tests.per_inventory',
3675
'bzrlib.tests.per_interbranch',
3676
'bzrlib.tests.per_lock',
3677
'bzrlib.tests.per_transport',
3678
'bzrlib.tests.per_tree',
3679
'bzrlib.tests.per_pack_repository',
3680
'bzrlib.tests.per_repository',
3681
'bzrlib.tests.per_repository_chk',
3682
'bzrlib.tests.per_repository_reference',
3683
'bzrlib.tests.per_versionedfile',
3684
'bzrlib.tests.per_workingtree',
3685
'bzrlib.tests.test__annotator',
3686
'bzrlib.tests.test__chk_map',
3687
'bzrlib.tests.test__dirstate_helpers',
3688
'bzrlib.tests.test__groupcompress',
3689
'bzrlib.tests.test__known_graph',
3690
'bzrlib.tests.test__rio',
3691
'bzrlib.tests.test__simple_set',
3692
'bzrlib.tests.test__static_tuple',
3693
'bzrlib.tests.test__walkdirs_win32',
3694
'bzrlib.tests.test_ancestry',
3695
'bzrlib.tests.test_annotate',
3696
'bzrlib.tests.test_api',
3697
'bzrlib.tests.test_atomicfile',
3698
'bzrlib.tests.test_bad_files',
3699
'bzrlib.tests.test_bencode',
3700
'bzrlib.tests.test_bisect_multi',
3701
'bzrlib.tests.test_branch',
3702
'bzrlib.tests.test_branchbuilder',
3703
'bzrlib.tests.test_btree_index',
3704
'bzrlib.tests.test_bugtracker',
3705
'bzrlib.tests.test_bundle',
3706
'bzrlib.tests.test_bzrdir',
3707
'bzrlib.tests.test__chunks_to_lines',
3708
'bzrlib.tests.test_cache_utf8',
3709
'bzrlib.tests.test_chk_map',
3710
'bzrlib.tests.test_chk_serializer',
3711
'bzrlib.tests.test_chunk_writer',
3712
'bzrlib.tests.test_clean_tree',
3713
'bzrlib.tests.test_commands',
3714
'bzrlib.tests.test_commit',
3715
'bzrlib.tests.test_commit_merge',
3716
'bzrlib.tests.test_config',
3717
'bzrlib.tests.test_conflicts',
3718
'bzrlib.tests.test_counted_lock',
3719
'bzrlib.tests.test_crash',
3720
'bzrlib.tests.test_decorators',
3721
'bzrlib.tests.test_delta',
3722
'bzrlib.tests.test_debug',
3723
'bzrlib.tests.test_deprecated_graph',
3724
'bzrlib.tests.test_diff',
3725
'bzrlib.tests.test_directory_service',
3726
'bzrlib.tests.test_dirstate',
3727
'bzrlib.tests.test_email_message',
3728
'bzrlib.tests.test_eol_filters',
3729
'bzrlib.tests.test_errors',
3730
'bzrlib.tests.test_export',
3731
'bzrlib.tests.test_extract',
3732
'bzrlib.tests.test_fetch',
3733
'bzrlib.tests.test_fifo_cache',
3734
'bzrlib.tests.test_filters',
3735
'bzrlib.tests.test_ftp_transport',
3736
'bzrlib.tests.test_foreign',
3737
'bzrlib.tests.test_generate_docs',
3738
'bzrlib.tests.test_generate_ids',
3739
'bzrlib.tests.test_globbing',
3740
'bzrlib.tests.test_gpg',
3741
'bzrlib.tests.test_graph',
3742
'bzrlib.tests.test_groupcompress',
3743
'bzrlib.tests.test_hashcache',
3744
'bzrlib.tests.test_help',
3745
'bzrlib.tests.test_hooks',
3746
'bzrlib.tests.test_http',
3747
'bzrlib.tests.test_http_response',
3748
'bzrlib.tests.test_https_ca_bundle',
3749
'bzrlib.tests.test_identitymap',
3750
'bzrlib.tests.test_ignores',
3751
'bzrlib.tests.test_index',
3752
'bzrlib.tests.test_info',
3753
'bzrlib.tests.test_inv',
3754
'bzrlib.tests.test_inventory_delta',
3755
'bzrlib.tests.test_knit',
3756
'bzrlib.tests.test_lazy_import',
3757
'bzrlib.tests.test_lazy_regex',
3758
'bzrlib.tests.test_lock',
3759
'bzrlib.tests.test_lockable_files',
3760
'bzrlib.tests.test_lockdir',
3761
'bzrlib.tests.test_log',
3762
'bzrlib.tests.test_lru_cache',
3763
'bzrlib.tests.test_lsprof',
3764
'bzrlib.tests.test_mail_client',
3765
'bzrlib.tests.test_memorytree',
3766
'bzrlib.tests.test_merge',
3767
'bzrlib.tests.test_merge3',
3768
'bzrlib.tests.test_merge_core',
3769
'bzrlib.tests.test_merge_directive',
3770
'bzrlib.tests.test_missing',
3771
'bzrlib.tests.test_msgeditor',
3772
'bzrlib.tests.test_multiparent',
3773
'bzrlib.tests.test_mutabletree',
3774
'bzrlib.tests.test_nonascii',
3775
'bzrlib.tests.test_options',
3776
'bzrlib.tests.test_osutils',
3777
'bzrlib.tests.test_osutils_encodings',
3778
'bzrlib.tests.test_pack',
3779
'bzrlib.tests.test_patch',
3780
'bzrlib.tests.test_patches',
3781
'bzrlib.tests.test_permissions',
3782
'bzrlib.tests.test_plugins',
3783
'bzrlib.tests.test_progress',
3784
'bzrlib.tests.test_read_bundle',
3785
'bzrlib.tests.test_reconcile',
3786
'bzrlib.tests.test_reconfigure',
3787
'bzrlib.tests.test_registry',
3788
'bzrlib.tests.test_remote',
3789
'bzrlib.tests.test_rename_map',
3790
'bzrlib.tests.test_repository',
3791
'bzrlib.tests.test_revert',
3792
'bzrlib.tests.test_revision',
3793
'bzrlib.tests.test_revisionspec',
3794
'bzrlib.tests.test_revisiontree',
3795
'bzrlib.tests.test_rio',
3796
'bzrlib.tests.test_rules',
3797
'bzrlib.tests.test_sampler',
3798
'bzrlib.tests.test_script',
3799
'bzrlib.tests.test_selftest',
3800
'bzrlib.tests.test_serializer',
3801
'bzrlib.tests.test_setup',
3802
'bzrlib.tests.test_sftp_transport',
3803
'bzrlib.tests.test_shelf',
3804
'bzrlib.tests.test_shelf_ui',
3805
'bzrlib.tests.test_smart',
3806
'bzrlib.tests.test_smart_add',
3807
'bzrlib.tests.test_smart_request',
3808
'bzrlib.tests.test_smart_transport',
3809
'bzrlib.tests.test_smtp_connection',
3810
'bzrlib.tests.test_source',
3811
'bzrlib.tests.test_ssh_transport',
3812
'bzrlib.tests.test_status',
3813
'bzrlib.tests.test_store',
3814
'bzrlib.tests.test_strace',
3815
'bzrlib.tests.test_subsume',
3816
'bzrlib.tests.test_switch',
3817
'bzrlib.tests.test_symbol_versioning',
3818
'bzrlib.tests.test_tag',
3819
'bzrlib.tests.test_testament',
3820
'bzrlib.tests.test_textfile',
3821
'bzrlib.tests.test_textmerge',
3822
'bzrlib.tests.test_timestamp',
3823
'bzrlib.tests.test_trace',
3824
'bzrlib.tests.test_transactions',
3825
'bzrlib.tests.test_transform',
3826
'bzrlib.tests.test_transport',
3827
'bzrlib.tests.test_transport_log',
3828
'bzrlib.tests.test_tree',
3829
'bzrlib.tests.test_treebuilder',
3830
'bzrlib.tests.test_tsort',
3831
'bzrlib.tests.test_tuned_gzip',
3832
'bzrlib.tests.test_ui',
3833
'bzrlib.tests.test_uncommit',
3834
'bzrlib.tests.test_upgrade',
3835
'bzrlib.tests.test_upgrade_stacked',
3836
'bzrlib.tests.test_urlutils',
3837
'bzrlib.tests.test_version',
3838
'bzrlib.tests.test_version_info',
3839
'bzrlib.tests.test_weave',
3840
'bzrlib.tests.test_whitebox',
3841
'bzrlib.tests.test_win32utils',
3842
'bzrlib.tests.test_workingtree',
3843
'bzrlib.tests.test_workingtree_4',
3844
'bzrlib.tests.test_wsgi',
3845
'bzrlib.tests.test_xml',
3849
def _test_suite_modules_to_doctest():
3850
"""Return the list of modules to doctest."""
3853
'bzrlib.branchbuilder',
3856
'bzrlib.iterablefile',
3860
'bzrlib.symbol_versioning',
3863
'bzrlib.version_info_formats.format_custom',
3867
def test_suite(keep_only=None, starting_with=None):
3868
"""Build and return TestSuite for the whole of bzrlib.
3870
:param keep_only: A list of test ids limiting the suite returned.
3872
:param starting_with: An id limiting the suite returned to the tests
3875
This function can be replaced if you need to change the default test
3876
suite on a global basis, but it is not encouraged.
3879
loader = TestUtil.TestLoader()
3881
if keep_only is not None:
3882
id_filter = TestIdList(keep_only)
3884
# We take precedence over keep_only because *at loading time* using
3885
# both options means we will load less tests for the same final result.
3886
def interesting_module(name):
3887
for start in starting_with:
3889
# Either the module name starts with the specified string
3890
name.startswith(start)
3891
# or it may contain tests starting with the specified string
3892
or start.startswith(name)
3896
loader = TestUtil.FilteredByModuleTestLoader(interesting_module)
3898
elif keep_only is not None:
3899
loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
3900
def interesting_module(name):
3901
return id_filter.refers_to(name)
3904
loader = TestUtil.TestLoader()
3905
def interesting_module(name):
3906
# No filtering, all modules are interesting
3909
suite = loader.suiteClass()
3911
# modules building their suite with loadTestsFromModuleNames
3912
suite.addTest(loader.loadTestsFromModuleNames(_test_suite_testmod_names()))
3914
for mod in _test_suite_modules_to_doctest():
3915
if not interesting_module(mod):
3916
# No tests to keep here, move along
3919
# note that this really does mean "report only" -- doctest
3920
# still runs the rest of the examples
3921
doc_suite = doctest.DocTestSuite(mod,
3922
optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
3923
except ValueError, e:
3924
print '**failed to get doctest for: %s\n%s' % (mod, e)
3926
if len(doc_suite._tests) == 0:
3927
raise errors.BzrError("no doctests found in %s" % (mod,))
3928
suite.addTest(doc_suite)
3930
default_encoding = sys.getdefaultencoding()
3931
for name, plugin in bzrlib.plugin.plugins().items():
3932
if not interesting_module(plugin.module.__name__):
3934
plugin_suite = plugin.test_suite()
3935
# We used to catch ImportError here and turn it into just a warning,
3936
# but really if you don't have --no-plugins this should be a failure.
3937
# mbp 20080213 - see http://bugs.launchpad.net/bugs/189771
3938
if plugin_suite is None:
3939
plugin_suite = plugin.load_plugin_tests(loader)
3940
if plugin_suite is not None:
3941
suite.addTest(plugin_suite)
3942
if default_encoding != sys.getdefaultencoding():
3943
bzrlib.trace.warning(
3944
'Plugin "%s" tried to reset default encoding to: %s', name,
3945
sys.getdefaultencoding())
3947
sys.setdefaultencoding(default_encoding)
3949
if keep_only is not None:
3950
# Now that the referred modules have loaded their tests, keep only the
3952
suite = filter_suite_by_id_list(suite, id_filter)
3953
# Do some sanity checks on the id_list filtering
3954
not_found, duplicates = suite_matches_id_list(suite, keep_only)
3956
# The tester has used both keep_only and starting_with, so he is
3957
# already aware that some tests are excluded from the list, there
3958
# is no need to tell him which.
3961
# Some tests mentioned in the list are not in the test suite. The
3962
# list may be out of date, report to the tester.
3963
for id in not_found:
3964
bzrlib.trace.warning('"%s" not found in the test suite', id)
3965
for id in duplicates:
3966
bzrlib.trace.warning('"%s" is used as an id by several tests', id)
3971
def multiply_scenarios(scenarios_left, scenarios_right):
3972
"""Multiply two sets of scenarios.
3974
:returns: the cartesian product of the two sets of scenarios, that is
3975
a scenario for every possible combination of a left scenario and a
3979
('%s,%s' % (left_name, right_name),
3980
dict(left_dict.items() + right_dict.items()))
3981
for left_name, left_dict in scenarios_left
3982
for right_name, right_dict in scenarios_right]
3985
def multiply_tests(tests, scenarios, result):
3986
"""Multiply tests_list by scenarios into result.
3988
This is the core workhorse for test parameterisation.
3990
Typically the load_tests() method for a per-implementation test suite will
3991
call multiply_tests and return the result.
3993
:param tests: The tests to parameterise.
3994
:param scenarios: The scenarios to apply: pairs of (scenario_name,
3995
scenario_param_dict).
3996
:param result: A TestSuite to add created tests to.
3998
This returns the passed in result TestSuite with the cross product of all
3999
the tests repeated once for each scenario. Each test is adapted by adding
4000
the scenario name at the end of its id(), and updating the test object's
4001
__dict__ with the scenario_param_dict.
4003
>>> import bzrlib.tests.test_sampler
4004
>>> r = multiply_tests(
4005
... bzrlib.tests.test_sampler.DemoTest('test_nothing'),
4006
... [('one', dict(param=1)),
4007
... ('two', dict(param=2))],
4009
>>> tests = list(iter_suite_tests(r))
4013
'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
4019
for test in iter_suite_tests(tests):
4020
apply_scenarios(test, scenarios, result)
4024
def apply_scenarios(test, scenarios, result):
4025
"""Apply the scenarios in scenarios to test and add to result.
4027
:param test: The test to apply scenarios to.
4028
:param scenarios: An iterable of scenarios to apply to test.
4030
:seealso: apply_scenario
4032
for scenario in scenarios:
4033
result.addTest(apply_scenario(test, scenario))
4037
def apply_scenario(test, scenario):
4038
"""Copy test and apply scenario to it.
4040
:param test: A test to adapt.
4041
:param scenario: A tuple describing the scenarion.
4042
The first element of the tuple is the new test id.
4043
The second element is a dict containing attributes to set on the
4045
:return: The adapted test.
4047
new_id = "%s(%s)" % (test.id(), scenario[0])
4048
new_test = clone_test(test, new_id)
4049
for name, value in scenario[1].items():
4050
setattr(new_test, name, value)
4054
def clone_test(test, new_id):
4055
"""Clone a test giving it a new id.
4057
:param test: The test to clone.
4058
:param new_id: The id to assign to it.
4059
:return: The new test.
4061
new_test = copy(test)
4062
new_test.id = lambda: new_id
4066
def _rmtree_temp_dir(dirname):
4067
# If LANG=C we probably have created some bogus paths
4068
# which rmtree(unicode) will fail to delete
4069
# so make sure we are using rmtree(str) to delete everything
4070
# except on win32, where rmtree(str) will fail
4071
# since it doesn't have the property of byte-stream paths
4072
# (they are either ascii or mbcs)
4073
if sys.platform == 'win32':
4074
# make sure we are using the unicode win32 api
4075
dirname = unicode(dirname)
4077
dirname = dirname.encode(sys.getfilesystemencoding())
4079
osutils.rmtree(dirname)
4081
# We don't want to fail here because some useful display will be lost
4082
# otherwise. Polluting the tmp dir is bad, but not giving all the
4083
# possible info to the test runner is even worse.
4084
sys.stderr.write('Unable to remove testing dir %s\n%s'
4085
% (os.path.basename(dirname), e))
4088
class Feature(object):
4089
"""An operating system Feature."""
4092
self._available = None
4094
def available(self):
4095
"""Is the feature available?
4097
:return: True if the feature is available.
4099
if self._available is None:
4100
self._available = self._probe()
4101
return self._available
4104
"""Implement this method in concrete features.
4106
:return: True if the feature is available.
4108
raise NotImplementedError
4111
if getattr(self, 'feature_name', None):
4112
return self.feature_name()
4113
return self.__class__.__name__
4116
class _SymlinkFeature(Feature):
4119
return osutils.has_symlinks()
4121
def feature_name(self):
4124
SymlinkFeature = _SymlinkFeature()
4127
class _HardlinkFeature(Feature):
4130
return osutils.has_hardlinks()
4132
def feature_name(self):
4135
HardlinkFeature = _HardlinkFeature()
4138
class _OsFifoFeature(Feature):
4141
return getattr(os, 'mkfifo', None)
4143
def feature_name(self):
4144
return 'filesystem fifos'
4146
OsFifoFeature = _OsFifoFeature()
4149
class _UnicodeFilenameFeature(Feature):
4150
"""Does the filesystem support Unicode filenames?"""
4154
# Check for character combinations unlikely to be covered by any
4155
# single non-unicode encoding. We use the characters
4156
# - greek small letter alpha (U+03B1) and
4157
# - braille pattern dots-123456 (U+283F).
4158
os.stat(u'\u03b1\u283f')
4159
except UnicodeEncodeError:
4161
except (IOError, OSError):
4162
# The filesystem allows the Unicode filename but the file doesn't
4166
# The filesystem allows the Unicode filename and the file exists,
4170
UnicodeFilenameFeature = _UnicodeFilenameFeature()
4173
def probe_unicode_in_user_encoding():
4174
"""Try to encode several unicode strings to use in unicode-aware tests.
4175
Return first successfull match.
4177
:return: (unicode value, encoded plain string value) or (None, None)
4179
possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
4180
for uni_val in possible_vals:
4182
str_val = uni_val.encode(osutils.get_user_encoding())
4183
except UnicodeEncodeError:
4184
# Try a different character
4187
return uni_val, str_val
4191
def probe_bad_non_ascii(encoding):
4192
"""Try to find [bad] character with code [128..255]
4193
that cannot be decoded to unicode in some encoding.
4194
Return None if all non-ascii characters is valid
4197
for i in xrange(128, 256):
4200
char.decode(encoding)
4201
except UnicodeDecodeError:
4206
class _HTTPSServerFeature(Feature):
4207
"""Some tests want an https Server, check if one is available.
4209
Right now, the only way this is available is under python2.6 which provides
4220
def feature_name(self):
4221
return 'HTTPSServer'
4224
HTTPSServerFeature = _HTTPSServerFeature()
4227
class _ParamikoFeature(Feature):
4228
"""Is paramiko available?"""
4232
from bzrlib.transport.sftp import SFTPAbsoluteServer
4234
except errors.ParamikoNotPresent:
4237
def feature_name(self):
4241
ParamikoFeature = _ParamikoFeature()
4244
class _UnicodeFilename(Feature):
4245
"""Does the filesystem support Unicode filenames?"""
4250
except UnicodeEncodeError:
4252
except (IOError, OSError):
4253
# The filesystem allows the Unicode filename but the file doesn't
4257
# The filesystem allows the Unicode filename and the file exists,
4261
UnicodeFilename = _UnicodeFilename()
4264
class _UTF8Filesystem(Feature):
4265
"""Is the filesystem UTF-8?"""
4268
if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
4272
UTF8Filesystem = _UTF8Filesystem()
4275
class _BreakinFeature(Feature):
4276
"""Does this platform support the breakin feature?"""
4279
from bzrlib import breakin
4280
if breakin.determine_signal() is None:
4282
if sys.platform == 'win32':
4283
# Windows doesn't have os.kill, and we catch the SIGBREAK signal.
4284
# We trigger SIGBREAK via a Console api so we need ctypes to
4285
# access the function
4290
def feature_name(self):
4291
return "SIGQUIT or SIGBREAK w/ctypes on win32"
4294
BreakinFeature = _BreakinFeature()
4297
class _CaseInsCasePresFilenameFeature(Feature):
4298
"""Is the file-system case insensitive, but case-preserving?"""
4301
fileno, name = tempfile.mkstemp(prefix='MixedCase')
4303
# first check truly case-preserving for created files, then check
4304
# case insensitive when opening existing files.
4305
name = osutils.normpath(name)
4306
base, rel = osutils.split(name)
4307
found_rel = osutils.canonical_relpath(base, name)
4308
return (found_rel == rel
4309
and os.path.isfile(name.upper())
4310
and os.path.isfile(name.lower()))
4315
def feature_name(self):
4316
return "case-insensitive case-preserving filesystem"
4318
CaseInsCasePresFilenameFeature = _CaseInsCasePresFilenameFeature()
4321
class _CaseInsensitiveFilesystemFeature(Feature):
4322
"""Check if underlying filesystem is case-insensitive but *not* case
4325
# Note that on Windows, Cygwin, MacOS etc, the file-systems are far
4326
# more likely to be case preserving, so this case is rare.
4329
if CaseInsCasePresFilenameFeature.available():
4332
if TestCaseWithMemoryTransport.TEST_ROOT is None:
4333
root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
4334
TestCaseWithMemoryTransport.TEST_ROOT = root
4336
root = TestCaseWithMemoryTransport.TEST_ROOT
4337
tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
4339
name_a = osutils.pathjoin(tdir, 'a')
4340
name_A = osutils.pathjoin(tdir, 'A')
4342
result = osutils.isdir(name_A)
4343
_rmtree_temp_dir(tdir)
4346
def feature_name(self):
4347
return 'case-insensitive filesystem'
4349
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
4352
class _SubUnitFeature(Feature):
4353
"""Check if subunit is available."""
4362
def feature_name(self):
4365
SubUnitFeature = _SubUnitFeature()
4366
# Only define SubUnitBzrRunner if subunit is available.
4368
from subunit import TestProtocolClient
4370
from subunit.test_results import AutoTimingTestResultDecorator
4372
AutoTimingTestResultDecorator = lambda x:x
4373
class SubUnitBzrRunner(TextTestRunner):
4374
def run(self, test):
4375
result = AutoTimingTestResultDecorator(
4376
TestProtocolClient(self.stream))