1
# Copyright (C) 2005 by Canonical Ltd
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
11
# GNU General Public License for more details.
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
from testsweet import TestBase, run_suite, InTempDir
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
# TODO: Perhaps there should be an API to find out if bzr running under the
19
# test suite -- some plugins might want to avoid making intrusive changes if
20
# this is the case. However, we want behaviour under to test to diverge as
21
# little as possible, so this should be used rarely if it's added at all.
22
# (Suggestion from j-a-meinel, 2005-11-24)
24
# NOTE: Some classes in here use camelCaseNaming() rather than
25
# underscore_naming(). That's for consistency with unittest; it's not the
26
# general style of bzrlib. Please continue that consistency when adding e.g.
27
# new assertFoo() methods.
31
from cStringIO import StringIO
38
from pprint import pformat
43
from subprocess import Popen, PIPE, STDOUT
19
68
import bzrlib.commands
22
MODULES_TO_DOCTEST = []
25
class BzrTestBase(InTempDir):
26
"""bzr-specific test base class"""
27
def run_bzr(self, *args, **kwargs):
28
retcode = kwargs.get('retcode', 0)
29
self.assertEquals(bzrlib.commands.run_bzr(args), retcode)
69
import bzrlib.timestamp
71
import bzrlib.inventory
72
import bzrlib.iterablefile
77
# lsprof not available
79
from bzrlib.merge import merge_inner
82
from bzrlib.smart import client, request, server
84
from bzrlib import symbol_versioning
85
from bzrlib.symbol_versioning import (
92
from bzrlib.transport import get_transport
93
import bzrlib.transport
94
from bzrlib.transport.local import LocalURLServer
95
from bzrlib.transport.memory import MemoryServer
96
from bzrlib.transport.readonly import ReadonlyServer
97
from bzrlib.trace import mutter, note
98
from bzrlib.tests import TestUtil
99
from bzrlib.tests.http_server import HttpServer
100
from bzrlib.tests.TestUtil import (
104
from bzrlib.tests.treeshape import build_tree_contents
105
from bzrlib.ui.text import TextUIFactory
106
import bzrlib.version_info_formats.format_custom
107
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
109
# Mark this python module as being part of the implementation
110
# of unittest: this gives us better tracebacks where the last
111
# shown frame is the test code, not our assertXYZ.
114
default_transport = LocalURLServer
117
class ExtendedTestResult(unittest._TextTestResult):
118
"""Accepts, reports and accumulates the results of running tests.
120
Compared to the unittest version this class adds support for
121
profiling, benchmarking, stopping as soon as a test fails, and
122
skipping tests. There are further-specialized subclasses for
123
different types of display.
125
When a test finishes, in whatever way, it calls one of the addSuccess,
126
addFailure or addError classes. These in turn may redirect to a more
127
specific case for the special test results supported by our extended
130
Note that just one of these objects is fed the results from many tests.
135
def __init__(self, stream, descriptions, verbosity,
140
"""Construct new TestResult.
142
:param bench_history: Optionally, a writable file object to accumulate
145
unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
146
if bench_history is not None:
147
from bzrlib.version import _get_bzr_source_tree
148
src_tree = _get_bzr_source_tree()
151
revision_id = src_tree.get_parent_ids()[0]
153
# XXX: if this is a brand new tree, do the same as if there
157
# XXX: If there's no branch, what should we do?
159
bench_history.write("--date %s %s\n" % (time.time(), revision_id))
160
self._bench_history = bench_history
161
self.ui = ui.ui_factory
162
self.num_tests = num_tests
164
self.failure_count = 0
165
self.known_failure_count = 0
167
self.not_applicable_count = 0
168
self.unsupported = {}
170
self._overall_start_time = time.time()
171
self._strict = strict
175
ok = self.wasStrictlySuccessful()
177
ok = self.wasSuccessful()
179
self.stream.write('tests passed\n')
181
self.stream.write('tests failed\n')
182
if TestCase._first_thread_leaker_id:
184
'%s is leaking threads among %d leaking tests.\n' % (
185
TestCase._first_thread_leaker_id,
186
TestCase._leaking_threads_tests))
188
def _extractBenchmarkTime(self, testCase):
189
"""Add a benchmark time for the current test case."""
190
return getattr(testCase, "_benchtime", None)
192
def _elapsedTestTimeString(self):
193
"""Return a time string for the overall time the current test has taken."""
194
return self._formatTime(time.time() - self._start_time)
196
def _testTimeString(self, testCase):
197
benchmark_time = self._extractBenchmarkTime(testCase)
198
if benchmark_time is not None:
200
self._formatTime(benchmark_time),
201
self._elapsedTestTimeString())
203
return " %s" % self._elapsedTestTimeString()
205
def _formatTime(self, seconds):
206
"""Format seconds as milliseconds with leading spaces."""
207
# some benchmarks can take thousands of seconds to run, so we need 8
209
return "%8dms" % (1000 * seconds)
211
def _shortened_test_description(self, test):
213
what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
216
def startTest(self, test):
217
unittest.TestResult.startTest(self, test)
220
self.report_test_start(test)
221
test.number = self.count
222
self._recordTestStartTime()
224
def startTests(self):
226
'testing: %s\n' % (osutils.realpath(sys.argv[0]),))
228
' %s (%s python%s)\n' % (
230
bzrlib.version_string,
231
bzrlib._format_version_tuple(sys.version_info),
233
self.stream.write('\n')
235
def _recordTestStartTime(self):
236
"""Record that a test has started."""
237
self._start_time = time.time()
239
def _cleanupLogFile(self, test):
240
# We can only do this if we have one of our TestCases, not if
242
setKeepLogfile = getattr(test, 'setKeepLogfile', None)
243
if setKeepLogfile is not None:
246
def addError(self, test, err):
247
"""Tell result that test finished with an error.
249
Called from the TestCase run() method when the test
250
fails with an unexpected error.
252
self._testConcluded(test)
253
if isinstance(err[1], TestNotApplicable):
254
return self._addNotApplicable(test, err)
255
elif isinstance(err[1], UnavailableFeature):
256
return self.addNotSupported(test, err[1].args[0])
258
unittest.TestResult.addError(self, test, err)
259
self.error_count += 1
260
self.report_error(test, err)
263
self._cleanupLogFile(test)
265
def addFailure(self, test, err):
266
"""Tell result that test failed.
268
Called from the TestCase run() method when the test
269
fails because e.g. an assert() method failed.
271
self._testConcluded(test)
272
if isinstance(err[1], KnownFailure):
273
return self._addKnownFailure(test, err)
275
unittest.TestResult.addFailure(self, test, err)
276
self.failure_count += 1
277
self.report_failure(test, err)
280
self._cleanupLogFile(test)
282
def addSuccess(self, test):
283
"""Tell result that test completed successfully.
285
Called from the TestCase run()
287
self._testConcluded(test)
288
if self._bench_history is not None:
289
benchmark_time = self._extractBenchmarkTime(test)
290
if benchmark_time is not None:
291
self._bench_history.write("%s %s\n" % (
292
self._formatTime(benchmark_time),
294
self.report_success(test)
295
self._cleanupLogFile(test)
296
unittest.TestResult.addSuccess(self, test)
297
test._log_contents = ''
299
def _testConcluded(self, test):
300
"""Common code when a test has finished.
302
Called regardless of whether it succeded, failed, etc.
306
def _addKnownFailure(self, test, err):
307
self.known_failure_count += 1
308
self.report_known_failure(test, err)
310
def addNotSupported(self, test, feature):
311
"""The test will not be run because of a missing feature.
313
# this can be called in two different ways: it may be that the
314
# test started running, and then raised (through addError)
315
# UnavailableFeature. Alternatively this method can be called
316
# while probing for features before running the tests; in that
317
# case we will see startTest and stopTest, but the test will never
319
self.unsupported.setdefault(str(feature), 0)
320
self.unsupported[str(feature)] += 1
321
self.report_unsupported(test, feature)
323
def addSkip(self, test, reason):
324
"""A test has not run for 'reason'."""
326
self.report_skip(test, reason)
328
def _addNotApplicable(self, test, skip_excinfo):
329
if isinstance(skip_excinfo[1], TestNotApplicable):
330
self.not_applicable_count += 1
331
self.report_not_applicable(test, skip_excinfo)
334
except KeyboardInterrupt:
337
self.addError(test, test.exc_info())
339
# seems best to treat this as success from point-of-view of unittest
340
# -- it actually does nothing so it barely matters :)
341
unittest.TestResult.addSuccess(self, test)
342
test._log_contents = ''
344
def printErrorList(self, flavour, errors):
345
for test, err in errors:
346
self.stream.writeln(self.separator1)
347
self.stream.write("%s: " % flavour)
348
self.stream.writeln(self.getDescription(test))
349
if getattr(test, '_get_log', None) is not None:
350
self.stream.write('\n')
352
('vvvv[log from %s]' % test.id()).ljust(78,'-'))
353
self.stream.write('\n')
354
self.stream.write(test._get_log())
355
self.stream.write('\n')
357
('^^^^[log from %s]' % test.id()).ljust(78,'-'))
358
self.stream.write('\n')
359
self.stream.writeln(self.separator2)
360
self.stream.writeln("%s" % err)
365
def report_cleaning_up(self):
368
def report_success(self, test):
371
def wasStrictlySuccessful(self):
372
if self.unsupported or self.known_failure_count:
374
return self.wasSuccessful()
377
class TextTestResult(ExtendedTestResult):
378
"""Displays progress and results of tests in text form"""
380
def __init__(self, stream, descriptions, verbosity,
386
ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
387
bench_history, num_tests, strict)
389
self.pb = self.ui.nested_progress_bar()
390
self._supplied_pb = False
393
self._supplied_pb = True
394
self.pb.show_pct = False
395
self.pb.show_spinner = False
396
self.pb.show_eta = False,
397
self.pb.show_count = False
398
self.pb.show_bar = False
400
def report_starting(self):
401
self.pb.update('[test 0/%d] Starting' % (self.num_tests))
403
def _progress_prefix_text(self):
404
# the longer this text, the less space we have to show the test
406
a = '[%d' % self.count # total that have been run
407
# tests skipped as known not to be relevant are not important enough
409
## if self.skip_count:
410
## a += ', %d skip' % self.skip_count
411
## if self.known_failure_count:
412
## a += '+%dX' % self.known_failure_count
413
if self.num_tests is not None:
414
a +='/%d' % self.num_tests
416
runtime = time.time() - self._overall_start_time
418
a += '%dm%ds' % (runtime / 60, runtime % 60)
422
a += ', %d err' % self.error_count
423
if self.failure_count:
424
a += ', %d fail' % self.failure_count
426
a += ', %d missing' % len(self.unsupported)
430
def report_test_start(self, test):
433
self._progress_prefix_text()
435
+ self._shortened_test_description(test))
437
def _test_description(self, test):
438
return self._shortened_test_description(test)
440
def report_error(self, test, err):
441
self.pb.note('ERROR: %s\n %s\n',
442
self._test_description(test),
446
def report_failure(self, test, err):
447
self.pb.note('FAIL: %s\n %s\n',
448
self._test_description(test),
452
def report_known_failure(self, test, err):
453
self.pb.note('XFAIL: %s\n%s\n',
454
self._test_description(test), err[1])
456
def report_skip(self, test, reason):
459
def report_not_applicable(self, test, skip_excinfo):
462
def report_unsupported(self, test, feature):
463
"""test cannot be run because feature is missing."""
465
def report_cleaning_up(self):
466
self.pb.update('Cleaning up')
469
if not self._supplied_pb:
473
class VerboseTestResult(ExtendedTestResult):
474
"""Produce long output, with one line per test run plus times"""
476
def _ellipsize_to_right(self, a_string, final_width):
477
"""Truncate and pad a string, keeping the right hand side"""
478
if len(a_string) > final_width:
479
result = '...' + a_string[3-final_width:]
482
return result.ljust(final_width)
484
def report_starting(self):
485
self.stream.write('running %d tests...\n' % self.num_tests)
487
def report_test_start(self, test):
489
name = self._shortened_test_description(test)
490
# width needs space for 6 char status, plus 1 for slash, plus 2 10-char
491
# numbers, plus a trailing blank
492
# when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on space
493
self.stream.write(self._ellipsize_to_right(name,
494
osutils.terminal_width()-30))
497
def _error_summary(self, err):
499
return '%s%s' % (indent, err[1])
501
def report_error(self, test, err):
502
self.stream.writeln('ERROR %s\n%s'
503
% (self._testTimeString(test),
504
self._error_summary(err)))
506
def report_failure(self, test, err):
507
self.stream.writeln(' FAIL %s\n%s'
508
% (self._testTimeString(test),
509
self._error_summary(err)))
511
def report_known_failure(self, test, err):
512
self.stream.writeln('XFAIL %s\n%s'
513
% (self._testTimeString(test),
514
self._error_summary(err)))
516
def report_success(self, test):
517
self.stream.writeln(' OK %s' % self._testTimeString(test))
518
for bench_called, stats in getattr(test, '_benchcalls', []):
519
self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
520
stats.pprint(file=self.stream)
521
# flush the stream so that we get smooth output. This verbose mode is
522
# used to show the output in PQM.
525
def report_skip(self, test, reason):
526
self.stream.writeln(' SKIP %s\n%s'
527
% (self._testTimeString(test), reason))
529
def report_not_applicable(self, test, skip_excinfo):
530
self.stream.writeln(' N/A %s\n%s'
531
% (self._testTimeString(test),
532
self._error_summary(skip_excinfo)))
534
def report_unsupported(self, test, feature):
535
"""test cannot be run because feature is missing."""
536
self.stream.writeln("NODEP %s\n The feature '%s' is not available."
537
%(self._testTimeString(test), feature))
540
class TextTestRunner(object):
541
stop_on_failure = False
551
self.stream = unittest._WritelnDecorator(stream)
552
self.descriptions = descriptions
553
self.verbosity = verbosity
554
self._bench_history = bench_history
555
self.list_only = list_only
556
self._strict = strict
559
"Run the given test case or test suite."
560
startTime = time.time()
561
if self.verbosity == 1:
562
result_class = TextTestResult
563
elif self.verbosity >= 2:
564
result_class = VerboseTestResult
565
result = result_class(self.stream,
568
bench_history=self._bench_history,
569
num_tests=test.countTestCases(),
572
result.stop_early = self.stop_on_failure
573
result.report_starting()
575
if self.verbosity >= 2:
576
self.stream.writeln("Listing tests only ...\n")
578
for t in iter_suite_tests(test):
579
self.stream.writeln("%s" % (t.id()))
588
if isinstance(test, testtools.ConcurrentTestSuite):
589
# We need to catch bzr specific behaviors
590
test.run(BZRTransformingResult(result))
593
run = result.testsRun
595
stopTime = time.time()
596
timeTaken = stopTime - startTime
598
self.stream.writeln(result.separator2)
599
self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
600
run, run != 1 and "s" or "", timeTaken))
601
self.stream.writeln()
602
if not result.wasSuccessful():
603
self.stream.write("FAILED (")
604
failed, errored = map(len, (result.failures, result.errors))
606
self.stream.write("failures=%d" % failed)
608
if failed: self.stream.write(", ")
609
self.stream.write("errors=%d" % errored)
610
if result.known_failure_count:
611
if failed or errored: self.stream.write(", ")
612
self.stream.write("known_failure_count=%d" %
613
result.known_failure_count)
614
self.stream.writeln(")")
616
if result.known_failure_count:
617
self.stream.writeln("OK (known_failures=%d)" %
618
result.known_failure_count)
620
self.stream.writeln("OK")
621
if result.skip_count > 0:
622
skipped = result.skip_count
623
self.stream.writeln('%d test%s skipped' %
624
(skipped, skipped != 1 and "s" or ""))
625
if result.unsupported:
626
for feature, count in sorted(result.unsupported.items()):
627
self.stream.writeln("Missing feature '%s' skipped %d tests." %
633
def iter_suite_tests(suite):
634
"""Return all tests in a suite, recursing through nested suites"""
635
if isinstance(suite, unittest.TestCase):
637
elif isinstance(suite, unittest.TestSuite):
639
for r in iter_suite_tests(item):
642
raise Exception('unknown type %r for object %r'
643
% (type(suite), suite))
646
class TestSkipped(Exception):
647
"""Indicates that a test was intentionally skipped, rather than failing."""
650
class TestNotApplicable(TestSkipped):
651
"""A test is not applicable to the situation where it was run.
653
This is only normally raised by parameterized tests, if they find that
654
the instance they're constructed upon does not support one aspect
659
class KnownFailure(AssertionError):
660
"""Indicates that a test failed in a precisely expected manner.
662
Such failures dont block the whole test suite from passing because they are
663
indicators of partially completed code or of future work. We have an
664
explicit error for them so that we can ensure that they are always visible:
665
KnownFailures are always shown in the output of bzr selftest.
669
class UnavailableFeature(Exception):
670
"""A feature required for this test was not available.
672
The feature should be used to construct the exception.
676
class CommandFailed(Exception):
680
class StringIOWrapper(object):
681
"""A wrapper around cStringIO which just adds an encoding attribute.
683
Internally we can check sys.stdout to see what the output encoding
684
should be. However, cStringIO has no encoding attribute that we can
685
set. So we wrap it instead.
690
def __init__(self, s=None):
692
self.__dict__['_cstring'] = StringIO(s)
694
self.__dict__['_cstring'] = StringIO()
696
def __getattr__(self, name, getattr=getattr):
697
return getattr(self.__dict__['_cstring'], name)
699
def __setattr__(self, name, val):
700
if name == 'encoding':
701
self.__dict__['encoding'] = val
703
return setattr(self._cstring, name, val)
706
class TestUIFactory(TextUIFactory):
707
"""A UI Factory for testing.
709
Hide the progress bar but emit note()s.
711
Allows get_password to be tested without real tty attached.
714
def __init__(self, stdout=None, stderr=None, stdin=None):
715
if stdin is not None:
716
# We use a StringIOWrapper to be able to test various
717
# encodings, but the user is still responsible to
718
# encode the string and to set the encoding attribute
719
# of StringIOWrapper.
720
stdin = StringIOWrapper(stdin)
721
super(TestUIFactory, self).__init__(stdin, stdout, stderr)
724
"""See progress.ProgressBar.clear()."""
726
def clear_term(self):
727
"""See progress.ProgressBar.clear_term()."""
730
"""See progress.ProgressBar.finished()."""
732
def note(self, fmt_string, *args):
733
"""See progress.ProgressBar.note()."""
735
fmt_string = fmt_string % args
736
self.stdout.write(fmt_string + "\n")
738
def progress_bar(self):
741
def nested_progress_bar(self):
744
def update(self, message, count=None, total=None):
745
"""See progress.ProgressBar.update()."""
747
def get_non_echoed_password(self):
748
"""Get password from stdin without trying to handle the echo mode"""
749
password = self.stdin.readline()
752
if password[-1] == '\n':
753
password = password[:-1]
757
class TestCase(unittest.TestCase):
758
"""Base class for bzr unit tests.
760
Tests that need access to disk resources should subclass
761
TestCaseInTempDir not TestCase.
763
Error and debug log messages are redirected from their usual
764
location into a temporary file, the contents of which can be
765
retrieved by _get_log(). We use a real OS file, not an in-memory object,
766
so that it can also capture file IO. When the test completes this file
767
is read into memory and removed from disk.
769
There are also convenience functions to invoke bzr's command-line
770
routine, and to build and check bzr trees.
772
In addition to the usual method of overriding tearDown(), this class also
773
allows subclasses to register functions into the _cleanups list, which is
774
run in order as the object is torn down. It's less likely this will be
775
accidentally overlooked.
778
_active_threads = None
779
_leaking_threads_tests = 0
780
_first_thread_leaker_id = None
781
_log_file_name = None
783
_keep_log_file = False
784
# record lsprof data when performing benchmark calls.
785
_gather_lsprof_in_benchmarks = False
786
attrs_to_keep = ('id', '_testMethodName', '_testMethodDoc',
787
'_log_contents', '_log_file_name', '_benchtime',
788
'_TestCase__testMethodName', '_TestCase__testMethodDoc',)
790
def __init__(self, methodName='testMethod'):
791
super(TestCase, self).__init__(methodName)
793
self._bzr_test_setUp_run = False
794
self._bzr_test_tearDown_run = False
797
unittest.TestCase.setUp(self)
798
self._bzr_test_setUp_run = True
799
self._cleanEnvironment()
802
self._benchcalls = []
803
self._benchtime = None
805
# Track locks - needs to be called before _clear_debug_flags.
807
self._clear_debug_flags()
808
TestCase._active_threads = threading.activeCount()
809
self.addCleanup(self._check_leaked_threads)
814
pdb.Pdb().set_trace(sys._getframe().f_back)
816
def _check_leaked_threads(self):
817
active = threading.activeCount()
818
leaked_threads = active - TestCase._active_threads
819
TestCase._active_threads = active
821
TestCase._leaking_threads_tests += 1
822
if TestCase._first_thread_leaker_id is None:
823
TestCase._first_thread_leaker_id = self.id()
825
def _clear_debug_flags(self):
826
"""Prevent externally set debug flags affecting tests.
828
Tests that want to use debug flags can just set them in the
829
debug_flags set during setup/teardown.
831
self._preserved_debug_flags = set(debug.debug_flags)
832
if 'allow_debug' not in selftest_debug_flags:
833
debug.debug_flags.clear()
834
self.addCleanup(self._restore_debug_flags)
836
def _clear_hooks(self):
837
# prevent hooks affecting tests
838
self._preserved_hooks = {}
839
for key, factory in hooks.known_hooks.items():
840
parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
841
current_hooks = hooks.known_hooks_key_to_object(key)
842
self._preserved_hooks[parent] = (name, current_hooks)
843
self.addCleanup(self._restoreHooks)
844
for key, factory in hooks.known_hooks.items():
845
parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
846
setattr(parent, name, factory())
847
# this hook should always be installed
848
request._install_hook()
850
def _silenceUI(self):
851
"""Turn off UI for duration of test"""
852
# by default the UI is off; tests can turn it on if they want it.
853
saved = ui.ui_factory
855
ui.ui_factory = saved
856
ui.ui_factory = ui.SilentUIFactory()
857
self.addCleanup(_restore)
859
def _check_locks(self):
860
"""Check that all lock take/release actions have been paired."""
861
# once we have fixed all the current lock problems, we can change the
862
# following code to always check for mismatched locks, but only do
863
# traceback showing with -Dlock (self._lock_check_thorough is True).
864
# For now, because the test suite will fail, we only assert that lock
865
# matching has occured with -Dlock.
867
acquired_locks = [lock for action, lock in self._lock_actions
868
if action == 'acquired']
869
released_locks = [lock for action, lock in self._lock_actions
870
if action == 'released']
871
broken_locks = [lock for action, lock in self._lock_actions
872
if action == 'broken']
873
# trivially, given the tests for lock acquistion and release, if we
874
# have as many in each list, it should be ok. Some lock tests also
875
# break some locks on purpose and should be taken into account by
876
# considering that breaking a lock is just a dirty way of releasing it.
877
if len(acquired_locks) != (len(released_locks) + len(broken_locks)):
878
message = ('Different number of acquired and '
879
'released or broken locks. (%s, %s + %s)' %
880
(acquired_locks, released_locks, broken_locks))
881
if not self._lock_check_thorough:
882
# Rather than fail, just warn
883
print "Broken test %s: %s" % (self, message)
887
def _track_locks(self):
888
"""Track lock activity during tests."""
889
self._lock_actions = []
890
self._lock_check_thorough = 'lock' not in debug.debug_flags
891
self.addCleanup(self._check_locks)
892
_mod_lock.Lock.hooks.install_named_hook('lock_acquired',
893
self._lock_acquired, None)
894
_mod_lock.Lock.hooks.install_named_hook('lock_released',
895
self._lock_released, None)
896
_mod_lock.Lock.hooks.install_named_hook('lock_broken',
897
self._lock_broken, None)
899
def _lock_acquired(self, result):
900
self._lock_actions.append(('acquired', result))
902
def _lock_released(self, result):
903
self._lock_actions.append(('released', result))
905
def _lock_broken(self, result):
906
self._lock_actions.append(('broken', result))
908
def _ndiff_strings(self, a, b):
909
"""Return ndiff between two strings containing lines.
911
A trailing newline is added if missing to make the strings
913
if b and b[-1] != '\n':
915
if a and a[-1] != '\n':
917
difflines = difflib.ndiff(a.splitlines(True),
919
linejunk=lambda x: False,
920
charjunk=lambda x: False)
921
return ''.join(difflines)
923
def assertEqual(self, a, b, message=''):
927
except UnicodeError, e:
928
# If we can't compare without getting a UnicodeError, then
929
# obviously they are different
930
mutter('UnicodeError: %s', e)
933
raise AssertionError("%snot equal:\na = %s\nb = %s\n"
935
pformat(a), pformat(b)))
937
assertEquals = assertEqual
939
def assertEqualDiff(self, a, b, message=None):
940
"""Assert two texts are equal, if not raise an exception.
942
This is intended for use with multi-line strings where it can
943
be hard to find the differences by eye.
945
# TODO: perhaps override assertEquals to call this for strings?
949
message = "texts not equal:\n"
951
message = 'first string is missing a final newline.\n'
953
message = 'second string is missing a final newline.\n'
954
raise AssertionError(message +
955
self._ndiff_strings(a, b))
957
def assertEqualMode(self, mode, mode_test):
958
self.assertEqual(mode, mode_test,
959
'mode mismatch %o != %o' % (mode, mode_test))
961
def assertEqualStat(self, expected, actual):
962
"""assert that expected and actual are the same stat result.
964
:param expected: A stat result.
965
:param actual: A stat result.
966
:raises AssertionError: If the expected and actual stat values differ
969
self.assertEqual(expected.st_size, actual.st_size)
970
self.assertEqual(expected.st_mtime, actual.st_mtime)
971
self.assertEqual(expected.st_ctime, actual.st_ctime)
972
self.assertEqual(expected.st_dev, actual.st_dev)
973
self.assertEqual(expected.st_ino, actual.st_ino)
974
self.assertEqual(expected.st_mode, actual.st_mode)
976
def assertLength(self, length, obj_with_len):
977
"""Assert that obj_with_len is of length length."""
978
if len(obj_with_len) != length:
979
self.fail("Incorrect length: wanted %d, got %d for %r" % (
980
length, len(obj_with_len), obj_with_len))
982
def assertPositive(self, val):
983
"""Assert that val is greater than 0."""
984
self.assertTrue(val > 0, 'expected a positive value, but got %s' % val)
986
def assertNegative(self, val):
987
"""Assert that val is less than 0."""
988
self.assertTrue(val < 0, 'expected a negative value, but got %s' % val)
990
def assertStartsWith(self, s, prefix):
991
if not s.startswith(prefix):
992
raise AssertionError('string %r does not start with %r' % (s, prefix))
994
def assertEndsWith(self, s, suffix):
995
"""Asserts that s ends with suffix."""
996
if not s.endswith(suffix):
997
raise AssertionError('string %r does not end with %r' % (s, suffix))
999
def assertContainsRe(self, haystack, needle_re, flags=0):
1000
"""Assert that a contains something matching a regular expression."""
1001
if not re.search(needle_re, haystack, flags):
1002
if '\n' in haystack or len(haystack) > 60:
1003
# a long string, format it in a more readable way
1004
raise AssertionError(
1005
'pattern "%s" not found in\n"""\\\n%s"""\n'
1006
% (needle_re, haystack))
1008
raise AssertionError('pattern "%s" not found in "%s"'
1009
% (needle_re, haystack))
1011
def assertNotContainsRe(self, haystack, needle_re, flags=0):
1012
"""Assert that a does not match a regular expression"""
1013
if re.search(needle_re, haystack, flags):
1014
raise AssertionError('pattern "%s" found in "%s"'
1015
% (needle_re, haystack))
1017
def assertSubset(self, sublist, superlist):
1018
"""Assert that every entry in sublist is present in superlist."""
1019
missing = set(sublist) - set(superlist)
1020
if len(missing) > 0:
1021
raise AssertionError("value(s) %r not present in container %r" %
1022
(missing, superlist))
1024
def assertListRaises(self, excClass, func, *args, **kwargs):
1025
"""Fail unless excClass is raised when the iterator from func is used.
1027
Many functions can return generators this makes sure
1028
to wrap them in a list() call to make sure the whole generator
1029
is run, and that the proper exception is raised.
1032
list(func(*args, **kwargs))
1036
if getattr(excClass,'__name__', None) is not None:
1037
excName = excClass.__name__
1039
excName = str(excClass)
1040
raise self.failureException, "%s not raised" % excName
1042
def assertRaises(self, excClass, callableObj, *args, **kwargs):
1043
"""Assert that a callable raises a particular exception.
1045
:param excClass: As for the except statement, this may be either an
1046
exception class, or a tuple of classes.
1047
:param callableObj: A callable, will be passed ``*args`` and
1050
Returns the exception so that you can examine it.
1053
callableObj(*args, **kwargs)
1057
if getattr(excClass,'__name__', None) is not None:
1058
excName = excClass.__name__
1061
excName = str(excClass)
1062
raise self.failureException, "%s not raised" % excName
1064
def assertIs(self, left, right, message=None):
1065
if not (left is right):
1066
if message is not None:
1067
raise AssertionError(message)
1069
raise AssertionError("%r is not %r." % (left, right))
1071
def assertIsNot(self, left, right, message=None):
1073
if message is not None:
1074
raise AssertionError(message)
1076
raise AssertionError("%r is %r." % (left, right))
1078
def assertTransportMode(self, transport, path, mode):
1079
"""Fail if a path does not have mode "mode".
1081
If modes are not supported on this transport, the assertion is ignored.
1083
if not transport._can_roundtrip_unix_modebits():
1085
path_stat = transport.stat(path)
1086
actual_mode = stat.S_IMODE(path_stat.st_mode)
1087
self.assertEqual(mode, actual_mode,
1088
'mode of %r incorrect (%s != %s)'
1089
% (path, oct(mode), oct(actual_mode)))
1091
def assertIsSameRealPath(self, path1, path2):
1092
"""Fail if path1 and path2 points to different files"""
1093
self.assertEqual(osutils.realpath(path1),
1094
osutils.realpath(path2),
1095
"apparent paths:\na = %s\nb = %s\n," % (path1, path2))
1097
def assertIsInstance(self, obj, kls, msg=None):
1098
"""Fail if obj is not an instance of kls
32
def selftest(verbose=False):
33
from unittest import TestLoader, TestSuite
34
import bzrlib, bzrlib.store, bzrlib.inventory, bzrlib.branch
35
import bzrlib.osutils, bzrlib.commands, bzrlib.merge3, bzrlib.plugin
36
from doctest import DocTestSuite
43
global MODULES_TO_TEST, MODULES_TO_DOCTEST
46
['bzrlib.selftest.whitebox',
47
'bzrlib.selftest.versioning',
48
'bzrlib.selftest.testinv',
49
'bzrlib.selftest.testmerge3',
50
'bzrlib.selftest.testhashcache',
51
'bzrlib.selftest.teststatus',
52
'bzrlib.selftest.testlog',
53
'bzrlib.selftest.blackbox',
54
'bzrlib.selftest.testrevisionnamespaces',
55
'bzrlib.selftest.testbranch',
56
'bzrlib.selftest.testrevision',
58
'bzrlib.selftest.testdiff',
1100
:param msg: Supplementary message to show if the assertion fails.
1102
if not isinstance(obj, kls):
1103
m = "%r is an instance of %s rather than %s" % (
1104
obj, obj.__class__, kls)
1109
def expectFailure(self, reason, assertion, *args, **kwargs):
1110
"""Invoke a test, expecting it to fail for the given reason.
1112
This is for assertions that ought to succeed, but currently fail.
1113
(The failure is *expected* but not *wanted*.) Please be very precise
1114
about the failure you're expecting. If a new bug is introduced,
1115
AssertionError should be raised, not KnownFailure.
1117
Frequently, expectFailure should be followed by an opposite assertion.
1120
Intended to be used with a callable that raises AssertionError as the
1121
'assertion' parameter. args and kwargs are passed to the 'assertion'.
1123
Raises KnownFailure if the test fails. Raises AssertionError if the
1128
self.expectFailure('Math is broken', self.assertNotEqual, 54,
1130
self.assertEqual(42, dynamic_val)
1132
This means that a dynamic_val of 54 will cause the test to raise
1133
a KnownFailure. Once math is fixed and the expectFailure is removed,
1134
only a dynamic_val of 42 will allow the test to pass. Anything other
1135
than 54 or 42 will cause an AssertionError.
1138
assertion(*args, **kwargs)
1139
except AssertionError:
1140
raise KnownFailure(reason)
1142
self.fail('Unexpected success. Should have failed: %s' % reason)
1144
def assertFileEqual(self, content, path):
1145
"""Fail if path does not contain 'content'."""
1146
self.failUnlessExists(path)
1147
f = file(path, 'rb')
1152
self.assertEqualDiff(content, s)
1154
def failUnlessExists(self, path):
1155
"""Fail unless path or paths, which may be abs or relative, exist."""
1156
if not isinstance(path, basestring):
1158
self.failUnlessExists(p)
1160
self.failUnless(osutils.lexists(path),path+" does not exist")
1162
def failIfExists(self, path):
1163
"""Fail if path or paths, which may be abs or relative, exist."""
1164
if not isinstance(path, basestring):
1166
self.failIfExists(p)
1168
self.failIf(osutils.lexists(path),path+" exists")
1170
def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1171
"""A helper for callDeprecated and applyDeprecated.
1173
:param a_callable: A callable to call.
1174
:param args: The positional arguments for the callable
1175
:param kwargs: The keyword arguments for the callable
1176
:return: A tuple (warnings, result). result is the result of calling
1177
a_callable(``*args``, ``**kwargs``).
1180
def capture_warnings(msg, cls=None, stacklevel=None):
1181
# we've hooked into a deprecation specific callpath,
1182
# only deprecations should getting sent via it.
1183
self.assertEqual(cls, DeprecationWarning)
1184
local_warnings.append(msg)
1185
original_warning_method = symbol_versioning.warn
1186
symbol_versioning.set_warning_method(capture_warnings)
1188
result = a_callable(*args, **kwargs)
1190
symbol_versioning.set_warning_method(original_warning_method)
1191
return (local_warnings, result)
1193
def applyDeprecated(self, deprecation_format, a_callable, *args, **kwargs):
1194
"""Call a deprecated callable without warning the user.
1196
Note that this only captures warnings raised by symbol_versioning.warn,
1197
not other callers that go direct to the warning module.
1199
To test that a deprecated method raises an error, do something like
1202
self.assertRaises(errors.ReservedId,
1203
self.applyDeprecated,
1204
deprecated_in((1, 5, 0)),
1208
:param deprecation_format: The deprecation format that the callable
1209
should have been deprecated with. This is the same type as the
1210
parameter to deprecated_method/deprecated_function. If the
1211
callable is not deprecated with this format, an assertion error
1213
:param a_callable: A callable to call. This may be a bound method or
1214
a regular function. It will be called with ``*args`` and
1216
:param args: The positional arguments for the callable
1217
:param kwargs: The keyword arguments for the callable
1218
:return: The result of a_callable(``*args``, ``**kwargs``)
1220
call_warnings, result = self._capture_deprecation_warnings(a_callable,
1222
expected_first_warning = symbol_versioning.deprecation_string(
1223
a_callable, deprecation_format)
1224
if len(call_warnings) == 0:
1225
self.fail("No deprecation warning generated by call to %s" %
1227
self.assertEqual(expected_first_warning, call_warnings[0])
1230
def callCatchWarnings(self, fn, *args, **kw):
1231
"""Call a callable that raises python warnings.
1233
The caller's responsible for examining the returned warnings.
1235
If the callable raises an exception, the exception is not
1236
caught and propagates up to the caller. In that case, the list
1237
of warnings is not available.
1239
:returns: ([warning_object, ...], fn_result)
1241
# XXX: This is not perfect, because it completely overrides the
1242
# warnings filters, and some code may depend on suppressing particular
1243
# warnings. It's the easiest way to insulate ourselves from -Werror,
1244
# though. -- Andrew, 20071062
1246
def _catcher(message, category, filename, lineno, file=None, line=None):
1247
# despite the name, 'message' is normally(?) a Warning subclass
1249
wlist.append(message)
1250
saved_showwarning = warnings.showwarning
1251
saved_filters = warnings.filters
1253
warnings.showwarning = _catcher
1254
warnings.filters = []
1255
result = fn(*args, **kw)
1257
warnings.showwarning = saved_showwarning
1258
warnings.filters = saved_filters
1259
return wlist, result
1261
def callDeprecated(self, expected, callable, *args, **kwargs):
1262
"""Assert that a callable is deprecated in a particular way.
1264
This is a very precise test for unusual requirements. The
1265
applyDeprecated helper function is probably more suited for most tests
1266
as it allows you to simply specify the deprecation format being used
1267
and will ensure that that is issued for the function being called.
1269
Note that this only captures warnings raised by symbol_versioning.warn,
1270
not other callers that go direct to the warning module. To catch
1271
general warnings, use callCatchWarnings.
1273
:param expected: a list of the deprecation warnings expected, in order
1274
:param callable: The callable to call
1275
:param args: The positional arguments for the callable
1276
:param kwargs: The keyword arguments for the callable
1278
call_warnings, result = self._capture_deprecation_warnings(callable,
1280
self.assertEqual(expected, call_warnings)
1283
def _startLogFile(self):
1284
"""Send bzr and test log messages to a temporary file.
1286
The file is removed as the test is torn down.
1288
fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
1289
self._log_file = os.fdopen(fileno, 'w+')
1290
self._log_memento = bzrlib.trace.push_log_file(self._log_file)
1291
self._log_file_name = name
1292
self.addCleanup(self._finishLogFile)
1294
def _finishLogFile(self):
1295
"""Finished with the log file.
1297
Close the file and delete it, unless setKeepLogfile was called.
1299
if self._log_file is None:
1301
bzrlib.trace.pop_log_file(self._log_memento)
1302
self._log_file.close()
1303
self._log_file = None
1304
if not self._keep_log_file:
1305
os.remove(self._log_file_name)
1306
self._log_file_name = None
1308
def setKeepLogfile(self):
1309
"""Make the logfile not be deleted when _finishLogFile is called."""
1310
self._keep_log_file = True
1312
def addCleanup(self, callable, *args, **kwargs):
1313
"""Arrange to run a callable when this case is torn down.
1315
Callables are run in the reverse of the order they are registered,
1316
ie last-in first-out.
1318
self._cleanups.append((callable, args, kwargs))
1320
def _cleanEnvironment(self):
1322
'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
1323
'HOME': os.getcwd(),
1324
# bzr now uses the Win32 API and doesn't rely on APPDATA, but the
1325
# tests do check our impls match APPDATA
1326
'BZR_EDITOR': None, # test_msgeditor manipulates this variable
1330
'BZREMAIL': None, # may still be present in the environment
1332
'BZR_PROGRESS_BAR': None,
1334
'BZR_PLUGIN_PATH': None,
1335
# Make sure that any text ui tests are consistent regardless of
1336
# the environment the test case is run in; you may want tests that
1337
# test other combinations. 'dumb' is a reasonable guess for tests
1338
# going to a pipe or a StringIO.
1343
'SSH_AUTH_SOCK': None,
1347
'https_proxy': None,
1348
'HTTPS_PROXY': None,
1353
# Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
1354
# least. If you do (care), please update this comment
1358
'BZR_REMOTE_PATH': None,
1361
self.addCleanup(self._restoreEnvironment)
1362
for name, value in new_env.iteritems():
1363
self._captureVar(name, value)
1365
def _captureVar(self, name, newvalue):
1366
"""Set an environment variable, and reset it when finished."""
1367
self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
1369
def _restore_debug_flags(self):
1370
debug.debug_flags.clear()
1371
debug.debug_flags.update(self._preserved_debug_flags)
1373
def _restoreEnvironment(self):
1374
for name, value in self.__old_env.iteritems():
1375
osutils.set_or_unset_env(name, value)
1377
def _restoreHooks(self):
1378
for klass, (name, hooks) in self._preserved_hooks.items():
1379
setattr(klass, name, hooks)
1381
def knownFailure(self, reason):
1382
"""This test has failed for some known reason."""
1383
raise KnownFailure(reason)
1385
def _do_skip(self, result, reason):
1386
addSkip = getattr(result, 'addSkip', None)
1387
if not callable(addSkip):
1388
result.addError(self, sys.exc_info())
1390
addSkip(self, reason)
1392
def run(self, result=None):
1393
if result is None: result = self.defaultTestResult()
1394
for feature in getattr(self, '_test_needs_features', []):
1395
if not feature.available():
1396
result.startTest(self)
1397
if getattr(result, 'addNotSupported', None):
1398
result.addNotSupported(self, feature)
1400
result.addSuccess(self)
1401
result.stopTest(self)
1405
result.startTest(self)
1406
absent_attr = object()
1408
method_name = getattr(self, '_testMethodName', absent_attr)
1409
if method_name is absent_attr:
1411
method_name = getattr(self, '_TestCase__testMethodName')
1412
testMethod = getattr(self, method_name)
1416
if not self._bzr_test_setUp_run:
1418
"test setUp did not invoke "
1419
"bzrlib.tests.TestCase's setUp")
1420
except KeyboardInterrupt:
1423
except TestSkipped, e:
1424
self._do_skip(result, e.args[0])
1428
result.addError(self, sys.exc_info())
1436
except self.failureException:
1437
result.addFailure(self, sys.exc_info())
1438
except TestSkipped, e:
1440
reason = "No reason given."
1443
self._do_skip(result, reason)
1444
except KeyboardInterrupt:
1448
result.addError(self, sys.exc_info())
1452
if not self._bzr_test_tearDown_run:
1454
"test tearDown did not invoke "
1455
"bzrlib.tests.TestCase's tearDown")
1456
except KeyboardInterrupt:
1460
result.addError(self, sys.exc_info())
1463
if ok: result.addSuccess(self)
1465
result.stopTest(self)
1467
except TestNotApplicable:
1468
# Not moved from the result [yet].
1471
except KeyboardInterrupt:
1476
for attr_name in self.attrs_to_keep:
1477
if attr_name in self.__dict__:
1478
saved_attrs[attr_name] = self.__dict__[attr_name]
1479
self.__dict__ = saved_attrs
1483
self._log_contents = ''
1484
self._bzr_test_tearDown_run = True
1485
unittest.TestCase.tearDown(self)
1487
def time(self, callable, *args, **kwargs):
1488
"""Run callable and accrue the time it takes to the benchmark time.
1490
If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
1491
this will cause lsprofile statistics to be gathered and stored in
1494
if self._benchtime is None:
1498
if not self._gather_lsprof_in_benchmarks:
1499
return callable(*args, **kwargs)
1501
# record this benchmark
1502
ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
1504
self._benchcalls.append(((callable, args, kwargs), stats))
1507
self._benchtime += time.time() - start
1509
def _runCleanups(self):
1510
"""Run registered cleanup functions.
1512
This should only be called from TestCase.tearDown.
1514
# TODO: Perhaps this should keep running cleanups even if
1515
# one of them fails?
1517
# Actually pop the cleanups from the list so tearDown running
1518
# twice is safe (this happens for skipped tests).
1519
while self._cleanups:
1520
cleanup, args, kwargs = self._cleanups.pop()
1521
cleanup(*args, **kwargs)
1523
def log(self, *args):
1526
def _get_log(self, keep_log_file=False):
1527
"""Get the log from bzrlib.trace calls from this test.
1529
:param keep_log_file: When True, if the log is still a file on disk
1530
leave it as a file on disk. When False, if the log is still a file
1531
on disk, the log file is deleted and the log preserved as
1533
:return: A string containing the log.
1535
# flush the log file, to get all content
1537
if bzrlib.trace._trace_file:
1538
bzrlib.trace._trace_file.flush()
1539
if self._log_contents:
1540
# XXX: this can hardly contain the content flushed above --vila
1542
return self._log_contents
1543
if self._log_file_name is not None:
1544
logfile = open(self._log_file_name)
1546
log_contents = logfile.read()
1549
if not keep_log_file:
1550
self._log_contents = log_contents
1552
os.remove(self._log_file_name)
1554
if sys.platform == 'win32' and e.errno == errno.EACCES:
1555
sys.stderr.write(('Unable to delete log file '
1556
' %r\n' % self._log_file_name))
1561
return "DELETED log file to reduce memory footprint"
1563
def requireFeature(self, feature):
1564
"""This test requires a specific feature is available.
1566
:raises UnavailableFeature: When feature is not available.
1568
if not feature.available():
1569
raise UnavailableFeature(feature)
1571
def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
1573
"""Run bazaar command line, splitting up a string command line."""
1574
if isinstance(args, basestring):
1575
# shlex don't understand unicode strings,
1576
# so args should be plain string (bialix 20070906)
1577
args = list(shlex.split(str(args)))
1578
return self._run_bzr_core(args, retcode=retcode,
1579
encoding=encoding, stdin=stdin, working_dir=working_dir,
1582
def _run_bzr_core(self, args, retcode, encoding, stdin,
1584
if encoding is None:
1585
encoding = osutils.get_user_encoding()
1586
stdout = StringIOWrapper()
1587
stderr = StringIOWrapper()
1588
stdout.encoding = encoding
1589
stderr.encoding = encoding
1591
self.log('run bzr: %r', args)
1592
# FIXME: don't call into logging here
1593
handler = logging.StreamHandler(stderr)
1594
handler.setLevel(logging.INFO)
1595
logger = logging.getLogger('')
1596
logger.addHandler(handler)
1597
old_ui_factory = ui.ui_factory
1598
ui.ui_factory = TestUIFactory(stdin=stdin, stdout=stdout, stderr=stderr)
1601
if working_dir is not None:
1602
cwd = osutils.getcwd()
1603
os.chdir(working_dir)
1606
result = self.apply_redirected(ui.ui_factory.stdin,
1608
bzrlib.commands.run_bzr_catch_user_errors,
1611
logger.removeHandler(handler)
1612
ui.ui_factory = old_ui_factory
1616
out = stdout.getvalue()
1617
err = stderr.getvalue()
1619
self.log('output:\n%r', out)
1621
self.log('errors:\n%r', err)
1622
if retcode is not None:
1623
self.assertEquals(retcode, result,
1624
message='Unexpected return code')
1627
def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
1628
working_dir=None, error_regexes=[], output_encoding=None):
1629
"""Invoke bzr, as if it were run from the command line.
1631
The argument list should not include the bzr program name - the
1632
first argument is normally the bzr command. Arguments may be
1633
passed in three ways:
1635
1- A list of strings, eg ["commit", "a"]. This is recommended
1636
when the command contains whitespace or metacharacters, or
1637
is built up at run time.
1639
2- A single string, eg "add a". This is the most convenient
1640
for hardcoded commands.
1642
This runs bzr through the interface that catches and reports
1643
errors, and with logging set to something approximating the
1644
default, so that error reporting can be checked.
1646
This should be the main method for tests that want to exercise the
1647
overall behavior of the bzr application (rather than a unit test
1648
or a functional test of the library.)
1650
This sends the stdout/stderr results into the test's log,
1651
where it may be useful for debugging. See also run_captured.
1653
:keyword stdin: A string to be used as stdin for the command.
1654
:keyword retcode: The status code the command should return;
1656
:keyword working_dir: The directory to run the command in
1657
:keyword error_regexes: A list of expected error messages. If
1658
specified they must be seen in the error output of the command.
1660
out, err = self._run_bzr_autosplit(
1665
working_dir=working_dir,
1667
self.assertIsInstance(error_regexes, (list, tuple))
1668
for regex in error_regexes:
1669
self.assertContainsRe(err, regex)
1672
def run_bzr_error(self, error_regexes, *args, **kwargs):
1673
"""Run bzr, and check that stderr contains the supplied regexes
1675
:param error_regexes: Sequence of regular expressions which
1676
must each be found in the error output. The relative ordering
1678
:param args: command-line arguments for bzr
1679
:param kwargs: Keyword arguments which are interpreted by run_bzr
1680
This function changes the default value of retcode to be 3,
1681
since in most cases this is run when you expect bzr to fail.
1683
:return: (out, err) The actual output of running the command (in case
1684
you want to do more inspection)
1688
# Make sure that commit is failing because there is nothing to do
1689
self.run_bzr_error(['no changes to commit'],
1690
['commit', '-m', 'my commit comment'])
1691
# Make sure --strict is handling an unknown file, rather than
1692
# giving us the 'nothing to do' error
1693
self.build_tree(['unknown'])
1694
self.run_bzr_error(['Commit refused because there are unknown files'],
1695
['commit', --strict', '-m', 'my commit comment'])
1697
kwargs.setdefault('retcode', 3)
1698
kwargs['error_regexes'] = error_regexes
1699
out, err = self.run_bzr(*args, **kwargs)
1702
def run_bzr_subprocess(self, *args, **kwargs):
1703
"""Run bzr in a subprocess for testing.
1705
This starts a new Python interpreter and runs bzr in there.
1706
This should only be used for tests that have a justifiable need for
1707
this isolation: e.g. they are testing startup time, or signal
1708
handling, or early startup code, etc. Subprocess code can't be
1709
profiled or debugged so easily.
1711
:keyword retcode: The status code that is expected. Defaults to 0. If
1712
None is supplied, the status code is not checked.
1713
:keyword env_changes: A dictionary which lists changes to environment
1714
variables. A value of None will unset the env variable.
1715
The values must be strings. The change will only occur in the
1716
child, so you don't need to fix the environment after running.
1717
:keyword universal_newlines: Convert CRLF => LF
1718
:keyword allow_plugins: By default the subprocess is run with
1719
--no-plugins to ensure test reproducibility. Also, it is possible
1720
for system-wide plugins to create unexpected output on stderr,
1721
which can cause unnecessary test failures.
1723
env_changes = kwargs.get('env_changes', {})
1724
working_dir = kwargs.get('working_dir', None)
1725
allow_plugins = kwargs.get('allow_plugins', False)
1727
if isinstance(args[0], list):
1729
elif isinstance(args[0], basestring):
1730
args = list(shlex.split(args[0]))
1732
raise ValueError("passing varargs to run_bzr_subprocess")
1733
process = self.start_bzr_subprocess(args, env_changes=env_changes,
1734
working_dir=working_dir,
1735
allow_plugins=allow_plugins)
1736
# We distinguish between retcode=None and retcode not passed.
1737
supplied_retcode = kwargs.get('retcode', 0)
1738
return self.finish_bzr_subprocess(process, retcode=supplied_retcode,
1739
universal_newlines=kwargs.get('universal_newlines', False),
1742
def start_bzr_subprocess(self, process_args, env_changes=None,
1743
skip_if_plan_to_signal=False,
1745
allow_plugins=False):
1746
"""Start bzr in a subprocess for testing.
1748
This starts a new Python interpreter and runs bzr in there.
1749
This should only be used for tests that have a justifiable need for
1750
this isolation: e.g. they are testing startup time, or signal
1751
handling, or early startup code, etc. Subprocess code can't be
1752
profiled or debugged so easily.
1754
:param process_args: a list of arguments to pass to the bzr executable,
1755
for example ``['--version']``.
1756
:param env_changes: A dictionary which lists changes to environment
1757
variables. A value of None will unset the env variable.
1758
The values must be strings. The change will only occur in the
1759
child, so you don't need to fix the environment after running.
1760
:param skip_if_plan_to_signal: raise TestSkipped when true and os.kill
1762
:param allow_plugins: If False (default) pass --no-plugins to bzr.
1764
:returns: Popen object for the started process.
1766
if skip_if_plan_to_signal:
1767
if not getattr(os, 'kill', None):
1768
raise TestSkipped("os.kill not available.")
1770
if env_changes is None:
1774
def cleanup_environment():
1775
for env_var, value in env_changes.iteritems():
1776
old_env[env_var] = osutils.set_or_unset_env(env_var, value)
1778
def restore_environment():
1779
for env_var, value in old_env.iteritems():
1780
osutils.set_or_unset_env(env_var, value)
1782
bzr_path = self.get_bzr_path()
1785
if working_dir is not None:
1786
cwd = osutils.getcwd()
1787
os.chdir(working_dir)
1790
# win32 subprocess doesn't support preexec_fn
1791
# so we will avoid using it on all platforms, just to
1792
# make sure the code path is used, and we don't break on win32
1793
cleanup_environment()
1794
command = [sys.executable]
1795
# frozen executables don't need the path to bzr
1796
if getattr(sys, "frozen", None) is None:
1797
command.append(bzr_path)
1798
if not allow_plugins:
1799
command.append('--no-plugins')
1800
command.extend(process_args)
1801
process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
1803
restore_environment()
1809
def _popen(self, *args, **kwargs):
1810
"""Place a call to Popen.
1812
Allows tests to override this method to intercept the calls made to
1813
Popen for introspection.
1815
return Popen(*args, **kwargs)
1817
def get_bzr_path(self):
1818
"""Return the path of the 'bzr' executable for this test suite."""
1819
bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
1820
if not os.path.isfile(bzr_path):
1821
# We are probably installed. Assume sys.argv is the right file
1822
bzr_path = sys.argv[0]
1825
def finish_bzr_subprocess(self, process, retcode=0, send_signal=None,
1826
universal_newlines=False, process_args=None):
1827
"""Finish the execution of process.
1829
:param process: the Popen object returned from start_bzr_subprocess.
1830
:param retcode: The status code that is expected. Defaults to 0. If
1831
None is supplied, the status code is not checked.
1832
:param send_signal: an optional signal to send to the process.
1833
:param universal_newlines: Convert CRLF => LF
1834
:returns: (stdout, stderr)
1836
if send_signal is not None:
1837
os.kill(process.pid, send_signal)
1838
out, err = process.communicate()
1840
if universal_newlines:
1841
out = out.replace('\r\n', '\n')
1842
err = err.replace('\r\n', '\n')
1844
if retcode is not None and retcode != process.returncode:
1845
if process_args is None:
1846
process_args = "(unknown args)"
1847
mutter('Output of bzr %s:\n%s', process_args, out)
1848
mutter('Error for bzr %s:\n%s', process_args, err)
1849
self.fail('Command bzr %s failed with retcode %s != %s'
1850
% (process_args, retcode, process.returncode))
1853
def check_inventory_shape(self, inv, shape):
1854
"""Compare an inventory to a list of expected names.
1856
Fail if they are not precisely equal.
1859
shape = list(shape) # copy
1860
for path, ie in inv.entries():
1861
name = path.replace('\\', '/')
1862
if ie.kind == 'directory':
1869
self.fail("expected paths not found in inventory: %r" % shape)
1871
self.fail("unexpected paths found in inventory: %r" % extras)
1873
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
1874
a_callable=None, *args, **kwargs):
1875
"""Call callable with redirected std io pipes.
1877
Returns the return code."""
1878
if not callable(a_callable):
1879
raise ValueError("a_callable must be callable.")
1881
stdin = StringIO("")
1883
if getattr(self, "_log_file", None) is not None:
1884
stdout = self._log_file
1888
if getattr(self, "_log_file", None is not None):
1889
stderr = self._log_file
1892
real_stdin = sys.stdin
1893
real_stdout = sys.stdout
1894
real_stderr = sys.stderr
1899
return a_callable(*args, **kwargs)
1901
sys.stdout = real_stdout
1902
sys.stderr = real_stderr
1903
sys.stdin = real_stdin
1905
def reduceLockdirTimeout(self):
1906
"""Reduce the default lock timeout for the duration of the test, so that
1907
if LockContention occurs during a test, it does so quickly.
1909
Tests that expect to provoke LockContention errors should call this.
1911
orig_timeout = bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS
1913
bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = orig_timeout
1914
self.addCleanup(resetTimeout)
1915
bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = 0
1917
def make_utf8_encoded_stringio(self, encoding_type=None):
1918
"""Return a StringIOWrapper instance, that will encode Unicode
1921
if encoding_type is None:
1922
encoding_type = 'strict'
1924
output_encoding = 'utf-8'
1925
sio = codecs.getwriter(output_encoding)(sio, errors=encoding_type)
1926
sio.encoding = output_encoding
1930
class CapturedCall(object):
1931
"""A helper for capturing smart server calls for easy debug analysis."""
1933
def __init__(self, params, prefix_length):
1934
"""Capture the call with params and skip prefix_length stack frames."""
1937
# The last 5 frames are the __init__, the hook frame, and 3 smart
1938
# client frames. Beyond this we could get more clever, but this is good
1940
stack = traceback.extract_stack()[prefix_length:-5]
1941
self.stack = ''.join(traceback.format_list(stack))
1944
return self.call.method
1947
return self.call.method
1953
class TestCaseWithMemoryTransport(TestCase):
1954
"""Common test class for tests that do not need disk resources.
1956
Tests that need disk resources should derive from TestCaseWithTransport.
1958
TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
1960
For TestCaseWithMemoryTransport the test_home_dir is set to the name of
1961
a directory which does not exist. This serves to help ensure test isolation
1962
is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
1963
must exist. However, TestCaseWithMemoryTransport does not offer local
1964
file defaults for the transport in tests, nor does it obey the command line
1965
override, so tests that accidentally write to the common directory should
1968
:cvar TEST_ROOT: Directory containing all temporary directories, plus
1969
a .bzr directory that stops us ascending higher into the filesystem.
1975
def __init__(self, methodName='runTest'):
1976
# allow test parameterization after test construction and before test
1977
# execution. Variables that the parameterizer sets need to be
1978
# ones that are not set by setUp, or setUp will trash them.
1979
super(TestCaseWithMemoryTransport, self).__init__(methodName)
1980
self.vfs_transport_factory = default_transport
1981
self.transport_server = None
1982
self.transport_readonly_server = None
1983
self.__vfs_server = None
1985
def get_transport(self, relpath=None):
1986
"""Return a writeable transport.
1988
This transport is for the test scratch space relative to
1991
:param relpath: a path relative to the base url.
1993
t = get_transport(self.get_url(relpath))
1994
self.assertFalse(t.is_readonly())
1997
def get_readonly_transport(self, relpath=None):
1998
"""Return a readonly transport for the test scratch space
2000
This can be used to test that operations which should only need
2001
readonly access in fact do not try to write.
2003
:param relpath: a path relative to the base url.
2005
t = get_transport(self.get_readonly_url(relpath))
2006
self.assertTrue(t.is_readonly())
2009
def create_transport_readonly_server(self):
2010
"""Create a transport server from class defined at init.
2012
This is mostly a hook for daughter classes.
2014
return self.transport_readonly_server()
2016
def get_readonly_server(self):
2017
"""Get the server instance for the readonly transport
2019
This is useful for some tests with specific servers to do diagnostics.
2021
if self.__readonly_server is None:
2022
if self.transport_readonly_server is None:
2023
# readonly decorator requested
2024
# bring up the server
2025
self.__readonly_server = ReadonlyServer()
2026
self.__readonly_server.setUp(self.get_vfs_only_server())
2028
self.__readonly_server = self.create_transport_readonly_server()
2029
self.__readonly_server.setUp(self.get_vfs_only_server())
2030
self.addCleanup(self.__readonly_server.tearDown)
2031
return self.__readonly_server
2033
def get_readonly_url(self, relpath=None):
2034
"""Get a URL for the readonly transport.
2036
This will either be backed by '.' or a decorator to the transport
2037
used by self.get_url()
2038
relpath provides for clients to get a path relative to the base url.
2039
These should only be downwards relative, not upwards.
2041
base = self.get_readonly_server().get_url()
2042
return self._adjust_url(base, relpath)
2044
def get_vfs_only_server(self):
2045
"""Get the vfs only read/write server instance.
2047
This is useful for some tests with specific servers that need
2050
For TestCaseWithMemoryTransport this is always a MemoryServer, and there
2051
is no means to override it.
2053
if self.__vfs_server is None:
2054
self.__vfs_server = MemoryServer()
2055
self.__vfs_server.setUp()
2056
self.addCleanup(self.__vfs_server.tearDown)
2057
return self.__vfs_server
2059
def get_server(self):
2060
"""Get the read/write server instance.
2062
This is useful for some tests with specific servers that need
2065
This is built from the self.transport_server factory. If that is None,
2066
then the self.get_vfs_server is returned.
2068
if self.__server is None:
2069
if self.transport_server is None or self.transport_server is self.vfs_transport_factory:
2070
return self.get_vfs_only_server()
2072
# bring up a decorated means of access to the vfs only server.
2073
self.__server = self.transport_server()
2075
self.__server.setUp(self.get_vfs_only_server())
2076
except TypeError, e:
2077
# This should never happen; the try:Except here is to assist
2078
# developers having to update code rather than seeing an
2079
# uninformative TypeError.
2080
raise Exception, "Old server API in use: %s, %s" % (self.__server, e)
2081
self.addCleanup(self.__server.tearDown)
2082
return self.__server
2084
def _adjust_url(self, base, relpath):
2085
"""Get a URL (or maybe a path) for the readwrite transport.
2087
This will either be backed by '.' or to an equivalent non-file based
2089
relpath provides for clients to get a path relative to the base url.
2090
These should only be downwards relative, not upwards.
2092
if relpath is not None and relpath != '.':
2093
if not base.endswith('/'):
2095
# XXX: Really base should be a url; we did after all call
2096
# get_url()! But sometimes it's just a path (from
2097
# LocalAbspathServer), and it'd be wrong to append urlescaped data
2098
# to a non-escaped local path.
2099
if base.startswith('./') or base.startswith('/'):
2102
base += urlutils.escape(relpath)
2105
def get_url(self, relpath=None):
2106
"""Get a URL (or maybe a path) for the readwrite transport.
2108
This will either be backed by '.' or to an equivalent non-file based
2110
relpath provides for clients to get a path relative to the base url.
2111
These should only be downwards relative, not upwards.
2113
base = self.get_server().get_url()
2114
return self._adjust_url(base, relpath)
2116
def get_vfs_only_url(self, relpath=None):
2117
"""Get a URL (or maybe a path for the plain old vfs transport.
2119
This will never be a smart protocol. It always has all the
2120
capabilities of the local filesystem, but it might actually be a
2121
MemoryTransport or some other similar virtual filesystem.
2123
This is the backing transport (if any) of the server returned by
2124
get_url and get_readonly_url.
2126
:param relpath: provides for clients to get a path relative to the base
2127
url. These should only be downwards relative, not upwards.
2130
base = self.get_vfs_only_server().get_url()
2131
return self._adjust_url(base, relpath)
2133
def _create_safety_net(self):
2134
"""Make a fake bzr directory.
2136
This prevents any tests propagating up onto the TEST_ROOT directory's
2139
root = TestCaseWithMemoryTransport.TEST_ROOT
2140
bzrdir.BzrDir.create_standalone_workingtree(root)
2142
def _check_safety_net(self):
2143
"""Check that the safety .bzr directory have not been touched.
2145
_make_test_root have created a .bzr directory to prevent tests from
2146
propagating. This method ensures than a test did not leaked.
2148
root = TestCaseWithMemoryTransport.TEST_ROOT
2149
wt = workingtree.WorkingTree.open(root)
2150
last_rev = wt.last_revision()
2151
if last_rev != 'null:':
2152
# The current test have modified the /bzr directory, we need to
2153
# recreate a new one or all the followng tests will fail.
2154
# If you need to inspect its content uncomment the following line
2155
# import pdb; pdb.set_trace()
2156
_rmtree_temp_dir(root + '/.bzr')
2157
self._create_safety_net()
2158
raise AssertionError('%s/.bzr should not be modified' % root)
2160
def _make_test_root(self):
2161
if TestCaseWithMemoryTransport.TEST_ROOT is None:
2162
root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
2163
TestCaseWithMemoryTransport.TEST_ROOT = root
2165
self._create_safety_net()
2167
# The same directory is used by all tests, and we're not
2168
# specifically told when all tests are finished. This will do.
2169
atexit.register(_rmtree_temp_dir, root)
2171
self.addCleanup(self._check_safety_net)
2173
def makeAndChdirToTestDir(self):
2174
"""Create a temporary directories for this one test.
2176
This must set self.test_home_dir and self.test_dir and chdir to
2179
For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this test.
2181
os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2182
self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
2183
self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
2185
def make_branch(self, relpath, format=None):
2186
"""Create a branch on the transport at relpath."""
2187
repo = self.make_repository(relpath, format=format)
2188
return repo.bzrdir.create_branch()
2190
def make_bzrdir(self, relpath, format=None):
2192
# might be a relative or absolute path
2193
maybe_a_url = self.get_url(relpath)
2194
segments = maybe_a_url.rsplit('/', 1)
2195
t = get_transport(maybe_a_url)
2196
if len(segments) > 1 and segments[-1] not in ('', '.'):
2200
if isinstance(format, basestring):
2201
format = bzrdir.format_registry.make_bzrdir(format)
2202
return format.initialize_on_transport(t)
2203
except errors.UninitializableFormat:
2204
raise TestSkipped("Format %s is not initializable." % format)
2206
def make_repository(self, relpath, shared=False, format=None):
2207
"""Create a repository on our default transport at relpath.
2209
Note that relpath must be a relative path, not a full url.
2211
# FIXME: If you create a remoterepository this returns the underlying
2212
# real format, which is incorrect. Actually we should make sure that
2213
# RemoteBzrDir returns a RemoteRepository.
2214
# maybe mbp 20070410
2215
made_control = self.make_bzrdir(relpath, format=format)
2216
return made_control.create_repository(shared=shared)
2218
def make_smart_server(self, path):
2219
smart_server = server.SmartTCPServer_for_testing()
2220
smart_server.setUp(self.get_server())
2221
remote_transport = get_transport(smart_server.get_url()).clone(path)
2222
self.addCleanup(smart_server.tearDown)
2223
return remote_transport
2225
def make_branch_and_memory_tree(self, relpath, format=None):
2226
"""Create a branch on the default transport and a MemoryTree for it."""
2227
b = self.make_branch(relpath, format=format)
2228
return memorytree.MemoryTree.create_on_branch(b)
2230
def make_branch_builder(self, relpath, format=None):
2231
branch = self.make_branch(relpath, format=format)
2232
return branchbuilder.BranchBuilder(branch=branch)
2234
def overrideEnvironmentForTesting(self):
2235
os.environ['HOME'] = self.test_home_dir
2236
os.environ['BZR_HOME'] = self.test_home_dir
2239
super(TestCaseWithMemoryTransport, self).setUp()
2240
self._make_test_root()
2241
_currentdir = os.getcwdu()
2242
def _leaveDirectory():
2243
os.chdir(_currentdir)
2244
self.addCleanup(_leaveDirectory)
2245
self.makeAndChdirToTestDir()
2246
self.overrideEnvironmentForTesting()
2247
self.__readonly_server = None
2248
self.__server = None
2249
self.reduceLockdirTimeout()
2251
def setup_smart_server_with_call_log(self):
2252
"""Sets up a smart server as the transport server with a call log."""
2253
self.transport_server = server.SmartTCPServer_for_testing
2254
self.hpss_calls = []
2256
# Skip the current stack down to the caller of
2257
# setup_smart_server_with_call_log
2258
prefix_length = len(traceback.extract_stack()) - 2
2259
def capture_hpss_call(params):
2260
self.hpss_calls.append(
2261
CapturedCall(params, prefix_length))
2262
client._SmartClient.hooks.install_named_hook(
2263
'call', capture_hpss_call, None)
2265
def reset_smart_call_log(self):
2266
self.hpss_calls = []
2269
class TestCaseInTempDir(TestCaseWithMemoryTransport):
2270
"""Derived class that runs a test within a temporary directory.
2272
This is useful for tests that need to create a branch, etc.
2274
The directory is created in a slightly complex way: for each
2275
Python invocation, a new temporary top-level directory is created.
2276
All test cases create their own directory within that. If the
2277
tests complete successfully, the directory is removed.
2279
:ivar test_base_dir: The path of the top-level directory for this
2280
test, which contains a home directory and a work directory.
2282
:ivar test_home_dir: An initially empty directory under test_base_dir
2283
which is used as $HOME for this test.
2285
:ivar test_dir: A directory under test_base_dir used as the current
2286
directory when the test proper is run.
2289
OVERRIDE_PYTHON = 'python'
2291
def check_file_contents(self, filename, expect):
2292
self.log("check contents of file %s" % filename)
2293
contents = file(filename, 'r').read()
2294
if contents != expect:
2295
self.log("expected: %r" % expect)
2296
self.log("actually: %r" % contents)
2297
self.fail("contents of %s not as expected" % filename)
2299
def _getTestDirPrefix(self):
2300
# create a directory within the top level test directory
2301
if sys.platform == 'win32':
2302
name_prefix = re.sub('[<>*=+",:;_/\\-]', '_', self.id())
2303
# windows is likely to have path-length limits so use a short name
2304
name_prefix = name_prefix[-30:]
2306
name_prefix = re.sub('[/]', '_', self.id())
2309
def makeAndChdirToTestDir(self):
2310
"""See TestCaseWithMemoryTransport.makeAndChdirToTestDir().
2312
For TestCaseInTempDir we create a temporary directory based on the test
2313
name and then create two subdirs - test and home under it.
2315
name_prefix = osutils.pathjoin(TestCaseWithMemoryTransport.TEST_ROOT,
2316
self._getTestDirPrefix())
2318
for i in range(100):
2319
if os.path.exists(name):
2320
name = name_prefix + '_' + str(i)
2324
# now create test and home directories within this dir
2325
self.test_base_dir = name
2326
self.test_home_dir = self.test_base_dir + '/home'
2327
os.mkdir(self.test_home_dir)
2328
self.test_dir = self.test_base_dir + '/work'
2329
os.mkdir(self.test_dir)
2330
os.chdir(self.test_dir)
2331
# put name of test inside
2332
f = file(self.test_base_dir + '/name', 'w')
2337
self.addCleanup(self.deleteTestDir)
2339
def deleteTestDir(self):
2340
os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2341
_rmtree_temp_dir(self.test_base_dir)
2343
def build_tree(self, shape, line_endings='binary', transport=None):
2344
"""Build a test tree according to a pattern.
2346
shape is a sequence of file specifications. If the final
2347
character is '/', a directory is created.
2349
This assumes that all the elements in the tree being built are new.
2351
This doesn't add anything to a branch.
2353
:type shape: list or tuple.
2354
:param line_endings: Either 'binary' or 'native'
2355
in binary mode, exact contents are written in native mode, the
2356
line endings match the default platform endings.
2357
:param transport: A transport to write to, for building trees on VFS's.
2358
If the transport is readonly or None, "." is opened automatically.
2361
if type(shape) not in (list, tuple):
2362
raise AssertionError("Parameter 'shape' should be "
2363
"a list or a tuple. Got %r instead" % (shape,))
2364
# It's OK to just create them using forward slashes on windows.
2365
if transport is None or transport.is_readonly():
2366
transport = get_transport(".")
2368
self.assertIsInstance(name, basestring)
2370
transport.mkdir(urlutils.escape(name[:-1]))
2372
if line_endings == 'binary':
2374
elif line_endings == 'native':
2377
raise errors.BzrError(
2378
'Invalid line ending request %r' % line_endings)
2379
content = "contents of %s%s" % (name.encode('utf-8'), end)
2380
transport.put_bytes_non_atomic(urlutils.escape(name), content)
2382
def build_tree_contents(self, shape):
2383
build_tree_contents(shape)
2385
def assertInWorkingTree(self, path, root_path='.', tree=None):
2386
"""Assert whether path or paths are in the WorkingTree"""
2388
tree = workingtree.WorkingTree.open(root_path)
2389
if not isinstance(path, basestring):
2391
self.assertInWorkingTree(p, tree=tree)
2393
self.assertIsNot(tree.path2id(path), None,
2394
path+' not in working tree.')
2396
def assertNotInWorkingTree(self, path, root_path='.', tree=None):
2397
"""Assert whether path or paths are not in the WorkingTree"""
2399
tree = workingtree.WorkingTree.open(root_path)
2400
if not isinstance(path, basestring):
2402
self.assertNotInWorkingTree(p,tree=tree)
2404
self.assertIs(tree.path2id(path), None, path+' in working tree.')
2407
class TestCaseWithTransport(TestCaseInTempDir):
2408
"""A test case that provides get_url and get_readonly_url facilities.
2410
These back onto two transport servers, one for readonly access and one for
2413
If no explicit class is provided for readonly access, a
2414
ReadonlyTransportDecorator is used instead which allows the use of non disk
2415
based read write transports.
2417
If an explicit class is provided for readonly access, that server and the
2418
readwrite one must both define get_url() as resolving to os.getcwd().
2421
def get_vfs_only_server(self):
2422
"""See TestCaseWithMemoryTransport.
2424
This is useful for some tests with specific servers that need
2427
if self.__vfs_server is None:
2428
self.__vfs_server = self.vfs_transport_factory()
2429
self.__vfs_server.setUp()
2430
self.addCleanup(self.__vfs_server.tearDown)
2431
return self.__vfs_server
2433
def make_branch_and_tree(self, relpath, format=None):
2434
"""Create a branch on the transport and a tree locally.
2436
If the transport is not a LocalTransport, the Tree can't be created on
2437
the transport. In that case if the vfs_transport_factory is
2438
LocalURLServer the working tree is created in the local
2439
directory backing the transport, and the returned tree's branch and
2440
repository will also be accessed locally. Otherwise a lightweight
2441
checkout is created and returned.
2443
:param format: The BzrDirFormat.
2444
:returns: the WorkingTree.
2446
# TODO: always use the local disk path for the working tree,
2447
# this obviously requires a format that supports branch references
2448
# so check for that by checking bzrdir.BzrDirFormat.get_default_format()
2450
b = self.make_branch(relpath, format=format)
2452
return b.bzrdir.create_workingtree()
2453
except errors.NotLocalUrl:
2454
# We can only make working trees locally at the moment. If the
2455
# transport can't support them, then we keep the non-disk-backed
2456
# branch and create a local checkout.
2457
if self.vfs_transport_factory is LocalURLServer:
2458
# the branch is colocated on disk, we cannot create a checkout.
2459
# hopefully callers will expect this.
2460
local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
2461
wt = local_controldir.create_workingtree()
2462
if wt.branch._format != b._format:
2464
# Make sure that assigning to wt._branch fixes wt.branch,
2465
# in case the implementation details of workingtree objects
2467
self.assertIs(b, wt.branch)
2470
return b.create_checkout(relpath, lightweight=True)
2472
def assertIsDirectory(self, relpath, transport):
2473
"""Assert that relpath within transport is a directory.
2475
This may not be possible on all transports; in that case it propagates
2476
a TransportNotPossible.
2479
mode = transport.stat(relpath).st_mode
2480
except errors.NoSuchFile:
2481
self.fail("path %s is not a directory; no such file"
2483
if not stat.S_ISDIR(mode):
2484
self.fail("path %s is not a directory; has mode %#o"
2487
def assertTreesEqual(self, left, right):
2488
"""Check that left and right have the same content and properties."""
2489
# we use a tree delta to check for equality of the content, and we
2490
# manually check for equality of other things such as the parents list.
2491
self.assertEqual(left.get_parent_ids(), right.get_parent_ids())
2492
differences = left.changes_from(right)
2493
self.assertFalse(differences.has_changed(),
2494
"Trees %r and %r are different: %r" % (left, right, differences))
2497
super(TestCaseWithTransport, self).setUp()
2498
self.__vfs_server = None
2501
class ChrootedTestCase(TestCaseWithTransport):
2502
"""A support class that provides readonly urls outside the local namespace.
2504
This is done by checking if self.transport_server is a MemoryServer. if it
2505
is then we are chrooted already, if it is not then an HttpServer is used
2508
TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
2509
be used without needed to redo it when a different
2510
subclass is in use ?
2514
super(ChrootedTestCase, self).setUp()
2515
if not self.vfs_transport_factory == MemoryServer:
2516
self.transport_readonly_server = HttpServer
2519
def condition_id_re(pattern):
2520
"""Create a condition filter which performs a re check on a test's id.
2522
:param pattern: A regular expression string.
2523
:return: A callable that returns True if the re matches.
2525
filter_re = osutils.re_compile_checked(pattern, 0,
2527
def condition(test):
2529
return filter_re.search(test_id)
2533
def condition_isinstance(klass_or_klass_list):
2534
"""Create a condition filter which returns isinstance(param, klass).
2536
:return: A callable which when called with one parameter obj return the
2537
result of isinstance(obj, klass_or_klass_list).
2540
return isinstance(obj, klass_or_klass_list)
2544
def condition_id_in_list(id_list):
2545
"""Create a condition filter which verify that test's id in a list.
2547
:param id_list: A TestIdList object.
2548
:return: A callable that returns True if the test's id appears in the list.
2550
def condition(test):
2551
return id_list.includes(test.id())
2555
def condition_id_startswith(starts):
2556
"""Create a condition filter verifying that test's id starts with a string.
2558
:param starts: A list of string.
2559
:return: A callable that returns True if the test's id starts with one of
2562
def condition(test):
2563
for start in starts:
2564
if test.id().startswith(start):
2570
def exclude_tests_by_condition(suite, condition):
2571
"""Create a test suite which excludes some tests from suite.
2573
:param suite: The suite to get tests from.
2574
:param condition: A callable whose result evaluates True when called with a
2575
test case which should be excluded from the result.
2576
:return: A suite which contains the tests found in suite that fail
2580
for test in iter_suite_tests(suite):
2581
if not condition(test):
2583
return TestUtil.TestSuite(result)
2586
def filter_suite_by_condition(suite, condition):
2587
"""Create a test suite by filtering another one.
2589
:param suite: The source suite.
2590
:param condition: A callable whose result evaluates True when called with a
2591
test case which should be included in the result.
2592
:return: A suite which contains the tests found in suite that pass
2596
for test in iter_suite_tests(suite):
2599
return TestUtil.TestSuite(result)
2602
def filter_suite_by_re(suite, pattern):
2603
"""Create a test suite by filtering another one.
2605
:param suite: the source suite
2606
:param pattern: pattern that names must match
2607
:returns: the newly created suite
2609
condition = condition_id_re(pattern)
2610
result_suite = filter_suite_by_condition(suite, condition)
2614
def filter_suite_by_id_list(suite, test_id_list):
2615
"""Create a test suite by filtering another one.
2617
:param suite: The source suite.
2618
:param test_id_list: A list of the test ids to keep as strings.
2619
:returns: the newly created suite
2621
condition = condition_id_in_list(test_id_list)
2622
result_suite = filter_suite_by_condition(suite, condition)
2626
def filter_suite_by_id_startswith(suite, start):
2627
"""Create a test suite by filtering another one.
2629
:param suite: The source suite.
2630
:param start: A list of string the test id must start with one of.
2631
:returns: the newly created suite
2633
condition = condition_id_startswith(start)
2634
result_suite = filter_suite_by_condition(suite, condition)
2638
def exclude_tests_by_re(suite, pattern):
2639
"""Create a test suite which excludes some tests from suite.
2641
:param suite: The suite to get tests from.
2642
:param pattern: A regular expression string. Test ids that match this
2643
pattern will be excluded from the result.
2644
:return: A TestSuite that contains all the tests from suite without the
2645
tests that matched pattern. The order of tests is the same as it was in
2648
return exclude_tests_by_condition(suite, condition_id_re(pattern))
2651
def preserve_input(something):
2652
"""A helper for performing test suite transformation chains.
2654
:param something: Anything you want to preserve.
2660
def randomize_suite(suite):
2661
"""Return a new TestSuite with suite's tests in random order.
2663
The tests in the input suite are flattened into a single suite in order to
2664
accomplish this. Any nested TestSuites are removed to provide global
2667
tests = list(iter_suite_tests(suite))
2668
random.shuffle(tests)
2669
return TestUtil.TestSuite(tests)
2672
def split_suite_by_condition(suite, condition):
2673
"""Split a test suite into two by a condition.
2675
:param suite: The suite to split.
2676
:param condition: The condition to match on. Tests that match this
2677
condition are returned in the first test suite, ones that do not match
2678
are in the second suite.
2679
:return: A tuple of two test suites, where the first contains tests from
2680
suite matching the condition, and the second contains the remainder
2681
from suite. The order within each output suite is the same as it was in
2686
for test in iter_suite_tests(suite):
2688
matched.append(test)
2690
did_not_match.append(test)
2691
return TestUtil.TestSuite(matched), TestUtil.TestSuite(did_not_match)
2694
def split_suite_by_re(suite, pattern):
2695
"""Split a test suite into two by a regular expression.
2697
:param suite: The suite to split.
2698
:param pattern: A regular expression string. Test ids that match this
2699
pattern will be in the first test suite returned, and the others in the
2700
second test suite returned.
2701
:return: A tuple of two test suites, where the first contains tests from
2702
suite matching pattern, and the second contains the remainder from
2703
suite. The order within each output suite is the same as it was in
2706
return split_suite_by_condition(suite, condition_id_re(pattern))
2709
def run_suite(suite, name='test', verbose=False, pattern=".*",
2710
stop_on_failure=False,
2711
transport=None, lsprof_timed=None, bench_history=None,
2712
matching_tests_first=None,
2715
exclude_pattern=None,
2718
suite_decorators=None,
2720
"""Run a test suite for bzr selftest.
2722
:param runner_class: The class of runner to use. Must support the
2723
constructor arguments passed by run_suite which are more than standard
2725
:return: A boolean indicating success.
2727
TestCase._gather_lsprof_in_benchmarks = lsprof_timed
2732
if runner_class is None:
2733
runner_class = TextTestRunner
2736
runner = runner_class(stream=stream,
2738
verbosity=verbosity,
2739
bench_history=bench_history,
2740
list_only=list_only,
2743
runner.stop_on_failure=stop_on_failure
2744
# built in decorator factories:
2746
random_order(random_seed, runner),
2747
exclude_tests(exclude_pattern),
2749
if matching_tests_first:
2750
decorators.append(tests_first(pattern))
2752
decorators.append(filter_tests(pattern))
2753
if suite_decorators:
2754
decorators.extend(suite_decorators)
2755
for decorator in decorators:
2756
suite = decorator(suite)
2757
result = runner.run(suite)
2762
return result.wasStrictlySuccessful()
2764
return result.wasSuccessful()
2767
# A registry where get() returns a suite decorator.
2768
parallel_registry = registry.Registry()
2771
def fork_decorator(suite):
2772
concurrency = osutils.local_concurrency()
2773
if concurrency == 1:
2775
from testtools import ConcurrentTestSuite
2776
return ConcurrentTestSuite(suite, fork_for_tests)
2777
parallel_registry.register('fork', fork_decorator)
2780
def subprocess_decorator(suite):
2781
concurrency = osutils.local_concurrency()
2782
if concurrency == 1:
2784
from testtools import ConcurrentTestSuite
2785
return ConcurrentTestSuite(suite, reinvoke_for_tests)
2786
parallel_registry.register('subprocess', subprocess_decorator)
2789
def exclude_tests(exclude_pattern):
2790
"""Return a test suite decorator that excludes tests."""
2791
if exclude_pattern is None:
2792
return identity_decorator
2793
def decorator(suite):
2794
return ExcludeDecorator(suite, exclude_pattern)
2798
def filter_tests(pattern):
2800
return identity_decorator
2801
def decorator(suite):
2802
return FilterTestsDecorator(suite, pattern)
2806
def random_order(random_seed, runner):
2807
"""Return a test suite decorator factory for randomising tests order.
2809
:param random_seed: now, a string which casts to a long, or a long.
2810
:param runner: A test runner with a stream attribute to report on.
2812
if random_seed is None:
2813
return identity_decorator
2814
def decorator(suite):
2815
return RandomDecorator(suite, random_seed, runner.stream)
2819
def tests_first(pattern):
2821
return identity_decorator
2822
def decorator(suite):
2823
return TestFirstDecorator(suite, pattern)
2827
def identity_decorator(suite):
2832
class TestDecorator(TestSuite):
2833
"""A decorator for TestCase/TestSuite objects.
2835
Usually, subclasses should override __iter__(used when flattening test
2836
suites), which we do to filter, reorder, parallelise and so on, run() and
2840
def __init__(self, suite):
2841
TestSuite.__init__(self)
2844
def countTestCases(self):
2847
cases += test.countTestCases()
2854
def run(self, result):
2855
# Use iteration on self, not self._tests, to allow subclasses to hook
2858
if result.shouldStop:
2864
class ExcludeDecorator(TestDecorator):
2865
"""A decorator which excludes test matching an exclude pattern."""
2867
def __init__(self, suite, exclude_pattern):
2868
TestDecorator.__init__(self, suite)
2869
self.exclude_pattern = exclude_pattern
2870
self.excluded = False
2874
return iter(self._tests)
2875
self.excluded = True
2876
suite = exclude_tests_by_re(self, self.exclude_pattern)
2878
self.addTests(suite)
2879
return iter(self._tests)
2882
class FilterTestsDecorator(TestDecorator):
2883
"""A decorator which filters tests to those matching a pattern."""
2885
def __init__(self, suite, pattern):
2886
TestDecorator.__init__(self, suite)
2887
self.pattern = pattern
2888
self.filtered = False
2892
return iter(self._tests)
2893
self.filtered = True
2894
suite = filter_suite_by_re(self, self.pattern)
2896
self.addTests(suite)
2897
return iter(self._tests)
2900
class RandomDecorator(TestDecorator):
2901
"""A decorator which randomises the order of its tests."""
2903
def __init__(self, suite, random_seed, stream):
2904
TestDecorator.__init__(self, suite)
2905
self.random_seed = random_seed
2906
self.randomised = False
2907
self.stream = stream
2911
return iter(self._tests)
2912
self.randomised = True
2913
self.stream.writeln("Randomizing test order using seed %s\n" %
2914
(self.actual_seed()))
2915
# Initialise the random number generator.
2916
random.seed(self.actual_seed())
2917
suite = randomize_suite(self)
2919
self.addTests(suite)
2920
return iter(self._tests)
2922
def actual_seed(self):
2923
if self.random_seed == "now":
2924
# We convert the seed to a long to make it reuseable across
2925
# invocations (because the user can reenter it).
2926
self.random_seed = long(time.time())
2928
# Convert the seed to a long if we can
2930
self.random_seed = long(self.random_seed)
2933
return self.random_seed
2936
class TestFirstDecorator(TestDecorator):
2937
"""A decorator which moves named tests to the front."""
2939
def __init__(self, suite, pattern):
2940
TestDecorator.__init__(self, suite)
2941
self.pattern = pattern
2942
self.filtered = False
2946
return iter(self._tests)
2947
self.filtered = True
2948
suites = split_suite_by_re(self, self.pattern)
2950
self.addTests(suites)
2951
return iter(self._tests)
2954
def partition_tests(suite, count):
2955
"""Partition suite into count lists of tests."""
2957
tests = list(iter_suite_tests(suite))
2958
tests_per_process = int(math.ceil(float(len(tests)) / count))
2959
for block in range(count):
2960
low_test = block * tests_per_process
2961
high_test = low_test + tests_per_process
2962
process_tests = tests[low_test:high_test]
2963
result.append(process_tests)
2967
def fork_for_tests(suite):
2968
"""Take suite and start up one runner per CPU by forking()
2970
:return: An iterable of TestCase-like objects which can each have
2971
run(result) called on them to feed tests to result.
2973
concurrency = osutils.local_concurrency()
2975
from subunit import TestProtocolClient, ProtocolTestCase
2976
class TestInOtherProcess(ProtocolTestCase):
2977
# Should be in subunit, I think. RBC.
2978
def __init__(self, stream, pid):
2979
ProtocolTestCase.__init__(self, stream)
2982
def run(self, result):
2984
ProtocolTestCase.run(self, result)
2986
os.waitpid(self.pid, os.WNOHANG)
2988
test_blocks = partition_tests(suite, concurrency)
2989
for process_tests in test_blocks:
2990
process_suite = TestSuite()
2991
process_suite.addTests(process_tests)
2992
c2pread, c2pwrite = os.pipe()
2997
# Leave stderr and stdout open so we can see test noise
2998
# Close stdin so that the child goes away if it decides to
2999
# read from stdin (otherwise its a roulette to see what
3000
# child actually gets keystrokes for pdb etc).
3003
stream = os.fdopen(c2pwrite, 'wb', 1)
3004
subunit_result = TestProtocolClient(stream)
3005
process_suite.run(subunit_result)
3010
stream = os.fdopen(c2pread, 'rb', 1)
3011
test = TestInOtherProcess(stream, pid)
3016
def reinvoke_for_tests(suite):
3017
"""Take suite and start up one runner per CPU using subprocess().
3019
:return: An iterable of TestCase-like objects which can each have
3020
run(result) called on them to feed tests to result.
3022
concurrency = osutils.local_concurrency()
3024
from subunit import ProtocolTestCase
3025
class TestInSubprocess(ProtocolTestCase):
3026
def __init__(self, process, name):
3027
ProtocolTestCase.__init__(self, process.stdout)
3028
self.process = process
3029
self.process.stdin.close()
3032
def run(self, result):
3034
ProtocolTestCase.run(self, result)
3037
os.unlink(self.name)
3038
# print "pid %d finished" % finished_process
3039
test_blocks = partition_tests(suite, concurrency)
3040
for process_tests in test_blocks:
3041
# ugly; currently reimplement rather than reuses TestCase methods.
3042
bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
3043
if not os.path.isfile(bzr_path):
3044
# We are probably installed. Assume sys.argv is the right file
3045
bzr_path = sys.argv[0]
3046
fd, test_list_file_name = tempfile.mkstemp()
3047
test_list_file = os.fdopen(fd, 'wb', 1)
3048
for test in process_tests:
3049
test_list_file.write(test.id() + '\n')
3050
test_list_file.close()
3052
argv = [bzr_path, 'selftest', '--load-list', test_list_file_name,
3054
if '--no-plugins' in sys.argv:
3055
argv.append('--no-plugins')
3056
# stderr=STDOUT would be ideal, but until we prevent noise on
3057
# stderr it can interrupt the subunit protocol.
3058
process = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE,
3060
test = TestInSubprocess(process, test_list_file_name)
3063
os.unlink(test_list_file_name)
3068
class BZRTransformingResult(unittest.TestResult):
3070
def __init__(self, target):
3071
unittest.TestResult.__init__(self)
3072
self.result = target
3074
def startTest(self, test):
3075
self.result.startTest(test)
3077
def stopTest(self, test):
3078
self.result.stopTest(test)
3080
def addError(self, test, err):
3081
feature = self._error_looks_like('UnavailableFeature: ', err)
3082
if feature is not None:
3083
self.result.addNotSupported(test, feature)
3085
self.result.addError(test, err)
3087
def addFailure(self, test, err):
3088
known = self._error_looks_like('KnownFailure: ', err)
3089
if known is not None:
3090
self.result._addKnownFailure(test, [KnownFailure,
3091
KnownFailure(known), None])
3093
self.result.addFailure(test, err)
3095
def addSkip(self, test, reason):
3096
self.result.addSkip(test, reason)
3098
def addSuccess(self, test):
3099
self.result.addSuccess(test)
3101
def _error_looks_like(self, prefix, err):
3102
"""Deserialize exception and returns the stringify value."""
3106
if isinstance(exc, subunit.RemoteException):
3107
# stringify the exception gives access to the remote traceback
3108
# We search the last line for 'prefix'
3109
lines = str(exc).split('\n')
3110
while lines and not lines[-1]:
3113
if lines[-1].startswith(prefix):
3114
value = lines[-1][len(prefix):]
3118
# Controlled by "bzr selftest -E=..." option
3119
selftest_debug_flags = set()
3122
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
3124
test_suite_factory=None,
3127
matching_tests_first=None,
3130
exclude_pattern=None,
3136
suite_decorators=None,
3138
"""Run the whole test suite under the enhanced runner"""
3139
# XXX: Very ugly way to do this...
3140
# Disable warning about old formats because we don't want it to disturb
3141
# any blackbox tests.
3142
from bzrlib import repository
3143
repository._deprecation_warning_done = True
3145
global default_transport
3146
if transport is None:
3147
transport = default_transport
3148
old_transport = default_transport
3149
default_transport = transport
3150
global selftest_debug_flags
3151
old_debug_flags = selftest_debug_flags
3152
if debug_flags is not None:
3153
selftest_debug_flags = set(debug_flags)
3155
if load_list is None:
3158
keep_only = load_test_id_list(load_list)
3159
if test_suite_factory is None:
3160
suite = test_suite(keep_only, starting_with)
3162
suite = test_suite_factory()
3163
return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
3164
stop_on_failure=stop_on_failure,
3165
transport=transport,
3166
lsprof_timed=lsprof_timed,
3167
bench_history=bench_history,
3168
matching_tests_first=matching_tests_first,
3169
list_only=list_only,
3170
random_seed=random_seed,
3171
exclude_pattern=exclude_pattern,
3173
runner_class=runner_class,
3174
suite_decorators=suite_decorators,
3177
default_transport = old_transport
3178
selftest_debug_flags = old_debug_flags
3181
def load_test_id_list(file_name):
3182
"""Load a test id list from a text file.
3184
The format is one test id by line. No special care is taken to impose
3185
strict rules, these test ids are used to filter the test suite so a test id
3186
that do not match an existing test will do no harm. This allows user to add
3187
comments, leave blank lines, etc.
3191
ftest = open(file_name, 'rt')
3193
if e.errno != errno.ENOENT:
3196
raise errors.NoSuchFile(file_name)
3198
for test_name in ftest.readlines():
3199
test_list.append(test_name.strip())
3204
def suite_matches_id_list(test_suite, id_list):
3205
"""Warns about tests not appearing or appearing more than once.
3207
:param test_suite: A TestSuite object.
3208
:param test_id_list: The list of test ids that should be found in
3211
:return: (absents, duplicates) absents is a list containing the test found
3212
in id_list but not in test_suite, duplicates is a list containing the
3213
test found multiple times in test_suite.
3215
When using a prefined test id list, it may occurs that some tests do not
3216
exist anymore or that some tests use the same id. This function warns the
3217
tester about potential problems in his workflow (test lists are volatile)
3218
or in the test suite itself (using the same id for several tests does not
3219
help to localize defects).
3221
# Build a dict counting id occurrences
3223
for test in iter_suite_tests(test_suite):
3225
tests[id] = tests.get(id, 0) + 1
3230
occurs = tests.get(id, 0)
3232
not_found.append(id)
3234
duplicates.append(id)
3236
return not_found, duplicates
3239
class TestIdList(object):
3240
"""Test id list to filter a test suite.
3242
Relying on the assumption that test ids are built as:
3243
<module>[.<class>.<method>][(<param>+)], <module> being in python dotted
3244
notation, this class offers methods to :
3245
- avoid building a test suite for modules not refered to in the test list,
3246
- keep only the tests listed from the module test suite.
3249
def __init__(self, test_id_list):
3250
# When a test suite needs to be filtered against us we compare test ids
3251
# for equality, so a simple dict offers a quick and simple solution.
3252
self.tests = dict().fromkeys(test_id_list, True)
3254
# While unittest.TestCase have ids like:
3255
# <module>.<class>.<method>[(<param+)],
3256
# doctest.DocTestCase can have ids like:
3259
# <module>.<function>
3260
# <module>.<class>.<method>
3262
# Since we can't predict a test class from its name only, we settle on
3263
# a simple constraint: a test id always begins with its module name.
3266
for test_id in test_id_list:
3267
parts = test_id.split('.')
3268
mod_name = parts.pop(0)
3269
modules[mod_name] = True
3271
mod_name += '.' + part
3272
modules[mod_name] = True
3273
self.modules = modules
3275
def refers_to(self, module_name):
3276
"""Is there tests for the module or one of its sub modules."""
3277
return self.modules.has_key(module_name)
3279
def includes(self, test_id):
3280
return self.tests.has_key(test_id)
3283
class TestPrefixAliasRegistry(registry.Registry):
3284
"""A registry for test prefix aliases.
3286
This helps implement shorcuts for the --starting-with selftest
3287
option. Overriding existing prefixes is not allowed but not fatal (a
3288
warning will be emitted).
3291
def register(self, key, obj, help=None, info=None,
3292
override_existing=False):
3293
"""See Registry.register.
3295
Trying to override an existing alias causes a warning to be emitted,
3296
not a fatal execption.
3299
super(TestPrefixAliasRegistry, self).register(
3300
key, obj, help=help, info=info, override_existing=False)
3302
actual = self.get(key)
3303
note('Test prefix alias %s is already used for %s, ignoring %s'
3304
% (key, actual, obj))
3306
def resolve_alias(self, id_start):
3307
"""Replace the alias by the prefix in the given string.
3309
Using an unknown prefix is an error to help catching typos.
3311
parts = id_start.split('.')
3313
parts[0] = self.get(parts[0])
3315
raise errors.BzrCommandError(
3316
'%s is not a known test prefix alias' % parts[0])
3317
return '.'.join(parts)
3320
test_prefix_alias_registry = TestPrefixAliasRegistry()
3321
"""Registry of test prefix aliases."""
3324
# This alias allows to detect typos ('bzrlin.') by making all valid test ids
3325
# appear prefixed ('bzrlib.' is "replaced" by 'bzrlib.').
3326
test_prefix_alias_registry.register('bzrlib', 'bzrlib')
3328
# Obvious higest levels prefixes, feel free to add your own via a plugin
3329
test_prefix_alias_registry.register('bd', 'bzrlib.doc')
3330
test_prefix_alias_registry.register('bu', 'bzrlib.utils')
3331
test_prefix_alias_registry.register('bt', 'bzrlib.tests')
3332
test_prefix_alias_registry.register('bb', 'bzrlib.tests.blackbox')
3333
test_prefix_alias_registry.register('bp', 'bzrlib.plugins')
3336
def test_suite(keep_only=None, starting_with=None):
3337
"""Build and return TestSuite for the whole of bzrlib.
3339
:param keep_only: A list of test ids limiting the suite returned.
3341
:param starting_with: An id limiting the suite returned to the tests
3344
This function can be replaced if you need to change the default test
3345
suite on a global basis, but it is not encouraged.
3349
'bzrlib.tests.blackbox',
3350
'bzrlib.tests.commands',
3351
'bzrlib.tests.per_branch',
3352
'bzrlib.tests.per_bzrdir',
3353
'bzrlib.tests.per_interrepository',
3354
'bzrlib.tests.per_intertree',
3355
'bzrlib.tests.per_inventory',
3356
'bzrlib.tests.per_interbranch',
3357
'bzrlib.tests.per_lock',
3358
'bzrlib.tests.per_transport',
3359
'bzrlib.tests.per_tree',
3360
'bzrlib.tests.per_repository',
3361
'bzrlib.tests.per_repository_chk',
3362
'bzrlib.tests.per_repository_reference',
3363
'bzrlib.tests.per_workingtree',
3364
'bzrlib.tests.test__annotator',
3365
'bzrlib.tests.test__chk_map',
3366
'bzrlib.tests.test__dirstate_helpers',
3367
'bzrlib.tests.test__groupcompress',
3368
'bzrlib.tests.test__known_graph',
3369
'bzrlib.tests.test__rio',
3370
'bzrlib.tests.test__walkdirs_win32',
3371
'bzrlib.tests.test_ancestry',
3372
'bzrlib.tests.test_annotate',
3373
'bzrlib.tests.test_api',
3374
'bzrlib.tests.test_atomicfile',
3375
'bzrlib.tests.test_bad_files',
3376
'bzrlib.tests.test_bencode',
3377
'bzrlib.tests.test_bisect_multi',
3378
'bzrlib.tests.test_branch',
3379
'bzrlib.tests.test_branchbuilder',
3380
'bzrlib.tests.test_btree_index',
3381
'bzrlib.tests.test_bugtracker',
3382
'bzrlib.tests.test_bundle',
3383
'bzrlib.tests.test_bzrdir',
3384
'bzrlib.tests.test__chunks_to_lines',
3385
'bzrlib.tests.test_cache_utf8',
3386
'bzrlib.tests.test_chk_map',
3387
'bzrlib.tests.test_chk_serializer',
3388
'bzrlib.tests.test_chunk_writer',
3389
'bzrlib.tests.test_clean_tree',
3390
'bzrlib.tests.test_commands',
3391
'bzrlib.tests.test_commit',
3392
'bzrlib.tests.test_commit_merge',
3393
'bzrlib.tests.test_config',
3394
'bzrlib.tests.test_conflicts',
3395
'bzrlib.tests.test_counted_lock',
3396
'bzrlib.tests.test_decorators',
3397
'bzrlib.tests.test_delta',
3398
'bzrlib.tests.test_debug',
3399
'bzrlib.tests.test_deprecated_graph',
3400
'bzrlib.tests.test_diff',
3401
'bzrlib.tests.test_directory_service',
3402
'bzrlib.tests.test_dirstate',
3403
'bzrlib.tests.test_email_message',
3404
'bzrlib.tests.test_eol_filters',
3405
'bzrlib.tests.test_errors',
3406
'bzrlib.tests.test_export',
3407
'bzrlib.tests.test_extract',
3408
'bzrlib.tests.test_fetch',
3409
'bzrlib.tests.test_fifo_cache',
3410
'bzrlib.tests.test_filters',
3411
'bzrlib.tests.test_ftp_transport',
3412
'bzrlib.tests.test_foreign',
3413
'bzrlib.tests.test_generate_docs',
3414
'bzrlib.tests.test_generate_ids',
3415
'bzrlib.tests.test_globbing',
3416
'bzrlib.tests.test_gpg',
3417
'bzrlib.tests.test_graph',
3418
'bzrlib.tests.test_groupcompress',
3419
'bzrlib.tests.test_hashcache',
3420
'bzrlib.tests.test_help',
3421
'bzrlib.tests.test_hooks',
3422
'bzrlib.tests.test_http',
3423
'bzrlib.tests.test_http_response',
3424
'bzrlib.tests.test_https_ca_bundle',
3425
'bzrlib.tests.test_identitymap',
3426
'bzrlib.tests.test_ignores',
3427
'bzrlib.tests.test_index',
3428
'bzrlib.tests.test_info',
3429
'bzrlib.tests.test_inv',
3430
'bzrlib.tests.test_inventory_delta',
3431
'bzrlib.tests.test_knit',
3432
'bzrlib.tests.test_lazy_import',
3433
'bzrlib.tests.test_lazy_regex',
3434
'bzrlib.tests.test_lockable_files',
3435
'bzrlib.tests.test_lockdir',
3436
'bzrlib.tests.test_log',
3437
'bzrlib.tests.test_lru_cache',
3438
'bzrlib.tests.test_lsprof',
3439
'bzrlib.tests.test_mail_client',
3440
'bzrlib.tests.test_memorytree',
3441
'bzrlib.tests.test_merge',
3442
'bzrlib.tests.test_merge3',
3443
'bzrlib.tests.test_merge_core',
3444
'bzrlib.tests.test_merge_directive',
3445
'bzrlib.tests.test_missing',
3446
'bzrlib.tests.test_msgeditor',
3447
'bzrlib.tests.test_multiparent',
3448
'bzrlib.tests.test_mutabletree',
3449
'bzrlib.tests.test_nonascii',
3450
'bzrlib.tests.test_options',
3451
'bzrlib.tests.test_osutils',
3452
'bzrlib.tests.test_osutils_encodings',
3453
'bzrlib.tests.test_pack',
3454
'bzrlib.tests.test_pack_repository',
3455
'bzrlib.tests.test_patch',
3456
'bzrlib.tests.test_patches',
3457
'bzrlib.tests.test_permissions',
3458
'bzrlib.tests.test_plugins',
3459
'bzrlib.tests.test_progress',
3460
'bzrlib.tests.test_read_bundle',
3461
'bzrlib.tests.test_reconcile',
3462
'bzrlib.tests.test_reconfigure',
3463
'bzrlib.tests.test_registry',
3464
'bzrlib.tests.test_remote',
3465
'bzrlib.tests.test_rename_map',
3466
'bzrlib.tests.test_repository',
3467
'bzrlib.tests.test_revert',
3468
'bzrlib.tests.test_revision',
3469
'bzrlib.tests.test_revisionspec',
3470
'bzrlib.tests.test_revisiontree',
3471
'bzrlib.tests.test_rio',
3472
'bzrlib.tests.test_rules',
3473
'bzrlib.tests.test_sampler',
3474
'bzrlib.tests.test_selftest',
3475
'bzrlib.tests.test_serializer',
3476
'bzrlib.tests.test_setup',
3477
'bzrlib.tests.test_sftp_transport',
3478
'bzrlib.tests.test_shelf',
3479
'bzrlib.tests.test_shelf_ui',
3480
'bzrlib.tests.test_smart',
3481
'bzrlib.tests.test_smart_add',
3482
'bzrlib.tests.test_smart_request',
3483
'bzrlib.tests.test_smart_transport',
3484
'bzrlib.tests.test_smtp_connection',
3485
'bzrlib.tests.test_source',
3486
'bzrlib.tests.test_ssh_transport',
3487
'bzrlib.tests.test_status',
3488
'bzrlib.tests.test_store',
3489
'bzrlib.tests.test_strace',
3490
'bzrlib.tests.test_subsume',
3491
'bzrlib.tests.test_switch',
3492
'bzrlib.tests.test_symbol_versioning',
3493
'bzrlib.tests.test_tag',
3494
'bzrlib.tests.test_testament',
3495
'bzrlib.tests.test_textfile',
3496
'bzrlib.tests.test_textmerge',
3497
'bzrlib.tests.test_timestamp',
3498
'bzrlib.tests.test_trace',
3499
'bzrlib.tests.test_transactions',
3500
'bzrlib.tests.test_transform',
3501
'bzrlib.tests.test_transport',
3502
'bzrlib.tests.test_transport_log',
3503
'bzrlib.tests.test_tree',
3504
'bzrlib.tests.test_treebuilder',
3505
'bzrlib.tests.test_tsort',
3506
'bzrlib.tests.test_tuned_gzip',
3507
'bzrlib.tests.test_ui',
3508
'bzrlib.tests.test_uncommit',
3509
'bzrlib.tests.test_upgrade',
3510
'bzrlib.tests.test_upgrade_stacked',
3511
'bzrlib.tests.test_urlutils',
3512
'bzrlib.tests.test_version',
3513
'bzrlib.tests.test_version_info',
3514
'bzrlib.tests.test_versionedfile',
3515
'bzrlib.tests.test_weave',
3516
'bzrlib.tests.test_whitebox',
3517
'bzrlib.tests.test_win32utils',
3518
'bzrlib.tests.test_workingtree',
3519
'bzrlib.tests.test_workingtree_4',
3520
'bzrlib.tests.test_wsgi',
3521
'bzrlib.tests.test_xml',
61
# XXX: should also test bzrlib.merge_core, but they seem to be out
62
# of date with the code.
64
for m in (bzrlib.store, bzrlib.inventory, bzrlib.branch,
65
bzrlib.osutils, bzrlib.commands, bzrlib.merge3):
66
if m not in MODULES_TO_DOCTEST:
67
MODULES_TO_DOCTEST.append(m)
70
TestBase.BZRPATH = os.path.join(os.path.realpath(os.path.dirname(bzrlib.__path__[0])), 'bzr')
71
print '%-30s %s' % ('bzr binary', TestBase.BZRPATH)
77
suite.addTest(TestLoader().loadTestsFromNames(testmod_names))
79
for m in MODULES_TO_TEST:
80
suite.addTest(TestLoader().loadTestsFromModule(m))
82
for m in (MODULES_TO_DOCTEST):
83
suite.addTest(DocTestSuite(m))
85
for p in bzrlib.plugin.all_plugins:
86
if hasattr(p, 'test_suite'):
87
suite.addTest(p.test_suite())
89
import bzrlib.merge_core
90
suite.addTest(unittest.makeSuite(bzrlib.merge_core.MergeTest, 'test_'))
92
return run_suite(suite, 'testbzr', verbose=verbose)
3524
loader = TestUtil.TestLoader()
3526
if keep_only is not None:
3527
id_filter = TestIdList(keep_only)
3529
starting_with = [test_prefix_alias_registry.resolve_alias(start)
3530
for start in starting_with]
3531
# We take precedence over keep_only because *at loading time* using
3532
# both options means we will load less tests for the same final result.
3533
def interesting_module(name):
3534
for start in starting_with:
3536
# Either the module name starts with the specified string
3537
name.startswith(start)
3538
# or it may contain tests starting with the specified string
3539
or start.startswith(name)
3543
loader = TestUtil.FilteredByModuleTestLoader(interesting_module)
3545
elif keep_only is not None:
3546
loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
3547
def interesting_module(name):
3548
return id_filter.refers_to(name)
3551
loader = TestUtil.TestLoader()
3552
def interesting_module(name):
3553
# No filtering, all modules are interesting
3556
suite = loader.suiteClass()
3558
# modules building their suite with loadTestsFromModuleNames
3559
suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
3561
modules_to_doctest = [
3563
'bzrlib.branchbuilder',
3566
'bzrlib.iterablefile',
3570
'bzrlib.symbol_versioning',
3573
'bzrlib.version_info_formats.format_custom',
3576
for mod in modules_to_doctest:
3577
if not interesting_module(mod):
3578
# No tests to keep here, move along
3581
# note that this really does mean "report only" -- doctest
3582
# still runs the rest of the examples
3583
doc_suite = doctest.DocTestSuite(mod,
3584
optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
3585
except ValueError, e:
3586
print '**failed to get doctest for: %s\n%s' % (mod, e)
3588
if len(doc_suite._tests) == 0:
3589
raise errors.BzrError("no doctests found in %s" % (mod,))
3590
suite.addTest(doc_suite)
3592
default_encoding = sys.getdefaultencoding()
3593
for name, plugin in bzrlib.plugin.plugins().items():
3594
if not interesting_module(plugin.module.__name__):
3596
plugin_suite = plugin.test_suite()
3597
# We used to catch ImportError here and turn it into just a warning,
3598
# but really if you don't have --no-plugins this should be a failure.
3599
# mbp 20080213 - see http://bugs.launchpad.net/bugs/189771
3600
if plugin_suite is None:
3601
plugin_suite = plugin.load_plugin_tests(loader)
3602
if plugin_suite is not None:
3603
suite.addTest(plugin_suite)
3604
if default_encoding != sys.getdefaultencoding():
3605
bzrlib.trace.warning(
3606
'Plugin "%s" tried to reset default encoding to: %s', name,
3607
sys.getdefaultencoding())
3609
sys.setdefaultencoding(default_encoding)
3612
suite = filter_suite_by_id_startswith(suite, starting_with)
3614
if keep_only is not None:
3615
# Now that the referred modules have loaded their tests, keep only the
3617
suite = filter_suite_by_id_list(suite, id_filter)
3618
# Do some sanity checks on the id_list filtering
3619
not_found, duplicates = suite_matches_id_list(suite, keep_only)
3621
# The tester has used both keep_only and starting_with, so he is
3622
# already aware that some tests are excluded from the list, there
3623
# is no need to tell him which.
3626
# Some tests mentioned in the list are not in the test suite. The
3627
# list may be out of date, report to the tester.
3628
for id in not_found:
3629
bzrlib.trace.warning('"%s" not found in the test suite', id)
3630
for id in duplicates:
3631
bzrlib.trace.warning('"%s" is used as an id by several tests', id)
3636
def multiply_scenarios(scenarios_left, scenarios_right):
3637
"""Multiply two sets of scenarios.
3639
:returns: the cartesian product of the two sets of scenarios, that is
3640
a scenario for every possible combination of a left scenario and a
3644
('%s,%s' % (left_name, right_name),
3645
dict(left_dict.items() + right_dict.items()))
3646
for left_name, left_dict in scenarios_left
3647
for right_name, right_dict in scenarios_right]
3650
def multiply_tests(tests, scenarios, result):
3651
"""Multiply tests_list by scenarios into result.
3653
This is the core workhorse for test parameterisation.
3655
Typically the load_tests() method for a per-implementation test suite will
3656
call multiply_tests and return the result.
3658
:param tests: The tests to parameterise.
3659
:param scenarios: The scenarios to apply: pairs of (scenario_name,
3660
scenario_param_dict).
3661
:param result: A TestSuite to add created tests to.
3663
This returns the passed in result TestSuite with the cross product of all
3664
the tests repeated once for each scenario. Each test is adapted by adding
3665
the scenario name at the end of its id(), and updating the test object's
3666
__dict__ with the scenario_param_dict.
3668
>>> import bzrlib.tests.test_sampler
3669
>>> r = multiply_tests(
3670
... bzrlib.tests.test_sampler.DemoTest('test_nothing'),
3671
... [('one', dict(param=1)),
3672
... ('two', dict(param=2))],
3674
>>> tests = list(iter_suite_tests(r))
3678
'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
3684
for test in iter_suite_tests(tests):
3685
apply_scenarios(test, scenarios, result)
3689
def apply_scenarios(test, scenarios, result):
3690
"""Apply the scenarios in scenarios to test and add to result.
3692
:param test: The test to apply scenarios to.
3693
:param scenarios: An iterable of scenarios to apply to test.
3695
:seealso: apply_scenario
3697
for scenario in scenarios:
3698
result.addTest(apply_scenario(test, scenario))
3702
def apply_scenario(test, scenario):
3703
"""Copy test and apply scenario to it.
3705
:param test: A test to adapt.
3706
:param scenario: A tuple describing the scenarion.
3707
The first element of the tuple is the new test id.
3708
The second element is a dict containing attributes to set on the
3710
:return: The adapted test.
3712
new_id = "%s(%s)" % (test.id(), scenario[0])
3713
new_test = clone_test(test, new_id)
3714
for name, value in scenario[1].items():
3715
setattr(new_test, name, value)
3719
def clone_test(test, new_id):
3720
"""Clone a test giving it a new id.
3722
:param test: The test to clone.
3723
:param new_id: The id to assign to it.
3724
:return: The new test.
3726
from copy import deepcopy
3727
new_test = deepcopy(test)
3728
new_test.id = lambda: new_id
3732
def _rmtree_temp_dir(dirname):
3733
# If LANG=C we probably have created some bogus paths
3734
# which rmtree(unicode) will fail to delete
3735
# so make sure we are using rmtree(str) to delete everything
3736
# except on win32, where rmtree(str) will fail
3737
# since it doesn't have the property of byte-stream paths
3738
# (they are either ascii or mbcs)
3739
if sys.platform == 'win32':
3740
# make sure we are using the unicode win32 api
3741
dirname = unicode(dirname)
3743
dirname = dirname.encode(sys.getfilesystemencoding())
3745
osutils.rmtree(dirname)
3747
if sys.platform == 'win32' and e.errno == errno.EACCES:
3748
sys.stderr.write('Permission denied: '
3749
'unable to remove testing dir '
3751
% (os.path.basename(dirname), e))
3756
class Feature(object):
3757
"""An operating system Feature."""
3760
self._available = None
3762
def available(self):
3763
"""Is the feature available?
3765
:return: True if the feature is available.
3767
if self._available is None:
3768
self._available = self._probe()
3769
return self._available
3772
"""Implement this method in concrete features.
3774
:return: True if the feature is available.
3776
raise NotImplementedError
3779
if getattr(self, 'feature_name', None):
3780
return self.feature_name()
3781
return self.__class__.__name__
3784
class _SymlinkFeature(Feature):
3787
return osutils.has_symlinks()
3789
def feature_name(self):
3792
SymlinkFeature = _SymlinkFeature()
3795
class _HardlinkFeature(Feature):
3798
return osutils.has_hardlinks()
3800
def feature_name(self):
3803
HardlinkFeature = _HardlinkFeature()
3806
class _OsFifoFeature(Feature):
3809
return getattr(os, 'mkfifo', None)
3811
def feature_name(self):
3812
return 'filesystem fifos'
3814
OsFifoFeature = _OsFifoFeature()
3817
class _UnicodeFilenameFeature(Feature):
3818
"""Does the filesystem support Unicode filenames?"""
3822
# Check for character combinations unlikely to be covered by any
3823
# single non-unicode encoding. We use the characters
3824
# - greek small letter alpha (U+03B1) and
3825
# - braille pattern dots-123456 (U+283F).
3826
os.stat(u'\u03b1\u283f')
3827
except UnicodeEncodeError:
3829
except (IOError, OSError):
3830
# The filesystem allows the Unicode filename but the file doesn't
3834
# The filesystem allows the Unicode filename and the file exists,
3838
UnicodeFilenameFeature = _UnicodeFilenameFeature()
3841
def probe_unicode_in_user_encoding():
3842
"""Try to encode several unicode strings to use in unicode-aware tests.
3843
Return first successfull match.
3845
:return: (unicode value, encoded plain string value) or (None, None)
3847
possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
3848
for uni_val in possible_vals:
3850
str_val = uni_val.encode(osutils.get_user_encoding())
3851
except UnicodeEncodeError:
3852
# Try a different character
3855
return uni_val, str_val
3859
def probe_bad_non_ascii(encoding):
3860
"""Try to find [bad] character with code [128..255]
3861
that cannot be decoded to unicode in some encoding.
3862
Return None if all non-ascii characters is valid
3865
for i in xrange(128, 256):
3868
char.decode(encoding)
3869
except UnicodeDecodeError:
3874
class _HTTPSServerFeature(Feature):
3875
"""Some tests want an https Server, check if one is available.
3877
Right now, the only way this is available is under python2.6 which provides
3888
def feature_name(self):
3889
return 'HTTPSServer'
3892
HTTPSServerFeature = _HTTPSServerFeature()
3895
class _UnicodeFilename(Feature):
3896
"""Does the filesystem support Unicode filenames?"""
3901
except UnicodeEncodeError:
3903
except (IOError, OSError):
3904
# The filesystem allows the Unicode filename but the file doesn't
3908
# The filesystem allows the Unicode filename and the file exists,
3912
UnicodeFilename = _UnicodeFilename()
3915
class _UTF8Filesystem(Feature):
3916
"""Is the filesystem UTF-8?"""
3919
if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
3923
UTF8Filesystem = _UTF8Filesystem()
3926
class _CaseInsCasePresFilenameFeature(Feature):
3927
"""Is the file-system case insensitive, but case-preserving?"""
3930
fileno, name = tempfile.mkstemp(prefix='MixedCase')
3932
# first check truly case-preserving for created files, then check
3933
# case insensitive when opening existing files.
3934
name = osutils.normpath(name)
3935
base, rel = osutils.split(name)
3936
found_rel = osutils.canonical_relpath(base, name)
3937
return (found_rel == rel
3938
and os.path.isfile(name.upper())
3939
and os.path.isfile(name.lower()))
3944
def feature_name(self):
3945
return "case-insensitive case-preserving filesystem"
3947
CaseInsCasePresFilenameFeature = _CaseInsCasePresFilenameFeature()
3950
class _CaseInsensitiveFilesystemFeature(Feature):
3951
"""Check if underlying filesystem is case-insensitive but *not* case
3954
# Note that on Windows, Cygwin, MacOS etc, the file-systems are far
3955
# more likely to be case preserving, so this case is rare.
3958
if CaseInsCasePresFilenameFeature.available():
3961
if TestCaseWithMemoryTransport.TEST_ROOT is None:
3962
root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
3963
TestCaseWithMemoryTransport.TEST_ROOT = root
3965
root = TestCaseWithMemoryTransport.TEST_ROOT
3966
tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
3968
name_a = osutils.pathjoin(tdir, 'a')
3969
name_A = osutils.pathjoin(tdir, 'A')
3971
result = osutils.isdir(name_A)
3972
_rmtree_temp_dir(tdir)
3975
def feature_name(self):
3976
return 'case-insensitive filesystem'
3978
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
3981
class _SubUnitFeature(Feature):
3982
"""Check if subunit is available."""
3991
def feature_name(self):
3994
SubUnitFeature = _SubUnitFeature()
3995
# Only define SubUnitBzrRunner if subunit is available.
3997
from subunit import TestProtocolClient
3998
class SubUnitBzrRunner(TextTestRunner):
3999
def run(self, test):
4000
result = TestProtocolClient(self.stream)