1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
# TODO: Perhaps there should be an API to find out if bzr running under the
19
# test suite -- some plugins might want to avoid making intrusive changes if
20
# this is the case. However, we want behaviour under to test to diverge as
21
# little as possible, so this should be used rarely if it's added at all.
22
# (Suggestion from j-a-meinel, 2005-11-24)
24
# NOTE: Some classes in here use camelCaseNaming() rather than
25
# underscore_naming(). That's for consistency with unittest; it's not the
26
# general style of bzrlib. Please continue that consistency when adding e.g.
27
# new assertFoo() methods.
31
from cStringIO import StringIO
38
from pprint import pformat
43
from subprocess import Popen, PIPE, STDOUT
67
import bzrlib.commands
68
import bzrlib.timestamp
70
import bzrlib.inventory
71
import bzrlib.iterablefile
76
# lsprof not available
78
from bzrlib.merge import merge_inner
81
from bzrlib.smart import client, request, server
83
from bzrlib import symbol_versioning
84
from bzrlib.symbol_versioning import (
91
from bzrlib.transport import get_transport
92
import bzrlib.transport
93
from bzrlib.transport.local import LocalURLServer
94
from bzrlib.transport.memory import MemoryServer
95
from bzrlib.transport.readonly import ReadonlyServer
96
from bzrlib.trace import mutter, note
97
from bzrlib.tests import TestUtil
98
from bzrlib.tests.http_server import HttpServer
99
from bzrlib.tests.TestUtil import (
103
from bzrlib.tests.treeshape import build_tree_contents
104
import bzrlib.version_info_formats.format_custom
105
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
107
# Mark this python module as being part of the implementation
108
# of unittest: this gives us better tracebacks where the last
109
# shown frame is the test code, not our assertXYZ.
112
default_transport = LocalURLServer
115
class ExtendedTestResult(unittest._TextTestResult):
116
"""Accepts, reports and accumulates the results of running tests.
118
Compared to the unittest version this class adds support for
119
profiling, benchmarking, stopping as soon as a test fails, and
120
skipping tests. There are further-specialized subclasses for
121
different types of display.
123
When a test finishes, in whatever way, it calls one of the addSuccess,
124
addFailure or addError classes. These in turn may redirect to a more
125
specific case for the special test results supported by our extended
128
Note that just one of these objects is fed the results from many tests.
133
def __init__(self, stream, descriptions, verbosity,
137
"""Construct new TestResult.
139
:param bench_history: Optionally, a writable file object to accumulate
142
unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
143
if bench_history is not None:
144
from bzrlib.version import _get_bzr_source_tree
145
src_tree = _get_bzr_source_tree()
148
revision_id = src_tree.get_parent_ids()[0]
150
# XXX: if this is a brand new tree, do the same as if there
154
# XXX: If there's no branch, what should we do?
156
bench_history.write("--date %s %s\n" % (time.time(), revision_id))
157
self._bench_history = bench_history
158
self.ui = ui.ui_factory
159
self.num_tests = num_tests
161
self.failure_count = 0
162
self.known_failure_count = 0
164
self.not_applicable_count = 0
165
self.unsupported = {}
167
self._overall_start_time = time.time()
169
def _extractBenchmarkTime(self, testCase):
170
"""Add a benchmark time for the current test case."""
171
return getattr(testCase, "_benchtime", None)
173
def _elapsedTestTimeString(self):
174
"""Return a time string for the overall time the current test has taken."""
175
return self._formatTime(time.time() - self._start_time)
177
def _testTimeString(self, testCase):
178
benchmark_time = self._extractBenchmarkTime(testCase)
179
if benchmark_time is not None:
181
self._formatTime(benchmark_time),
182
self._elapsedTestTimeString())
184
return " %s" % self._elapsedTestTimeString()
186
def _formatTime(self, seconds):
187
"""Format seconds as milliseconds with leading spaces."""
188
# some benchmarks can take thousands of seconds to run, so we need 8
190
return "%8dms" % (1000 * seconds)
192
def _shortened_test_description(self, test):
194
what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
197
def startTest(self, test):
198
unittest.TestResult.startTest(self, test)
199
self.report_test_start(test)
200
test.number = self.count
201
self._recordTestStartTime()
203
def _recordTestStartTime(self):
204
"""Record that a test has started."""
205
self._start_time = time.time()
207
def _cleanupLogFile(self, test):
208
# We can only do this if we have one of our TestCases, not if
210
setKeepLogfile = getattr(test, 'setKeepLogfile', None)
211
if setKeepLogfile is not None:
214
def addError(self, test, err):
215
"""Tell result that test finished with an error.
217
Called from the TestCase run() method when the test
218
fails with an unexpected error.
220
self._testConcluded(test)
221
if isinstance(err[1], TestNotApplicable):
222
return self._addNotApplicable(test, err)
223
elif isinstance(err[1], UnavailableFeature):
224
return self.addNotSupported(test, err[1].args[0])
226
unittest.TestResult.addError(self, test, err)
227
self.error_count += 1
228
self.report_error(test, err)
231
self._cleanupLogFile(test)
233
def addFailure(self, test, err):
234
"""Tell result that test failed.
236
Called from the TestCase run() method when the test
237
fails because e.g. an assert() method failed.
239
self._testConcluded(test)
240
if isinstance(err[1], KnownFailure):
241
return self._addKnownFailure(test, err)
243
unittest.TestResult.addFailure(self, test, err)
244
self.failure_count += 1
245
self.report_failure(test, err)
248
self._cleanupLogFile(test)
250
def addSuccess(self, test):
251
"""Tell result that test completed successfully.
253
Called from the TestCase run()
255
self._testConcluded(test)
256
if self._bench_history is not None:
257
benchmark_time = self._extractBenchmarkTime(test)
258
if benchmark_time is not None:
259
self._bench_history.write("%s %s\n" % (
260
self._formatTime(benchmark_time),
262
self.report_success(test)
263
self._cleanupLogFile(test)
264
unittest.TestResult.addSuccess(self, test)
265
test._log_contents = ''
267
def _testConcluded(self, test):
268
"""Common code when a test has finished.
270
Called regardless of whether it succeded, failed, etc.
274
def _addKnownFailure(self, test, err):
275
self.known_failure_count += 1
276
self.report_known_failure(test, err)
278
def addNotSupported(self, test, feature):
279
"""The test will not be run because of a missing feature.
281
# this can be called in two different ways: it may be that the
282
# test started running, and then raised (through addError)
283
# UnavailableFeature. Alternatively this method can be called
284
# while probing for features before running the tests; in that
285
# case we will see startTest and stopTest, but the test will never
287
self.unsupported.setdefault(str(feature), 0)
288
self.unsupported[str(feature)] += 1
289
self.report_unsupported(test, feature)
291
def addSkip(self, test, reason):
292
"""A test has not run for 'reason'."""
294
self.report_skip(test, reason)
296
def _addNotApplicable(self, test, skip_excinfo):
297
if isinstance(skip_excinfo[1], TestNotApplicable):
298
self.not_applicable_count += 1
299
self.report_not_applicable(test, skip_excinfo)
302
except KeyboardInterrupt:
305
self.addError(test, test.exc_info())
307
# seems best to treat this as success from point-of-view of unittest
308
# -- it actually does nothing so it barely matters :)
309
unittest.TestResult.addSuccess(self, test)
310
test._log_contents = ''
312
def printErrorList(self, flavour, errors):
313
for test, err in errors:
314
self.stream.writeln(self.separator1)
315
self.stream.write("%s: " % flavour)
316
self.stream.writeln(self.getDescription(test))
317
if getattr(test, '_get_log', None) is not None:
318
self.stream.write('\n')
320
('vvvv[log from %s]' % test.id()).ljust(78,'-'))
321
self.stream.write('\n')
322
self.stream.write(test._get_log())
323
self.stream.write('\n')
325
('^^^^[log from %s]' % test.id()).ljust(78,'-'))
326
self.stream.write('\n')
327
self.stream.writeln(self.separator2)
328
self.stream.writeln("%s" % err)
333
def report_cleaning_up(self):
336
def report_success(self, test):
339
def wasStrictlySuccessful(self):
340
if self.unsupported or self.known_failure_count:
342
return self.wasSuccessful()
345
class TextTestResult(ExtendedTestResult):
346
"""Displays progress and results of tests in text form"""
348
def __init__(self, stream, descriptions, verbosity,
353
ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
354
bench_history, num_tests)
356
self.pb = self.ui.nested_progress_bar()
357
self._supplied_pb = False
360
self._supplied_pb = True
361
self.pb.show_pct = False
362
self.pb.show_spinner = False
363
self.pb.show_eta = False,
364
self.pb.show_count = False
365
self.pb.show_bar = False
367
def report_starting(self):
368
self.pb.update('[test 0/%d] Starting' % (self.num_tests))
370
def _progress_prefix_text(self):
371
# the longer this text, the less space we have to show the test
373
a = '[%d' % self.count # total that have been run
374
# tests skipped as known not to be relevant are not important enough
376
## if self.skip_count:
377
## a += ', %d skip' % self.skip_count
378
## if self.known_failure_count:
379
## a += '+%dX' % self.known_failure_count
380
if self.num_tests is not None:
381
a +='/%d' % self.num_tests
383
runtime = time.time() - self._overall_start_time
385
a += '%dm%ds' % (runtime / 60, runtime % 60)
389
a += ', %d err' % self.error_count
390
if self.failure_count:
391
a += ', %d fail' % self.failure_count
393
a += ', %d missing' % len(self.unsupported)
397
def report_test_start(self, test):
400
self._progress_prefix_text()
402
+ self._shortened_test_description(test))
404
def _test_description(self, test):
405
return self._shortened_test_description(test)
407
def report_error(self, test, err):
408
self.pb.note('ERROR: %s\n %s\n',
409
self._test_description(test),
413
def report_failure(self, test, err):
414
self.pb.note('FAIL: %s\n %s\n',
415
self._test_description(test),
419
def report_known_failure(self, test, err):
420
self.pb.note('XFAIL: %s\n%s\n',
421
self._test_description(test), err[1])
423
def report_skip(self, test, reason):
426
def report_not_applicable(self, test, skip_excinfo):
429
def report_unsupported(self, test, feature):
430
"""test cannot be run because feature is missing."""
432
def report_cleaning_up(self):
433
self.pb.update('Cleaning up')
436
if not self._supplied_pb:
440
class VerboseTestResult(ExtendedTestResult):
441
"""Produce long output, with one line per test run plus times"""
443
def _ellipsize_to_right(self, a_string, final_width):
444
"""Truncate and pad a string, keeping the right hand side"""
445
if len(a_string) > final_width:
446
result = '...' + a_string[3-final_width:]
449
return result.ljust(final_width)
451
def report_starting(self):
452
self.stream.write('running %d tests...\n' % self.num_tests)
454
def report_test_start(self, test):
456
name = self._shortened_test_description(test)
457
# width needs space for 6 char status, plus 1 for slash, plus 2 10-char
458
# numbers, plus a trailing blank
459
# when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on space
460
self.stream.write(self._ellipsize_to_right(name,
461
osutils.terminal_width()-30))
464
def _error_summary(self, err):
466
return '%s%s' % (indent, err[1])
468
def report_error(self, test, err):
469
self.stream.writeln('ERROR %s\n%s'
470
% (self._testTimeString(test),
471
self._error_summary(err)))
473
def report_failure(self, test, err):
474
self.stream.writeln(' FAIL %s\n%s'
475
% (self._testTimeString(test),
476
self._error_summary(err)))
478
def report_known_failure(self, test, err):
479
self.stream.writeln('XFAIL %s\n%s'
480
% (self._testTimeString(test),
481
self._error_summary(err)))
483
def report_success(self, test):
484
self.stream.writeln(' OK %s' % self._testTimeString(test))
485
for bench_called, stats in getattr(test, '_benchcalls', []):
486
self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
487
stats.pprint(file=self.stream)
488
# flush the stream so that we get smooth output. This verbose mode is
489
# used to show the output in PQM.
492
def report_skip(self, test, reason):
493
self.stream.writeln(' SKIP %s\n%s'
494
% (self._testTimeString(test), reason))
496
def report_not_applicable(self, test, skip_excinfo):
497
self.stream.writeln(' N/A %s\n%s'
498
% (self._testTimeString(test),
499
self._error_summary(skip_excinfo)))
501
def report_unsupported(self, test, feature):
502
"""test cannot be run because feature is missing."""
503
self.stream.writeln("NODEP %s\n The feature '%s' is not available."
504
%(self._testTimeString(test), feature))
507
class TextTestRunner(object):
508
stop_on_failure = False
517
self.stream = unittest._WritelnDecorator(stream)
518
self.descriptions = descriptions
519
self.verbosity = verbosity
520
self._bench_history = bench_history
521
self.list_only = list_only
524
"Run the given test case or test suite."
525
startTime = time.time()
526
if self.verbosity == 1:
527
result_class = TextTestResult
528
elif self.verbosity >= 2:
529
result_class = VerboseTestResult
530
result = result_class(self.stream,
533
bench_history=self._bench_history,
534
num_tests=test.countTestCases(),
536
result.stop_early = self.stop_on_failure
537
result.report_starting()
539
if self.verbosity >= 2:
540
self.stream.writeln("Listing tests only ...\n")
542
for t in iter_suite_tests(test):
543
self.stream.writeln("%s" % (t.id()))
545
actionTaken = "Listed"
552
if isinstance(test, testtools.ConcurrentTestSuite):
553
# We need to catch bzr specific behaviors
554
test.run(BZRTransformingResult(result))
557
run = result.testsRun
559
stopTime = time.time()
560
timeTaken = stopTime - startTime
562
self.stream.writeln(result.separator2)
563
self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
564
run, run != 1 and "s" or "", timeTaken))
565
self.stream.writeln()
566
if not result.wasSuccessful():
567
self.stream.write("FAILED (")
568
failed, errored = map(len, (result.failures, result.errors))
570
self.stream.write("failures=%d" % failed)
572
if failed: self.stream.write(", ")
573
self.stream.write("errors=%d" % errored)
574
if result.known_failure_count:
575
if failed or errored: self.stream.write(", ")
576
self.stream.write("known_failure_count=%d" %
577
result.known_failure_count)
578
self.stream.writeln(")")
580
if result.known_failure_count:
581
self.stream.writeln("OK (known_failures=%d)" %
582
result.known_failure_count)
584
self.stream.writeln("OK")
585
if result.skip_count > 0:
586
skipped = result.skip_count
587
self.stream.writeln('%d test%s skipped' %
588
(skipped, skipped != 1 and "s" or ""))
589
if result.unsupported:
590
for feature, count in sorted(result.unsupported.items()):
591
self.stream.writeln("Missing feature '%s' skipped %d tests." %
597
def iter_suite_tests(suite):
598
"""Return all tests in a suite, recursing through nested suites"""
599
if isinstance(suite, unittest.TestCase):
601
elif isinstance(suite, unittest.TestSuite):
603
for r in iter_suite_tests(item):
606
raise Exception('unknown type %r for object %r'
607
% (type(suite), suite))
610
class TestSkipped(Exception):
611
"""Indicates that a test was intentionally skipped, rather than failing."""
614
class TestNotApplicable(TestSkipped):
615
"""A test is not applicable to the situation where it was run.
617
This is only normally raised by parameterized tests, if they find that
618
the instance they're constructed upon does not support one aspect
623
class KnownFailure(AssertionError):
624
"""Indicates that a test failed in a precisely expected manner.
626
Such failures dont block the whole test suite from passing because they are
627
indicators of partially completed code or of future work. We have an
628
explicit error for them so that we can ensure that they are always visible:
629
KnownFailures are always shown in the output of bzr selftest.
633
class UnavailableFeature(Exception):
634
"""A feature required for this test was not available.
636
The feature should be used to construct the exception.
640
class CommandFailed(Exception):
644
class StringIOWrapper(object):
645
"""A wrapper around cStringIO which just adds an encoding attribute.
647
Internally we can check sys.stdout to see what the output encoding
648
should be. However, cStringIO has no encoding attribute that we can
649
set. So we wrap it instead.
654
def __init__(self, s=None):
656
self.__dict__['_cstring'] = StringIO(s)
658
self.__dict__['_cstring'] = StringIO()
660
def __getattr__(self, name, getattr=getattr):
661
return getattr(self.__dict__['_cstring'], name)
663
def __setattr__(self, name, val):
664
if name == 'encoding':
665
self.__dict__['encoding'] = val
667
return setattr(self._cstring, name, val)
670
class TestUIFactory(ui.CLIUIFactory):
671
"""A UI Factory for testing.
673
Hide the progress bar but emit note()s.
675
Allows get_password to be tested without real tty attached.
678
def __init__(self, stdout=None, stderr=None, stdin=None):
679
if stdin is not None:
680
# We use a StringIOWrapper to be able to test various
681
# encodings, but the user is still responsible to
682
# encode the string and to set the encoding attribute
683
# of StringIOWrapper.
684
stdin = StringIOWrapper(stdin)
685
super(TestUIFactory, self).__init__(stdin, stdout, stderr)
688
"""See progress.ProgressBar.clear()."""
690
def clear_term(self):
691
"""See progress.ProgressBar.clear_term()."""
694
"""See progress.ProgressBar.finished()."""
696
def note(self, fmt_string, *args, **kwargs):
697
"""See progress.ProgressBar.note()."""
698
self.stdout.write((fmt_string + "\n") % args)
700
def progress_bar(self):
703
def nested_progress_bar(self):
706
def update(self, message, count=None, total=None):
707
"""See progress.ProgressBar.update()."""
709
def get_non_echoed_password(self):
710
"""Get password from stdin without trying to handle the echo mode"""
711
password = self.stdin.readline()
714
if password[-1] == '\n':
715
password = password[:-1]
719
def _report_leaked_threads():
720
bzrlib.trace.warning('%s is leaking threads among %d leaking tests',
721
TestCase._first_thread_leaker_id,
722
TestCase._leaking_threads_tests)
725
class TestCase(unittest.TestCase):
726
"""Base class for bzr unit tests.
728
Tests that need access to disk resources should subclass
729
TestCaseInTempDir not TestCase.
731
Error and debug log messages are redirected from their usual
732
location into a temporary file, the contents of which can be
733
retrieved by _get_log(). We use a real OS file, not an in-memory object,
734
so that it can also capture file IO. When the test completes this file
735
is read into memory and removed from disk.
737
There are also convenience functions to invoke bzr's command-line
738
routine, and to build and check bzr trees.
740
In addition to the usual method of overriding tearDown(), this class also
741
allows subclasses to register functions into the _cleanups list, which is
742
run in order as the object is torn down. It's less likely this will be
743
accidentally overlooked.
746
_active_threads = None
747
_leaking_threads_tests = 0
748
_first_thread_leaker_id = None
749
_log_file_name = None
751
_keep_log_file = False
752
# record lsprof data when performing benchmark calls.
753
_gather_lsprof_in_benchmarks = False
754
attrs_to_keep = ('id', '_testMethodName', '_testMethodDoc',
755
'_log_contents', '_log_file_name', '_benchtime',
756
'_TestCase__testMethodName')
758
def __init__(self, methodName='testMethod'):
759
super(TestCase, self).__init__(methodName)
761
self._bzr_test_setUp_run = False
762
self._bzr_test_tearDown_run = False
765
unittest.TestCase.setUp(self)
766
self._bzr_test_setUp_run = True
767
self._cleanEnvironment()
770
self._benchcalls = []
771
self._benchtime = None
773
self._clear_debug_flags()
774
TestCase._active_threads = threading.activeCount()
775
self.addCleanup(self._check_leaked_threads)
780
pdb.Pdb().set_trace(sys._getframe().f_back)
782
def _check_leaked_threads(self):
783
active = threading.activeCount()
784
leaked_threads = active - TestCase._active_threads
785
TestCase._active_threads = active
787
TestCase._leaking_threads_tests += 1
788
if TestCase._first_thread_leaker_id is None:
789
TestCase._first_thread_leaker_id = self.id()
790
# we're not specifically told when all tests are finished.
791
# This will do. We use a function to avoid keeping a reference
792
# to a TestCase object.
793
atexit.register(_report_leaked_threads)
795
def _clear_debug_flags(self):
796
"""Prevent externally set debug flags affecting tests.
798
Tests that want to use debug flags can just set them in the
799
debug_flags set during setup/teardown.
801
self._preserved_debug_flags = set(debug.debug_flags)
802
if 'allow_debug' not in selftest_debug_flags:
803
debug.debug_flags.clear()
804
self.addCleanup(self._restore_debug_flags)
806
def _clear_hooks(self):
807
# prevent hooks affecting tests
808
self._preserved_hooks = {}
809
for key, factory in hooks.known_hooks.items():
810
parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
811
current_hooks = hooks.known_hooks_key_to_object(key)
812
self._preserved_hooks[parent] = (name, current_hooks)
813
self.addCleanup(self._restoreHooks)
814
for key, factory in hooks.known_hooks.items():
815
parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
816
setattr(parent, name, factory())
817
# this hook should always be installed
818
request._install_hook()
820
def _silenceUI(self):
821
"""Turn off UI for duration of test"""
822
# by default the UI is off; tests can turn it on if they want it.
823
saved = ui.ui_factory
825
ui.ui_factory = saved
826
ui.ui_factory = ui.SilentUIFactory()
827
self.addCleanup(_restore)
829
def _ndiff_strings(self, a, b):
830
"""Return ndiff between two strings containing lines.
832
A trailing newline is added if missing to make the strings
834
if b and b[-1] != '\n':
836
if a and a[-1] != '\n':
838
difflines = difflib.ndiff(a.splitlines(True),
840
linejunk=lambda x: False,
841
charjunk=lambda x: False)
842
return ''.join(difflines)
844
def assertEqual(self, a, b, message=''):
848
except UnicodeError, e:
849
# If we can't compare without getting a UnicodeError, then
850
# obviously they are different
851
mutter('UnicodeError: %s', e)
854
raise AssertionError("%snot equal:\na = %s\nb = %s\n"
856
pformat(a), pformat(b)))
858
assertEquals = assertEqual
860
def assertEqualDiff(self, a, b, message=None):
861
"""Assert two texts are equal, if not raise an exception.
863
This is intended for use with multi-line strings where it can
864
be hard to find the differences by eye.
866
# TODO: perhaps override assertEquals to call this for strings?
870
message = "texts not equal:\n"
872
message = 'first string is missing a final newline.\n'
874
message = 'second string is missing a final newline.\n'
875
raise AssertionError(message +
876
self._ndiff_strings(a, b))
878
def assertEqualMode(self, mode, mode_test):
879
self.assertEqual(mode, mode_test,
880
'mode mismatch %o != %o' % (mode, mode_test))
882
def assertEqualStat(self, expected, actual):
883
"""assert that expected and actual are the same stat result.
885
:param expected: A stat result.
886
:param actual: A stat result.
887
:raises AssertionError: If the expected and actual stat values differ
890
self.assertEqual(expected.st_size, actual.st_size)
891
self.assertEqual(expected.st_mtime, actual.st_mtime)
892
self.assertEqual(expected.st_ctime, actual.st_ctime)
893
self.assertEqual(expected.st_dev, actual.st_dev)
894
self.assertEqual(expected.st_ino, actual.st_ino)
895
self.assertEqual(expected.st_mode, actual.st_mode)
897
def assertLength(self, length, obj_with_len):
898
"""Assert that obj_with_len is of length length."""
899
if len(obj_with_len) != length:
900
self.fail("Incorrect length: wanted %d, got %d for %r" % (
901
length, len(obj_with_len), obj_with_len))
903
def assertPositive(self, val):
904
"""Assert that val is greater than 0."""
905
self.assertTrue(val > 0, 'expected a positive value, but got %s' % val)
907
def assertNegative(self, val):
908
"""Assert that val is less than 0."""
909
self.assertTrue(val < 0, 'expected a negative value, but got %s' % val)
911
def assertStartsWith(self, s, prefix):
912
if not s.startswith(prefix):
913
raise AssertionError('string %r does not start with %r' % (s, prefix))
915
def assertEndsWith(self, s, suffix):
916
"""Asserts that s ends with suffix."""
917
if not s.endswith(suffix):
918
raise AssertionError('string %r does not end with %r' % (s, suffix))
920
def assertContainsRe(self, haystack, needle_re, flags=0):
921
"""Assert that a contains something matching a regular expression."""
922
if not re.search(needle_re, haystack, flags):
923
if '\n' in haystack or len(haystack) > 60:
924
# a long string, format it in a more readable way
925
raise AssertionError(
926
'pattern "%s" not found in\n"""\\\n%s"""\n'
927
% (needle_re, haystack))
929
raise AssertionError('pattern "%s" not found in "%s"'
930
% (needle_re, haystack))
932
def assertNotContainsRe(self, haystack, needle_re, flags=0):
933
"""Assert that a does not match a regular expression"""
934
if re.search(needle_re, haystack, flags):
935
raise AssertionError('pattern "%s" found in "%s"'
936
% (needle_re, haystack))
938
def assertSubset(self, sublist, superlist):
939
"""Assert that every entry in sublist is present in superlist."""
940
missing = set(sublist) - set(superlist)
942
raise AssertionError("value(s) %r not present in container %r" %
943
(missing, superlist))
945
def assertListRaises(self, excClass, func, *args, **kwargs):
946
"""Fail unless excClass is raised when the iterator from func is used.
948
Many functions can return generators this makes sure
949
to wrap them in a list() call to make sure the whole generator
950
is run, and that the proper exception is raised.
953
list(func(*args, **kwargs))
957
if getattr(excClass,'__name__', None) is not None:
958
excName = excClass.__name__
960
excName = str(excClass)
961
raise self.failureException, "%s not raised" % excName
963
def assertRaises(self, excClass, callableObj, *args, **kwargs):
964
"""Assert that a callable raises a particular exception.
966
:param excClass: As for the except statement, this may be either an
967
exception class, or a tuple of classes.
968
:param callableObj: A callable, will be passed ``*args`` and
971
Returns the exception so that you can examine it.
974
callableObj(*args, **kwargs)
978
if getattr(excClass,'__name__', None) is not None:
979
excName = excClass.__name__
982
excName = str(excClass)
983
raise self.failureException, "%s not raised" % excName
985
def assertIs(self, left, right, message=None):
986
if not (left is right):
987
if message is not None:
988
raise AssertionError(message)
990
raise AssertionError("%r is not %r." % (left, right))
992
def assertIsNot(self, left, right, message=None):
994
if message is not None:
995
raise AssertionError(message)
997
raise AssertionError("%r is %r." % (left, right))
999
def assertTransportMode(self, transport, path, mode):
1000
"""Fail if a path does not have mode "mode".
1002
If modes are not supported on this transport, the assertion is ignored.
1004
if not transport._can_roundtrip_unix_modebits():
1006
path_stat = transport.stat(path)
1007
actual_mode = stat.S_IMODE(path_stat.st_mode)
1008
self.assertEqual(mode, actual_mode,
1009
'mode of %r incorrect (%s != %s)'
1010
% (path, oct(mode), oct(actual_mode)))
1012
def assertIsSameRealPath(self, path1, path2):
1013
"""Fail if path1 and path2 points to different files"""
1014
self.assertEqual(osutils.realpath(path1),
1015
osutils.realpath(path2),
1016
"apparent paths:\na = %s\nb = %s\n," % (path1, path2))
1018
def assertIsInstance(self, obj, kls):
1019
"""Fail if obj is not an instance of kls"""
1020
if not isinstance(obj, kls):
1021
self.fail("%r is an instance of %s rather than %s" % (
1022
obj, obj.__class__, kls))
1024
def expectFailure(self, reason, assertion, *args, **kwargs):
1025
"""Invoke a test, expecting it to fail for the given reason.
1027
This is for assertions that ought to succeed, but currently fail.
1028
(The failure is *expected* but not *wanted*.) Please be very precise
1029
about the failure you're expecting. If a new bug is introduced,
1030
AssertionError should be raised, not KnownFailure.
1032
Frequently, expectFailure should be followed by an opposite assertion.
1035
Intended to be used with a callable that raises AssertionError as the
1036
'assertion' parameter. args and kwargs are passed to the 'assertion'.
1038
Raises KnownFailure if the test fails. Raises AssertionError if the
1043
self.expectFailure('Math is broken', self.assertNotEqual, 54,
1045
self.assertEqual(42, dynamic_val)
1047
This means that a dynamic_val of 54 will cause the test to raise
1048
a KnownFailure. Once math is fixed and the expectFailure is removed,
1049
only a dynamic_val of 42 will allow the test to pass. Anything other
1050
than 54 or 42 will cause an AssertionError.
1053
assertion(*args, **kwargs)
1054
except AssertionError:
1055
raise KnownFailure(reason)
1057
self.fail('Unexpected success. Should have failed: %s' % reason)
1059
def assertFileEqual(self, content, path):
1060
"""Fail if path does not contain 'content'."""
1061
self.failUnlessExists(path)
1062
f = file(path, 'rb')
1067
self.assertEqualDiff(content, s)
1069
def failUnlessExists(self, path):
1070
"""Fail unless path or paths, which may be abs or relative, exist."""
1071
if not isinstance(path, basestring):
1073
self.failUnlessExists(p)
1075
self.failUnless(osutils.lexists(path),path+" does not exist")
1077
def failIfExists(self, path):
1078
"""Fail if path or paths, which may be abs or relative, exist."""
1079
if not isinstance(path, basestring):
1081
self.failIfExists(p)
1083
self.failIf(osutils.lexists(path),path+" exists")
1085
def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1086
"""A helper for callDeprecated and applyDeprecated.
1088
:param a_callable: A callable to call.
1089
:param args: The positional arguments for the callable
1090
:param kwargs: The keyword arguments for the callable
1091
:return: A tuple (warnings, result). result is the result of calling
1092
a_callable(``*args``, ``**kwargs``).
1095
def capture_warnings(msg, cls=None, stacklevel=None):
1096
# we've hooked into a deprecation specific callpath,
1097
# only deprecations should getting sent via it.
1098
self.assertEqual(cls, DeprecationWarning)
1099
local_warnings.append(msg)
1100
original_warning_method = symbol_versioning.warn
1101
symbol_versioning.set_warning_method(capture_warnings)
1103
result = a_callable(*args, **kwargs)
1105
symbol_versioning.set_warning_method(original_warning_method)
1106
return (local_warnings, result)
1108
def applyDeprecated(self, deprecation_format, a_callable, *args, **kwargs):
1109
"""Call a deprecated callable without warning the user.
1111
Note that this only captures warnings raised by symbol_versioning.warn,
1112
not other callers that go direct to the warning module.
1114
To test that a deprecated method raises an error, do something like
1117
self.assertRaises(errors.ReservedId,
1118
self.applyDeprecated,
1119
deprecated_in((1, 5, 0)),
1123
:param deprecation_format: The deprecation format that the callable
1124
should have been deprecated with. This is the same type as the
1125
parameter to deprecated_method/deprecated_function. If the
1126
callable is not deprecated with this format, an assertion error
1128
:param a_callable: A callable to call. This may be a bound method or
1129
a regular function. It will be called with ``*args`` and
1131
:param args: The positional arguments for the callable
1132
:param kwargs: The keyword arguments for the callable
1133
:return: The result of a_callable(``*args``, ``**kwargs``)
1135
call_warnings, result = self._capture_deprecation_warnings(a_callable,
1137
expected_first_warning = symbol_versioning.deprecation_string(
1138
a_callable, deprecation_format)
1139
if len(call_warnings) == 0:
1140
self.fail("No deprecation warning generated by call to %s" %
1142
self.assertEqual(expected_first_warning, call_warnings[0])
1145
def callCatchWarnings(self, fn, *args, **kw):
1146
"""Call a callable that raises python warnings.
1148
The caller's responsible for examining the returned warnings.
1150
If the callable raises an exception, the exception is not
1151
caught and propagates up to the caller. In that case, the list
1152
of warnings is not available.
1154
:returns: ([warning_object, ...], fn_result)
1156
# XXX: This is not perfect, because it completely overrides the
1157
# warnings filters, and some code may depend on suppressing particular
1158
# warnings. It's the easiest way to insulate ourselves from -Werror,
1159
# though. -- Andrew, 20071062
1161
def _catcher(message, category, filename, lineno, file=None, line=None):
1162
# despite the name, 'message' is normally(?) a Warning subclass
1164
wlist.append(message)
1165
saved_showwarning = warnings.showwarning
1166
saved_filters = warnings.filters
1168
warnings.showwarning = _catcher
1169
warnings.filters = []
1170
result = fn(*args, **kw)
1172
warnings.showwarning = saved_showwarning
1173
warnings.filters = saved_filters
1174
return wlist, result
1176
def callDeprecated(self, expected, callable, *args, **kwargs):
1177
"""Assert that a callable is deprecated in a particular way.
1179
This is a very precise test for unusual requirements. The
1180
applyDeprecated helper function is probably more suited for most tests
1181
as it allows you to simply specify the deprecation format being used
1182
and will ensure that that is issued for the function being called.
1184
Note that this only captures warnings raised by symbol_versioning.warn,
1185
not other callers that go direct to the warning module. To catch
1186
general warnings, use callCatchWarnings.
1188
:param expected: a list of the deprecation warnings expected, in order
1189
:param callable: The callable to call
1190
:param args: The positional arguments for the callable
1191
:param kwargs: The keyword arguments for the callable
1193
call_warnings, result = self._capture_deprecation_warnings(callable,
1195
self.assertEqual(expected, call_warnings)
1198
def _startLogFile(self):
1199
"""Send bzr and test log messages to a temporary file.
1201
The file is removed as the test is torn down.
1203
fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
1204
self._log_file = os.fdopen(fileno, 'w+')
1205
self._log_memento = bzrlib.trace.push_log_file(self._log_file)
1206
self._log_file_name = name
1207
self.addCleanup(self._finishLogFile)
1209
def _finishLogFile(self):
1210
"""Finished with the log file.
1212
Close the file and delete it, unless setKeepLogfile was called.
1214
if self._log_file is None:
1216
bzrlib.trace.pop_log_file(self._log_memento)
1217
self._log_file.close()
1218
self._log_file = None
1219
if not self._keep_log_file:
1220
os.remove(self._log_file_name)
1221
self._log_file_name = None
1223
def setKeepLogfile(self):
1224
"""Make the logfile not be deleted when _finishLogFile is called."""
1225
self._keep_log_file = True
1227
def addCleanup(self, callable, *args, **kwargs):
1228
"""Arrange to run a callable when this case is torn down.
1230
Callables are run in the reverse of the order they are registered,
1231
ie last-in first-out.
1233
self._cleanups.append((callable, args, kwargs))
1235
def _cleanEnvironment(self):
1237
'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
1238
'HOME': os.getcwd(),
1239
# bzr now uses the Win32 API and doesn't rely on APPDATA, but the
1240
# tests do check our impls match APPDATA
1241
'BZR_EDITOR': None, # test_msgeditor manipulates this variable
1245
'BZREMAIL': None, # may still be present in the environment
1247
'BZR_PROGRESS_BAR': None,
1249
'BZR_PLUGIN_PATH': None,
1251
'SSH_AUTH_SOCK': None,
1255
'https_proxy': None,
1256
'HTTPS_PROXY': None,
1261
# Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
1262
# least. If you do (care), please update this comment
1266
'BZR_REMOTE_PATH': None,
1269
self.addCleanup(self._restoreEnvironment)
1270
for name, value in new_env.iteritems():
1271
self._captureVar(name, value)
1273
def _captureVar(self, name, newvalue):
1274
"""Set an environment variable, and reset it when finished."""
1275
self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
1277
def _restore_debug_flags(self):
1278
debug.debug_flags.clear()
1279
debug.debug_flags.update(self._preserved_debug_flags)
1281
def _restoreEnvironment(self):
1282
for name, value in self.__old_env.iteritems():
1283
osutils.set_or_unset_env(name, value)
1285
def _restoreHooks(self):
1286
for klass, (name, hooks) in self._preserved_hooks.items():
1287
setattr(klass, name, hooks)
1289
def knownFailure(self, reason):
1290
"""This test has failed for some known reason."""
1291
raise KnownFailure(reason)
1293
def _do_skip(self, result, reason):
1294
addSkip = getattr(result, 'addSkip', None)
1295
if not callable(addSkip):
1296
result.addError(self, sys.exc_info())
1298
addSkip(self, reason)
1300
def run(self, result=None):
1301
if result is None: result = self.defaultTestResult()
1302
for feature in getattr(self, '_test_needs_features', []):
1303
if not feature.available():
1304
result.startTest(self)
1305
if getattr(result, 'addNotSupported', None):
1306
result.addNotSupported(self, feature)
1308
result.addSuccess(self)
1309
result.stopTest(self)
1313
result.startTest(self)
1314
absent_attr = object()
1316
method_name = getattr(self, '_testMethodName', absent_attr)
1317
if method_name is absent_attr:
1319
method_name = getattr(self, '_TestCase__testMethodName')
1320
testMethod = getattr(self, method_name)
1324
if not self._bzr_test_setUp_run:
1326
"test setUp did not invoke "
1327
"bzrlib.tests.TestCase's setUp")
1328
except KeyboardInterrupt:
1330
except TestSkipped, e:
1331
self._do_skip(result, e.args[0])
1335
result.addError(self, sys.exc_info())
1342
except self.failureException:
1343
result.addFailure(self, sys.exc_info())
1344
except TestSkipped, e:
1346
reason = "No reason given."
1349
self._do_skip(result, reason)
1350
except KeyboardInterrupt:
1353
result.addError(self, sys.exc_info())
1357
if not self._bzr_test_tearDown_run:
1359
"test tearDown did not invoke "
1360
"bzrlib.tests.TestCase's tearDown")
1361
except KeyboardInterrupt:
1364
result.addError(self, sys.exc_info())
1366
if ok: result.addSuccess(self)
1368
result.stopTest(self)
1370
except TestNotApplicable:
1371
# Not moved from the result [yet].
1373
except KeyboardInterrupt:
1377
absent_attr = object()
1378
for attr_name in self.attrs_to_keep:
1379
attr = getattr(self, attr_name, absent_attr)
1380
if attr is not absent_attr:
1381
saved_attrs[attr_name] = attr
1382
self.__dict__ = saved_attrs
1385
self._bzr_test_tearDown_run = True
1387
self._log_contents = ''
1388
unittest.TestCase.tearDown(self)
1390
def time(self, callable, *args, **kwargs):
1391
"""Run callable and accrue the time it takes to the benchmark time.
1393
If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
1394
this will cause lsprofile statistics to be gathered and stored in
1397
if self._benchtime is None:
1401
if not self._gather_lsprof_in_benchmarks:
1402
return callable(*args, **kwargs)
1404
# record this benchmark
1405
ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
1407
self._benchcalls.append(((callable, args, kwargs), stats))
1410
self._benchtime += time.time() - start
1412
def _runCleanups(self):
1413
"""Run registered cleanup functions.
1415
This should only be called from TestCase.tearDown.
1417
# TODO: Perhaps this should keep running cleanups even if
1418
# one of them fails?
1420
# Actually pop the cleanups from the list so tearDown running
1421
# twice is safe (this happens for skipped tests).
1422
while self._cleanups:
1423
cleanup, args, kwargs = self._cleanups.pop()
1424
cleanup(*args, **kwargs)
1426
def log(self, *args):
1429
def _get_log(self, keep_log_file=False):
1430
"""Get the log from bzrlib.trace calls from this test.
1432
:param keep_log_file: When True, if the log is still a file on disk
1433
leave it as a file on disk. When False, if the log is still a file
1434
on disk, the log file is deleted and the log preserved as
1436
:return: A string containing the log.
1438
# flush the log file, to get all content
1440
if bzrlib.trace._trace_file:
1441
bzrlib.trace._trace_file.flush()
1442
if self._log_contents:
1443
# XXX: this can hardly contain the content flushed above --vila
1445
return self._log_contents
1446
if self._log_file_name is not None:
1447
logfile = open(self._log_file_name)
1449
log_contents = logfile.read()
1452
if not keep_log_file:
1453
self._log_contents = log_contents
1455
os.remove(self._log_file_name)
1457
if sys.platform == 'win32' and e.errno == errno.EACCES:
1458
sys.stderr.write(('Unable to delete log file '
1459
' %r\n' % self._log_file_name))
1464
return "DELETED log file to reduce memory footprint"
1466
def requireFeature(self, feature):
1467
"""This test requires a specific feature is available.
1469
:raises UnavailableFeature: When feature is not available.
1471
if not feature.available():
1472
raise UnavailableFeature(feature)
1474
def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
1476
"""Run bazaar command line, splitting up a string command line."""
1477
if isinstance(args, basestring):
1478
# shlex don't understand unicode strings,
1479
# so args should be plain string (bialix 20070906)
1480
args = list(shlex.split(str(args)))
1481
return self._run_bzr_core(args, retcode=retcode,
1482
encoding=encoding, stdin=stdin, working_dir=working_dir,
1485
def _run_bzr_core(self, args, retcode, encoding, stdin,
1487
if encoding is None:
1488
encoding = osutils.get_user_encoding()
1489
stdout = StringIOWrapper()
1490
stderr = StringIOWrapper()
1491
stdout.encoding = encoding
1492
stderr.encoding = encoding
1494
self.log('run bzr: %r', args)
1495
# FIXME: don't call into logging here
1496
handler = logging.StreamHandler(stderr)
1497
handler.setLevel(logging.INFO)
1498
logger = logging.getLogger('')
1499
logger.addHandler(handler)
1500
old_ui_factory = ui.ui_factory
1501
ui.ui_factory = TestUIFactory(stdin=stdin, stdout=stdout, stderr=stderr)
1504
if working_dir is not None:
1505
cwd = osutils.getcwd()
1506
os.chdir(working_dir)
1509
result = self.apply_redirected(ui.ui_factory.stdin,
1511
bzrlib.commands.run_bzr_catch_user_errors,
1514
logger.removeHandler(handler)
1515
ui.ui_factory = old_ui_factory
1519
out = stdout.getvalue()
1520
err = stderr.getvalue()
1522
self.log('output:\n%r', out)
1524
self.log('errors:\n%r', err)
1525
if retcode is not None:
1526
self.assertEquals(retcode, result,
1527
message='Unexpected return code')
1530
def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
1531
working_dir=None, error_regexes=[], output_encoding=None):
1532
"""Invoke bzr, as if it were run from the command line.
1534
The argument list should not include the bzr program name - the
1535
first argument is normally the bzr command. Arguments may be
1536
passed in three ways:
1538
1- A list of strings, eg ["commit", "a"]. This is recommended
1539
when the command contains whitespace or metacharacters, or
1540
is built up at run time.
1542
2- A single string, eg "add a". This is the most convenient
1543
for hardcoded commands.
1545
This runs bzr through the interface that catches and reports
1546
errors, and with logging set to something approximating the
1547
default, so that error reporting can be checked.
1549
This should be the main method for tests that want to exercise the
1550
overall behavior of the bzr application (rather than a unit test
1551
or a functional test of the library.)
1553
This sends the stdout/stderr results into the test's log,
1554
where it may be useful for debugging. See also run_captured.
1556
:keyword stdin: A string to be used as stdin for the command.
1557
:keyword retcode: The status code the command should return;
1559
:keyword working_dir: The directory to run the command in
1560
:keyword error_regexes: A list of expected error messages. If
1561
specified they must be seen in the error output of the command.
1563
out, err = self._run_bzr_autosplit(
1568
working_dir=working_dir,
1570
for regex in error_regexes:
1571
self.assertContainsRe(err, regex)
1574
def run_bzr_error(self, error_regexes, *args, **kwargs):
1575
"""Run bzr, and check that stderr contains the supplied regexes
1577
:param error_regexes: Sequence of regular expressions which
1578
must each be found in the error output. The relative ordering
1580
:param args: command-line arguments for bzr
1581
:param kwargs: Keyword arguments which are interpreted by run_bzr
1582
This function changes the default value of retcode to be 3,
1583
since in most cases this is run when you expect bzr to fail.
1585
:return: (out, err) The actual output of running the command (in case
1586
you want to do more inspection)
1590
# Make sure that commit is failing because there is nothing to do
1591
self.run_bzr_error(['no changes to commit'],
1592
['commit', '-m', 'my commit comment'])
1593
# Make sure --strict is handling an unknown file, rather than
1594
# giving us the 'nothing to do' error
1595
self.build_tree(['unknown'])
1596
self.run_bzr_error(['Commit refused because there are unknown files'],
1597
['commit', --strict', '-m', 'my commit comment'])
1599
kwargs.setdefault('retcode', 3)
1600
kwargs['error_regexes'] = error_regexes
1601
out, err = self.run_bzr(*args, **kwargs)
1604
def run_bzr_subprocess(self, *args, **kwargs):
1605
"""Run bzr in a subprocess for testing.
1607
This starts a new Python interpreter and runs bzr in there.
1608
This should only be used for tests that have a justifiable need for
1609
this isolation: e.g. they are testing startup time, or signal
1610
handling, or early startup code, etc. Subprocess code can't be
1611
profiled or debugged so easily.
1613
:keyword retcode: The status code that is expected. Defaults to 0. If
1614
None is supplied, the status code is not checked.
1615
:keyword env_changes: A dictionary which lists changes to environment
1616
variables. A value of None will unset the env variable.
1617
The values must be strings. The change will only occur in the
1618
child, so you don't need to fix the environment after running.
1619
:keyword universal_newlines: Convert CRLF => LF
1620
:keyword allow_plugins: By default the subprocess is run with
1621
--no-plugins to ensure test reproducibility. Also, it is possible
1622
for system-wide plugins to create unexpected output on stderr,
1623
which can cause unnecessary test failures.
1625
env_changes = kwargs.get('env_changes', {})
1626
working_dir = kwargs.get('working_dir', None)
1627
allow_plugins = kwargs.get('allow_plugins', False)
1629
if isinstance(args[0], list):
1631
elif isinstance(args[0], basestring):
1632
args = list(shlex.split(args[0]))
1634
raise ValueError("passing varargs to run_bzr_subprocess")
1635
process = self.start_bzr_subprocess(args, env_changes=env_changes,
1636
working_dir=working_dir,
1637
allow_plugins=allow_plugins)
1638
# We distinguish between retcode=None and retcode not passed.
1639
supplied_retcode = kwargs.get('retcode', 0)
1640
return self.finish_bzr_subprocess(process, retcode=supplied_retcode,
1641
universal_newlines=kwargs.get('universal_newlines', False),
1644
def start_bzr_subprocess(self, process_args, env_changes=None,
1645
skip_if_plan_to_signal=False,
1647
allow_plugins=False):
1648
"""Start bzr in a subprocess for testing.
1650
This starts a new Python interpreter and runs bzr in there.
1651
This should only be used for tests that have a justifiable need for
1652
this isolation: e.g. they are testing startup time, or signal
1653
handling, or early startup code, etc. Subprocess code can't be
1654
profiled or debugged so easily.
1656
:param process_args: a list of arguments to pass to the bzr executable,
1657
for example ``['--version']``.
1658
:param env_changes: A dictionary which lists changes to environment
1659
variables. A value of None will unset the env variable.
1660
The values must be strings. The change will only occur in the
1661
child, so you don't need to fix the environment after running.
1662
:param skip_if_plan_to_signal: raise TestSkipped when true and os.kill
1664
:param allow_plugins: If False (default) pass --no-plugins to bzr.
1666
:returns: Popen object for the started process.
1668
if skip_if_plan_to_signal:
1669
if not getattr(os, 'kill', None):
1670
raise TestSkipped("os.kill not available.")
1672
if env_changes is None:
1676
def cleanup_environment():
1677
for env_var, value in env_changes.iteritems():
1678
old_env[env_var] = osutils.set_or_unset_env(env_var, value)
1680
def restore_environment():
1681
for env_var, value in old_env.iteritems():
1682
osutils.set_or_unset_env(env_var, value)
1684
bzr_path = self.get_bzr_path()
1687
if working_dir is not None:
1688
cwd = osutils.getcwd()
1689
os.chdir(working_dir)
1692
# win32 subprocess doesn't support preexec_fn
1693
# so we will avoid using it on all platforms, just to
1694
# make sure the code path is used, and we don't break on win32
1695
cleanup_environment()
1696
command = [sys.executable]
1697
# frozen executables don't need the path to bzr
1698
if getattr(sys, "frozen", None) is None:
1699
command.append(bzr_path)
1700
if not allow_plugins:
1701
command.append('--no-plugins')
1702
command.extend(process_args)
1703
process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
1705
restore_environment()
1711
def _popen(self, *args, **kwargs):
1712
"""Place a call to Popen.
1714
Allows tests to override this method to intercept the calls made to
1715
Popen for introspection.
1717
return Popen(*args, **kwargs)
1719
def get_bzr_path(self):
1720
"""Return the path of the 'bzr' executable for this test suite."""
1721
bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
1722
if not os.path.isfile(bzr_path):
1723
# We are probably installed. Assume sys.argv is the right file
1724
bzr_path = sys.argv[0]
1727
def finish_bzr_subprocess(self, process, retcode=0, send_signal=None,
1728
universal_newlines=False, process_args=None):
1729
"""Finish the execution of process.
1731
:param process: the Popen object returned from start_bzr_subprocess.
1732
:param retcode: The status code that is expected. Defaults to 0. If
1733
None is supplied, the status code is not checked.
1734
:param send_signal: an optional signal to send to the process.
1735
:param universal_newlines: Convert CRLF => LF
1736
:returns: (stdout, stderr)
1738
if send_signal is not None:
1739
os.kill(process.pid, send_signal)
1740
out, err = process.communicate()
1742
if universal_newlines:
1743
out = out.replace('\r\n', '\n')
1744
err = err.replace('\r\n', '\n')
1746
if retcode is not None and retcode != process.returncode:
1747
if process_args is None:
1748
process_args = "(unknown args)"
1749
mutter('Output of bzr %s:\n%s', process_args, out)
1750
mutter('Error for bzr %s:\n%s', process_args, err)
1751
self.fail('Command bzr %s failed with retcode %s != %s'
1752
% (process_args, retcode, process.returncode))
1755
def check_inventory_shape(self, inv, shape):
1756
"""Compare an inventory to a list of expected names.
1758
Fail if they are not precisely equal.
1761
shape = list(shape) # copy
1762
for path, ie in inv.entries():
1763
name = path.replace('\\', '/')
1764
if ie.kind == 'directory':
1771
self.fail("expected paths not found in inventory: %r" % shape)
1773
self.fail("unexpected paths found in inventory: %r" % extras)
1775
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
1776
a_callable=None, *args, **kwargs):
1777
"""Call callable with redirected std io pipes.
1779
Returns the return code."""
1780
if not callable(a_callable):
1781
raise ValueError("a_callable must be callable.")
1783
stdin = StringIO("")
1785
if getattr(self, "_log_file", None) is not None:
1786
stdout = self._log_file
1790
if getattr(self, "_log_file", None is not None):
1791
stderr = self._log_file
1794
real_stdin = sys.stdin
1795
real_stdout = sys.stdout
1796
real_stderr = sys.stderr
1801
return a_callable(*args, **kwargs)
1803
sys.stdout = real_stdout
1804
sys.stderr = real_stderr
1805
sys.stdin = real_stdin
1807
def reduceLockdirTimeout(self):
1808
"""Reduce the default lock timeout for the duration of the test, so that
1809
if LockContention occurs during a test, it does so quickly.
1811
Tests that expect to provoke LockContention errors should call this.
1813
orig_timeout = bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS
1815
bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = orig_timeout
1816
self.addCleanup(resetTimeout)
1817
bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = 0
1819
def make_utf8_encoded_stringio(self, encoding_type=None):
1820
"""Return a StringIOWrapper instance, that will encode Unicode
1823
if encoding_type is None:
1824
encoding_type = 'strict'
1826
output_encoding = 'utf-8'
1827
sio = codecs.getwriter(output_encoding)(sio, errors=encoding_type)
1828
sio.encoding = output_encoding
1832
class CapturedCall(object):
1833
"""A helper for capturing smart server calls for easy debug analysis."""
1835
def __init__(self, params, prefix_length):
1836
"""Capture the call with params and skip prefix_length stack frames."""
1839
# The last 5 frames are the __init__, the hook frame, and 3 smart
1840
# client frames. Beyond this we could get more clever, but this is good
1842
stack = traceback.extract_stack()[prefix_length:-5]
1843
self.stack = ''.join(traceback.format_list(stack))
1846
return self.call.method
1849
return self.call.method
1855
class TestCaseWithMemoryTransport(TestCase):
1856
"""Common test class for tests that do not need disk resources.
1858
Tests that need disk resources should derive from TestCaseWithTransport.
1860
TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
1862
For TestCaseWithMemoryTransport the test_home_dir is set to the name of
1863
a directory which does not exist. This serves to help ensure test isolation
1864
is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
1865
must exist. However, TestCaseWithMemoryTransport does not offer local
1866
file defaults for the transport in tests, nor does it obey the command line
1867
override, so tests that accidentally write to the common directory should
1870
:cvar TEST_ROOT: Directory containing all temporary directories, plus
1871
a .bzr directory that stops us ascending higher into the filesystem.
1877
def __init__(self, methodName='runTest'):
1878
# allow test parameterization after test construction and before test
1879
# execution. Variables that the parameterizer sets need to be
1880
# ones that are not set by setUp, or setUp will trash them.
1881
super(TestCaseWithMemoryTransport, self).__init__(methodName)
1882
self.vfs_transport_factory = default_transport
1883
self.transport_server = None
1884
self.transport_readonly_server = None
1885
self.__vfs_server = None
1887
def get_transport(self, relpath=None):
1888
"""Return a writeable transport.
1890
This transport is for the test scratch space relative to
1893
:param relpath: a path relative to the base url.
1895
t = get_transport(self.get_url(relpath))
1896
self.assertFalse(t.is_readonly())
1899
def get_readonly_transport(self, relpath=None):
1900
"""Return a readonly transport for the test scratch space
1902
This can be used to test that operations which should only need
1903
readonly access in fact do not try to write.
1905
:param relpath: a path relative to the base url.
1907
t = get_transport(self.get_readonly_url(relpath))
1908
self.assertTrue(t.is_readonly())
1911
def create_transport_readonly_server(self):
1912
"""Create a transport server from class defined at init.
1914
This is mostly a hook for daughter classes.
1916
return self.transport_readonly_server()
1918
def get_readonly_server(self):
1919
"""Get the server instance for the readonly transport
1921
This is useful for some tests with specific servers to do diagnostics.
1923
if self.__readonly_server is None:
1924
if self.transport_readonly_server is None:
1925
# readonly decorator requested
1926
# bring up the server
1927
self.__readonly_server = ReadonlyServer()
1928
self.__readonly_server.setUp(self.get_vfs_only_server())
1930
self.__readonly_server = self.create_transport_readonly_server()
1931
self.__readonly_server.setUp(self.get_vfs_only_server())
1932
self.addCleanup(self.__readonly_server.tearDown)
1933
return self.__readonly_server
1935
def get_readonly_url(self, relpath=None):
1936
"""Get a URL for the readonly transport.
1938
This will either be backed by '.' or a decorator to the transport
1939
used by self.get_url()
1940
relpath provides for clients to get a path relative to the base url.
1941
These should only be downwards relative, not upwards.
1943
base = self.get_readonly_server().get_url()
1944
return self._adjust_url(base, relpath)
1946
def get_vfs_only_server(self):
1947
"""Get the vfs only read/write server instance.
1949
This is useful for some tests with specific servers that need
1952
For TestCaseWithMemoryTransport this is always a MemoryServer, and there
1953
is no means to override it.
1955
if self.__vfs_server is None:
1956
self.__vfs_server = MemoryServer()
1957
self.__vfs_server.setUp()
1958
self.addCleanup(self.__vfs_server.tearDown)
1959
return self.__vfs_server
1961
def get_server(self):
1962
"""Get the read/write server instance.
1964
This is useful for some tests with specific servers that need
1967
This is built from the self.transport_server factory. If that is None,
1968
then the self.get_vfs_server is returned.
1970
if self.__server is None:
1971
if self.transport_server is None or self.transport_server is self.vfs_transport_factory:
1972
return self.get_vfs_only_server()
1974
# bring up a decorated means of access to the vfs only server.
1975
self.__server = self.transport_server()
1977
self.__server.setUp(self.get_vfs_only_server())
1978
except TypeError, e:
1979
# This should never happen; the try:Except here is to assist
1980
# developers having to update code rather than seeing an
1981
# uninformative TypeError.
1982
raise Exception, "Old server API in use: %s, %s" % (self.__server, e)
1983
self.addCleanup(self.__server.tearDown)
1984
return self.__server
1986
def _adjust_url(self, base, relpath):
1987
"""Get a URL (or maybe a path) for the readwrite transport.
1989
This will either be backed by '.' or to an equivalent non-file based
1991
relpath provides for clients to get a path relative to the base url.
1992
These should only be downwards relative, not upwards.
1994
if relpath is not None and relpath != '.':
1995
if not base.endswith('/'):
1997
# XXX: Really base should be a url; we did after all call
1998
# get_url()! But sometimes it's just a path (from
1999
# LocalAbspathServer), and it'd be wrong to append urlescaped data
2000
# to a non-escaped local path.
2001
if base.startswith('./') or base.startswith('/'):
2004
base += urlutils.escape(relpath)
2007
def get_url(self, relpath=None):
2008
"""Get a URL (or maybe a path) for the readwrite transport.
2010
This will either be backed by '.' or to an equivalent non-file based
2012
relpath provides for clients to get a path relative to the base url.
2013
These should only be downwards relative, not upwards.
2015
base = self.get_server().get_url()
2016
return self._adjust_url(base, relpath)
2018
def get_vfs_only_url(self, relpath=None):
2019
"""Get a URL (or maybe a path for the plain old vfs transport.
2021
This will never be a smart protocol. It always has all the
2022
capabilities of the local filesystem, but it might actually be a
2023
MemoryTransport or some other similar virtual filesystem.
2025
This is the backing transport (if any) of the server returned by
2026
get_url and get_readonly_url.
2028
:param relpath: provides for clients to get a path relative to the base
2029
url. These should only be downwards relative, not upwards.
2032
base = self.get_vfs_only_server().get_url()
2033
return self._adjust_url(base, relpath)
2035
def _create_safety_net(self):
2036
"""Make a fake bzr directory.
2038
This prevents any tests propagating up onto the TEST_ROOT directory's
2041
root = TestCaseWithMemoryTransport.TEST_ROOT
2042
bzrdir.BzrDir.create_standalone_workingtree(root)
2044
def _check_safety_net(self):
2045
"""Check that the safety .bzr directory have not been touched.
2047
_make_test_root have created a .bzr directory to prevent tests from
2048
propagating. This method ensures than a test did not leaked.
2050
root = TestCaseWithMemoryTransport.TEST_ROOT
2051
wt = workingtree.WorkingTree.open(root)
2052
last_rev = wt.last_revision()
2053
if last_rev != 'null:':
2054
# The current test have modified the /bzr directory, we need to
2055
# recreate a new one or all the followng tests will fail.
2056
# If you need to inspect its content uncomment the following line
2057
# import pdb; pdb.set_trace()
2058
_rmtree_temp_dir(root + '/.bzr')
2059
self._create_safety_net()
2060
raise AssertionError('%s/.bzr should not be modified' % root)
2062
def _make_test_root(self):
2063
if TestCaseWithMemoryTransport.TEST_ROOT is None:
2064
root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
2065
TestCaseWithMemoryTransport.TEST_ROOT = root
2067
self._create_safety_net()
2069
# The same directory is used by all tests, and we're not
2070
# specifically told when all tests are finished. This will do.
2071
atexit.register(_rmtree_temp_dir, root)
2073
self.addCleanup(self._check_safety_net)
2075
def makeAndChdirToTestDir(self):
2076
"""Create a temporary directories for this one test.
2078
This must set self.test_home_dir and self.test_dir and chdir to
2081
For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this test.
2083
os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2084
self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
2085
self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
2087
def make_branch(self, relpath, format=None):
2088
"""Create a branch on the transport at relpath."""
2089
repo = self.make_repository(relpath, format=format)
2090
return repo.bzrdir.create_branch()
2092
def make_bzrdir(self, relpath, format=None):
2094
# might be a relative or absolute path
2095
maybe_a_url = self.get_url(relpath)
2096
segments = maybe_a_url.rsplit('/', 1)
2097
t = get_transport(maybe_a_url)
2098
if len(segments) > 1 and segments[-1] not in ('', '.'):
2102
if isinstance(format, basestring):
2103
format = bzrdir.format_registry.make_bzrdir(format)
2104
return format.initialize_on_transport(t)
2105
except errors.UninitializableFormat:
2106
raise TestSkipped("Format %s is not initializable." % format)
2108
def make_repository(self, relpath, shared=False, format=None):
2109
"""Create a repository on our default transport at relpath.
2111
Note that relpath must be a relative path, not a full url.
2113
# FIXME: If you create a remoterepository this returns the underlying
2114
# real format, which is incorrect. Actually we should make sure that
2115
# RemoteBzrDir returns a RemoteRepository.
2116
# maybe mbp 20070410
2117
made_control = self.make_bzrdir(relpath, format=format)
2118
return made_control.create_repository(shared=shared)
2120
def make_smart_server(self, path):
2121
smart_server = server.SmartTCPServer_for_testing()
2122
smart_server.setUp(self.get_server())
2123
remote_transport = get_transport(smart_server.get_url()).clone(path)
2124
self.addCleanup(smart_server.tearDown)
2125
return remote_transport
2127
def make_branch_and_memory_tree(self, relpath, format=None):
2128
"""Create a branch on the default transport and a MemoryTree for it."""
2129
b = self.make_branch(relpath, format=format)
2130
return memorytree.MemoryTree.create_on_branch(b)
2132
def make_branch_builder(self, relpath, format=None):
2133
return branchbuilder.BranchBuilder(self.get_transport(relpath),
2136
def overrideEnvironmentForTesting(self):
2137
os.environ['HOME'] = self.test_home_dir
2138
os.environ['BZR_HOME'] = self.test_home_dir
2141
super(TestCaseWithMemoryTransport, self).setUp()
2142
self._make_test_root()
2143
_currentdir = os.getcwdu()
2144
def _leaveDirectory():
2145
os.chdir(_currentdir)
2146
self.addCleanup(_leaveDirectory)
2147
self.makeAndChdirToTestDir()
2148
self.overrideEnvironmentForTesting()
2149
self.__readonly_server = None
2150
self.__server = None
2151
self.reduceLockdirTimeout()
2153
def setup_smart_server_with_call_log(self):
2154
"""Sets up a smart server as the transport server with a call log."""
2155
self.transport_server = server.SmartTCPServer_for_testing
2156
self.hpss_calls = []
2158
# Skip the current stack down to the caller of
2159
# setup_smart_server_with_call_log
2160
prefix_length = len(traceback.extract_stack()) - 2
2161
def capture_hpss_call(params):
2162
self.hpss_calls.append(
2163
CapturedCall(params, prefix_length))
2164
client._SmartClient.hooks.install_named_hook(
2165
'call', capture_hpss_call, None)
2167
def reset_smart_call_log(self):
2168
self.hpss_calls = []
2171
class TestCaseInTempDir(TestCaseWithMemoryTransport):
2172
"""Derived class that runs a test within a temporary directory.
2174
This is useful for tests that need to create a branch, etc.
2176
The directory is created in a slightly complex way: for each
2177
Python invocation, a new temporary top-level directory is created.
2178
All test cases create their own directory within that. If the
2179
tests complete successfully, the directory is removed.
2181
:ivar test_base_dir: The path of the top-level directory for this
2182
test, which contains a home directory and a work directory.
2184
:ivar test_home_dir: An initially empty directory under test_base_dir
2185
which is used as $HOME for this test.
2187
:ivar test_dir: A directory under test_base_dir used as the current
2188
directory when the test proper is run.
2191
OVERRIDE_PYTHON = 'python'
2193
def check_file_contents(self, filename, expect):
2194
self.log("check contents of file %s" % filename)
2195
contents = file(filename, 'r').read()
2196
if contents != expect:
2197
self.log("expected: %r" % expect)
2198
self.log("actually: %r" % contents)
2199
self.fail("contents of %s not as expected" % filename)
2201
def _getTestDirPrefix(self):
2202
# create a directory within the top level test directory
2203
if sys.platform == 'win32':
2204
name_prefix = re.sub('[<>*=+",:;_/\\-]', '_', self.id())
2205
# windows is likely to have path-length limits so use a short name
2206
name_prefix = name_prefix[-30:]
2208
name_prefix = re.sub('[/]', '_', self.id())
2211
def makeAndChdirToTestDir(self):
2212
"""See TestCaseWithMemoryTransport.makeAndChdirToTestDir().
2214
For TestCaseInTempDir we create a temporary directory based on the test
2215
name and then create two subdirs - test and home under it.
2217
name_prefix = osutils.pathjoin(TestCaseWithMemoryTransport.TEST_ROOT,
2218
self._getTestDirPrefix())
2220
for i in range(100):
2221
if os.path.exists(name):
2222
name = name_prefix + '_' + str(i)
2226
# now create test and home directories within this dir
2227
self.test_base_dir = name
2228
self.test_home_dir = self.test_base_dir + '/home'
2229
os.mkdir(self.test_home_dir)
2230
self.test_dir = self.test_base_dir + '/work'
2231
os.mkdir(self.test_dir)
2232
os.chdir(self.test_dir)
2233
# put name of test inside
2234
f = file(self.test_base_dir + '/name', 'w')
2239
self.addCleanup(self.deleteTestDir)
2241
def deleteTestDir(self):
2242
os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2243
_rmtree_temp_dir(self.test_base_dir)
2245
def build_tree(self, shape, line_endings='binary', transport=None):
2246
"""Build a test tree according to a pattern.
2248
shape is a sequence of file specifications. If the final
2249
character is '/', a directory is created.
2251
This assumes that all the elements in the tree being built are new.
2253
This doesn't add anything to a branch.
2255
:type shape: list or tuple.
2256
:param line_endings: Either 'binary' or 'native'
2257
in binary mode, exact contents are written in native mode, the
2258
line endings match the default platform endings.
2259
:param transport: A transport to write to, for building trees on VFS's.
2260
If the transport is readonly or None, "." is opened automatically.
2263
if type(shape) not in (list, tuple):
2264
raise AssertionError("Parameter 'shape' should be "
2265
"a list or a tuple. Got %r instead" % (shape,))
2266
# It's OK to just create them using forward slashes on windows.
2267
if transport is None or transport.is_readonly():
2268
transport = get_transport(".")
2270
self.assertIsInstance(name, basestring)
2272
transport.mkdir(urlutils.escape(name[:-1]))
2274
if line_endings == 'binary':
2276
elif line_endings == 'native':
2279
raise errors.BzrError(
2280
'Invalid line ending request %r' % line_endings)
2281
content = "contents of %s%s" % (name.encode('utf-8'), end)
2282
transport.put_bytes_non_atomic(urlutils.escape(name), content)
2284
def build_tree_contents(self, shape):
2285
build_tree_contents(shape)
2287
def assertInWorkingTree(self, path, root_path='.', tree=None):
2288
"""Assert whether path or paths are in the WorkingTree"""
2290
tree = workingtree.WorkingTree.open(root_path)
2291
if not isinstance(path, basestring):
2293
self.assertInWorkingTree(p, tree=tree)
2295
self.assertIsNot(tree.path2id(path), None,
2296
path+' not in working tree.')
2298
def assertNotInWorkingTree(self, path, root_path='.', tree=None):
2299
"""Assert whether path or paths are not in the WorkingTree"""
2301
tree = workingtree.WorkingTree.open(root_path)
2302
if not isinstance(path, basestring):
2304
self.assertNotInWorkingTree(p,tree=tree)
2306
self.assertIs(tree.path2id(path), None, path+' in working tree.')
2309
class TestCaseWithTransport(TestCaseInTempDir):
2310
"""A test case that provides get_url and get_readonly_url facilities.
2312
These back onto two transport servers, one for readonly access and one for
2315
If no explicit class is provided for readonly access, a
2316
ReadonlyTransportDecorator is used instead which allows the use of non disk
2317
based read write transports.
2319
If an explicit class is provided for readonly access, that server and the
2320
readwrite one must both define get_url() as resolving to os.getcwd().
2323
def get_vfs_only_server(self):
2324
"""See TestCaseWithMemoryTransport.
2326
This is useful for some tests with specific servers that need
2329
if self.__vfs_server is None:
2330
self.__vfs_server = self.vfs_transport_factory()
2331
self.__vfs_server.setUp()
2332
self.addCleanup(self.__vfs_server.tearDown)
2333
return self.__vfs_server
2335
def make_branch_and_tree(self, relpath, format=None):
2336
"""Create a branch on the transport and a tree locally.
2338
If the transport is not a LocalTransport, the Tree can't be created on
2339
the transport. In that case if the vfs_transport_factory is
2340
LocalURLServer the working tree is created in the local
2341
directory backing the transport, and the returned tree's branch and
2342
repository will also be accessed locally. Otherwise a lightweight
2343
checkout is created and returned.
2345
:param format: The BzrDirFormat.
2346
:returns: the WorkingTree.
2348
# TODO: always use the local disk path for the working tree,
2349
# this obviously requires a format that supports branch references
2350
# so check for that by checking bzrdir.BzrDirFormat.get_default_format()
2352
b = self.make_branch(relpath, format=format)
2354
return b.bzrdir.create_workingtree()
2355
except errors.NotLocalUrl:
2356
# We can only make working trees locally at the moment. If the
2357
# transport can't support them, then we keep the non-disk-backed
2358
# branch and create a local checkout.
2359
if self.vfs_transport_factory is LocalURLServer:
2360
# the branch is colocated on disk, we cannot create a checkout.
2361
# hopefully callers will expect this.
2362
local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
2363
wt = local_controldir.create_workingtree()
2364
if wt.branch._format != b._format:
2366
# Make sure that assigning to wt._branch fixes wt.branch,
2367
# in case the implementation details of workingtree objects
2369
self.assertIs(b, wt.branch)
2372
return b.create_checkout(relpath, lightweight=True)
2374
def assertIsDirectory(self, relpath, transport):
2375
"""Assert that relpath within transport is a directory.
2377
This may not be possible on all transports; in that case it propagates
2378
a TransportNotPossible.
2381
mode = transport.stat(relpath).st_mode
2382
except errors.NoSuchFile:
2383
self.fail("path %s is not a directory; no such file"
2385
if not stat.S_ISDIR(mode):
2386
self.fail("path %s is not a directory; has mode %#o"
2389
def assertTreesEqual(self, left, right):
2390
"""Check that left and right have the same content and properties."""
2391
# we use a tree delta to check for equality of the content, and we
2392
# manually check for equality of other things such as the parents list.
2393
self.assertEqual(left.get_parent_ids(), right.get_parent_ids())
2394
differences = left.changes_from(right)
2395
self.assertFalse(differences.has_changed(),
2396
"Trees %r and %r are different: %r" % (left, right, differences))
2399
super(TestCaseWithTransport, self).setUp()
2400
self.__vfs_server = None
2403
class ChrootedTestCase(TestCaseWithTransport):
2404
"""A support class that provides readonly urls outside the local namespace.
2406
This is done by checking if self.transport_server is a MemoryServer. if it
2407
is then we are chrooted already, if it is not then an HttpServer is used
2410
TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
2411
be used without needed to redo it when a different
2412
subclass is in use ?
2416
super(ChrootedTestCase, self).setUp()
2417
if not self.vfs_transport_factory == MemoryServer:
2418
self.transport_readonly_server = HttpServer
2421
def condition_id_re(pattern):
2422
"""Create a condition filter which performs a re check on a test's id.
2424
:param pattern: A regular expression string.
2425
:return: A callable that returns True if the re matches.
2427
filter_re = osutils.re_compile_checked(pattern, 0,
2429
def condition(test):
2431
return filter_re.search(test_id)
2435
def condition_isinstance(klass_or_klass_list):
2436
"""Create a condition filter which returns isinstance(param, klass).
2438
:return: A callable which when called with one parameter obj return the
2439
result of isinstance(obj, klass_or_klass_list).
2442
return isinstance(obj, klass_or_klass_list)
2446
def condition_id_in_list(id_list):
2447
"""Create a condition filter which verify that test's id in a list.
2449
:param id_list: A TestIdList object.
2450
:return: A callable that returns True if the test's id appears in the list.
2452
def condition(test):
2453
return id_list.includes(test.id())
2457
def condition_id_startswith(starts):
2458
"""Create a condition filter verifying that test's id starts with a string.
2460
:param starts: A list of string.
2461
:return: A callable that returns True if the test's id starts with one of
2464
def condition(test):
2465
for start in starts:
2466
if test.id().startswith(start):
2472
def exclude_tests_by_condition(suite, condition):
2473
"""Create a test suite which excludes some tests from suite.
2475
:param suite: The suite to get tests from.
2476
:param condition: A callable whose result evaluates True when called with a
2477
test case which should be excluded from the result.
2478
:return: A suite which contains the tests found in suite that fail
2482
for test in iter_suite_tests(suite):
2483
if not condition(test):
2485
return TestUtil.TestSuite(result)
2488
def filter_suite_by_condition(suite, condition):
2489
"""Create a test suite by filtering another one.
2491
:param suite: The source suite.
2492
:param condition: A callable whose result evaluates True when called with a
2493
test case which should be included in the result.
2494
:return: A suite which contains the tests found in suite that pass
2498
for test in iter_suite_tests(suite):
2501
return TestUtil.TestSuite(result)
2504
def filter_suite_by_re(suite, pattern):
2505
"""Create a test suite by filtering another one.
2507
:param suite: the source suite
2508
:param pattern: pattern that names must match
2509
:returns: the newly created suite
2511
condition = condition_id_re(pattern)
2512
result_suite = filter_suite_by_condition(suite, condition)
2516
def filter_suite_by_id_list(suite, test_id_list):
2517
"""Create a test suite by filtering another one.
2519
:param suite: The source suite.
2520
:param test_id_list: A list of the test ids to keep as strings.
2521
:returns: the newly created suite
2523
condition = condition_id_in_list(test_id_list)
2524
result_suite = filter_suite_by_condition(suite, condition)
2528
def filter_suite_by_id_startswith(suite, start):
2529
"""Create a test suite by filtering another one.
2531
:param suite: The source suite.
2532
:param start: A list of string the test id must start with one of.
2533
:returns: the newly created suite
2535
condition = condition_id_startswith(start)
2536
result_suite = filter_suite_by_condition(suite, condition)
2540
def exclude_tests_by_re(suite, pattern):
2541
"""Create a test suite which excludes some tests from suite.
2543
:param suite: The suite to get tests from.
2544
:param pattern: A regular expression string. Test ids that match this
2545
pattern will be excluded from the result.
2546
:return: A TestSuite that contains all the tests from suite without the
2547
tests that matched pattern. The order of tests is the same as it was in
2550
return exclude_tests_by_condition(suite, condition_id_re(pattern))
2553
def preserve_input(something):
2554
"""A helper for performing test suite transformation chains.
2556
:param something: Anything you want to preserve.
2562
def randomize_suite(suite):
2563
"""Return a new TestSuite with suite's tests in random order.
2565
The tests in the input suite are flattened into a single suite in order to
2566
accomplish this. Any nested TestSuites are removed to provide global
2569
tests = list(iter_suite_tests(suite))
2570
random.shuffle(tests)
2571
return TestUtil.TestSuite(tests)
2574
def split_suite_by_condition(suite, condition):
2575
"""Split a test suite into two by a condition.
2577
:param suite: The suite to split.
2578
:param condition: The condition to match on. Tests that match this
2579
condition are returned in the first test suite, ones that do not match
2580
are in the second suite.
2581
:return: A tuple of two test suites, where the first contains tests from
2582
suite matching the condition, and the second contains the remainder
2583
from suite. The order within each output suite is the same as it was in
2588
for test in iter_suite_tests(suite):
2590
matched.append(test)
2592
did_not_match.append(test)
2593
return TestUtil.TestSuite(matched), TestUtil.TestSuite(did_not_match)
2596
def split_suite_by_re(suite, pattern):
2597
"""Split a test suite into two by a regular expression.
2599
:param suite: The suite to split.
2600
:param pattern: A regular expression string. Test ids that match this
2601
pattern will be in the first test suite returned, and the others in the
2602
second test suite returned.
2603
:return: A tuple of two test suites, where the first contains tests from
2604
suite matching pattern, and the second contains the remainder from
2605
suite. The order within each output suite is the same as it was in
2608
return split_suite_by_condition(suite, condition_id_re(pattern))
2611
def run_suite(suite, name='test', verbose=False, pattern=".*",
2612
stop_on_failure=False,
2613
transport=None, lsprof_timed=None, bench_history=None,
2614
matching_tests_first=None,
2617
exclude_pattern=None,
2620
suite_decorators=None):
2621
"""Run a test suite for bzr selftest.
2623
:param runner_class: The class of runner to use. Must support the
2624
constructor arguments passed by run_suite which are more than standard
2626
:return: A boolean indicating success.
2628
TestCase._gather_lsprof_in_benchmarks = lsprof_timed
2633
if runner_class is None:
2634
runner_class = TextTestRunner
2635
runner = runner_class(stream=sys.stdout,
2637
verbosity=verbosity,
2638
bench_history=bench_history,
2639
list_only=list_only,
2641
runner.stop_on_failure=stop_on_failure
2642
# built in decorator factories:
2644
random_order(random_seed, runner),
2645
exclude_tests(exclude_pattern),
2647
if matching_tests_first:
2648
decorators.append(tests_first(pattern))
2650
decorators.append(filter_tests(pattern))
2651
if suite_decorators:
2652
decorators.extend(suite_decorators)
2653
for decorator in decorators:
2654
suite = decorator(suite)
2655
result = runner.run(suite)
2657
return result.wasStrictlySuccessful()
2659
return result.wasSuccessful()
2662
# A registry where get() returns a suite decorator.
2663
parallel_registry = registry.Registry()
2666
def fork_decorator(suite):
2667
concurrency = local_concurrency()
2668
if concurrency == 1:
2670
from testtools import ConcurrentTestSuite
2671
return ConcurrentTestSuite(suite, fork_for_tests)
2672
parallel_registry.register('fork', fork_decorator)
2675
def subprocess_decorator(suite):
2676
concurrency = local_concurrency()
2677
if concurrency == 1:
2679
from testtools import ConcurrentTestSuite
2680
return ConcurrentTestSuite(suite, reinvoke_for_tests)
2681
parallel_registry.register('subprocess', subprocess_decorator)
2684
def exclude_tests(exclude_pattern):
2685
"""Return a test suite decorator that excludes tests."""
2686
if exclude_pattern is None:
2687
return identity_decorator
2688
def decorator(suite):
2689
return ExcludeDecorator(suite, exclude_pattern)
2693
def filter_tests(pattern):
2695
return identity_decorator
2696
def decorator(suite):
2697
return FilterTestsDecorator(suite, pattern)
2701
def random_order(random_seed, runner):
2702
"""Return a test suite decorator factory for randomising tests order.
2704
:param random_seed: now, a string which casts to a long, or a long.
2705
:param runner: A test runner with a stream attribute to report on.
2707
if random_seed is None:
2708
return identity_decorator
2709
def decorator(suite):
2710
return RandomDecorator(suite, random_seed, runner.stream)
2714
def tests_first(pattern):
2716
return identity_decorator
2717
def decorator(suite):
2718
return TestFirstDecorator(suite, pattern)
2722
def identity_decorator(suite):
2727
class TestDecorator(TestSuite):
2728
"""A decorator for TestCase/TestSuite objects.
2730
Usually, subclasses should override __iter__(used when flattening test
2731
suites), which we do to filter, reorder, parallelise and so on, run() and
2735
def __init__(self, suite):
2736
TestSuite.__init__(self)
2739
def countTestCases(self):
2742
cases += test.countTestCases()
2749
def run(self, result):
2750
# Use iteration on self, not self._tests, to allow subclasses to hook
2753
if result.shouldStop:
2759
class ExcludeDecorator(TestDecorator):
2760
"""A decorator which excludes test matching an exclude pattern."""
2762
def __init__(self, suite, exclude_pattern):
2763
TestDecorator.__init__(self, suite)
2764
self.exclude_pattern = exclude_pattern
2765
self.excluded = False
2769
return iter(self._tests)
2770
self.excluded = True
2771
suite = exclude_tests_by_re(self, self.exclude_pattern)
2773
self.addTests(suite)
2774
return iter(self._tests)
2777
class FilterTestsDecorator(TestDecorator):
2778
"""A decorator which filters tests to those matching a pattern."""
2780
def __init__(self, suite, pattern):
2781
TestDecorator.__init__(self, suite)
2782
self.pattern = pattern
2783
self.filtered = False
2787
return iter(self._tests)
2788
self.filtered = True
2789
suite = filter_suite_by_re(self, self.pattern)
2791
self.addTests(suite)
2792
return iter(self._tests)
2795
class RandomDecorator(TestDecorator):
2796
"""A decorator which randomises the order of its tests."""
2798
def __init__(self, suite, random_seed, stream):
2799
TestDecorator.__init__(self, suite)
2800
self.random_seed = random_seed
2801
self.randomised = False
2802
self.stream = stream
2806
return iter(self._tests)
2807
self.randomised = True
2808
self.stream.writeln("Randomizing test order using seed %s\n" %
2809
(self.actual_seed()))
2810
# Initialise the random number generator.
2811
random.seed(self.actual_seed())
2812
suite = randomize_suite(self)
2814
self.addTests(suite)
2815
return iter(self._tests)
2817
def actual_seed(self):
2818
if self.random_seed == "now":
2819
# We convert the seed to a long to make it reuseable across
2820
# invocations (because the user can reenter it).
2821
self.random_seed = long(time.time())
2823
# Convert the seed to a long if we can
2825
self.random_seed = long(self.random_seed)
2828
return self.random_seed
2831
class TestFirstDecorator(TestDecorator):
2832
"""A decorator which moves named tests to the front."""
2834
def __init__(self, suite, pattern):
2835
TestDecorator.__init__(self, suite)
2836
self.pattern = pattern
2837
self.filtered = False
2841
return iter(self._tests)
2842
self.filtered = True
2843
suites = split_suite_by_re(self, self.pattern)
2845
self.addTests(suites)
2846
return iter(self._tests)
2849
def partition_tests(suite, count):
2850
"""Partition suite into count lists of tests."""
2852
tests = list(iter_suite_tests(suite))
2853
tests_per_process = int(math.ceil(float(len(tests)) / count))
2854
for block in range(count):
2855
low_test = block * tests_per_process
2856
high_test = low_test + tests_per_process
2857
process_tests = tests[low_test:high_test]
2858
result.append(process_tests)
2862
def fork_for_tests(suite):
2863
"""Take suite and start up one runner per CPU by forking()
2865
:return: An iterable of TestCase-like objects which can each have
2866
run(result) called on them to feed tests to result.
2868
concurrency = local_concurrency()
2870
from subunit import TestProtocolClient, ProtocolTestCase
2871
class TestInOtherProcess(ProtocolTestCase):
2872
# Should be in subunit, I think. RBC.
2873
def __init__(self, stream, pid):
2874
ProtocolTestCase.__init__(self, stream)
2877
def run(self, result):
2879
ProtocolTestCase.run(self, result)
2881
os.waitpid(self.pid, os.WNOHANG)
2883
test_blocks = partition_tests(suite, concurrency)
2884
for process_tests in test_blocks:
2885
process_suite = TestSuite()
2886
process_suite.addTests(process_tests)
2887
c2pread, c2pwrite = os.pipe()
2892
# Leave stderr and stdout open so we can see test noise
2893
# Close stdin so that the child goes away if it decides to
2894
# read from stdin (otherwise its a roulette to see what
2895
# child actually gets keystrokes for pdb etc).
2898
stream = os.fdopen(c2pwrite, 'wb', 1)
2899
subunit_result = TestProtocolClient(stream)
2900
process_suite.run(subunit_result)
2905
stream = os.fdopen(c2pread, 'rb', 1)
2906
test = TestInOtherProcess(stream, pid)
2911
def reinvoke_for_tests(suite):
2912
"""Take suite and start up one runner per CPU using subprocess().
2914
:return: An iterable of TestCase-like objects which can each have
2915
run(result) called on them to feed tests to result.
2917
concurrency = local_concurrency()
2919
from subunit import TestProtocolClient, ProtocolTestCase
2920
class TestInSubprocess(ProtocolTestCase):
2921
def __init__(self, process, name):
2922
ProtocolTestCase.__init__(self, process.stdout)
2923
self.process = process
2924
self.process.stdin.close()
2927
def run(self, result):
2929
ProtocolTestCase.run(self, result)
2932
os.unlink(self.name)
2933
# print "pid %d finished" % finished_process
2934
test_blocks = partition_tests(suite, concurrency)
2935
for process_tests in test_blocks:
2936
# ugly; currently reimplement rather than reuses TestCase methods.
2937
bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
2938
if not os.path.isfile(bzr_path):
2939
# We are probably installed. Assume sys.argv is the right file
2940
bzr_path = sys.argv[0]
2941
fd, test_list_file_name = tempfile.mkstemp()
2942
test_list_file = os.fdopen(fd, 'wb', 1)
2943
for test in process_tests:
2944
test_list_file.write(test.id() + '\n')
2945
test_list_file.close()
2947
argv = [bzr_path, 'selftest', '--load-list', test_list_file_name,
2949
if '--no-plugins' in sys.argv:
2950
argv.append('--no-plugins')
2951
# stderr=STDOUT would be ideal, but until we prevent noise on
2952
# stderr it can interrupt the subunit protocol.
2953
process = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE,
2955
test = TestInSubprocess(process, test_list_file_name)
2958
os.unlink(test_list_file_name)
2963
def cpucount(content):
2964
lines = content.splitlines()
2965
prefix = 'processor'
2967
if line.startswith(prefix):
2968
concurrency = int(line[line.find(':')+1:]) + 1
2972
def local_concurrency():
2974
content = file('/proc/cpuinfo', 'rb').read()
2975
concurrency = cpucount(content)
2976
except Exception, e:
2981
class BZRTransformingResult(unittest.TestResult):
2983
def __init__(self, target):
2984
unittest.TestResult.__init__(self)
2985
self.result = target
2987
def startTest(self, test):
2988
self.result.startTest(test)
2990
def stopTest(self, test):
2991
self.result.stopTest(test)
2993
def addError(self, test, err):
2994
feature = self._error_looks_like('UnavailableFeature: ', err)
2995
if feature is not None:
2996
self.result.addNotSupported(test, feature)
2998
self.result.addError(test, err)
3000
def addFailure(self, test, err):
3001
known = self._error_looks_like('KnownFailure: ', err)
3002
if known is not None:
3003
self.result._addKnownFailure(test, [KnownFailure,
3004
KnownFailure(known), None])
3006
self.result.addFailure(test, err)
3008
def addSkip(self, test, reason):
3009
self.result.addSkip(test, reason)
3011
def addSuccess(self, test):
3012
self.result.addSuccess(test)
3014
def _error_looks_like(self, prefix, err):
3015
"""Deserialize exception and returns the stringify value."""
3019
if isinstance(exc, subunit.RemoteException):
3020
# stringify the exception gives access to the remote traceback
3021
# We search the last line for 'prefix'
3022
lines = str(exc).split('\n')
3024
last = lines[-2] # -1 is empty, final \n
3027
if last.startswith(prefix):
3028
value = last[len(prefix):]
3032
# Controlled by "bzr selftest -E=..." option
3033
selftest_debug_flags = set()
3036
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
3038
test_suite_factory=None,
3041
matching_tests_first=None,
3044
exclude_pattern=None,
3050
suite_decorators=None,
3052
"""Run the whole test suite under the enhanced runner"""
3053
# XXX: Very ugly way to do this...
3054
# Disable warning about old formats because we don't want it to disturb
3055
# any blackbox tests.
3056
from bzrlib import repository
3057
repository._deprecation_warning_done = True
3059
global default_transport
3060
if transport is None:
3061
transport = default_transport
3062
old_transport = default_transport
3063
default_transport = transport
3064
global selftest_debug_flags
3065
old_debug_flags = selftest_debug_flags
3066
if debug_flags is not None:
3067
selftest_debug_flags = set(debug_flags)
3069
if load_list is None:
3072
keep_only = load_test_id_list(load_list)
3073
if test_suite_factory is None:
3074
suite = test_suite(keep_only, starting_with)
3076
suite = test_suite_factory()
3077
return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
3078
stop_on_failure=stop_on_failure,
3079
transport=transport,
3080
lsprof_timed=lsprof_timed,
3081
bench_history=bench_history,
3082
matching_tests_first=matching_tests_first,
3083
list_only=list_only,
3084
random_seed=random_seed,
3085
exclude_pattern=exclude_pattern,
3087
runner_class=runner_class,
3088
suite_decorators=suite_decorators,
3091
default_transport = old_transport
3092
selftest_debug_flags = old_debug_flags
3095
def load_test_id_list(file_name):
3096
"""Load a test id list from a text file.
3098
The format is one test id by line. No special care is taken to impose
3099
strict rules, these test ids are used to filter the test suite so a test id
3100
that do not match an existing test will do no harm. This allows user to add
3101
comments, leave blank lines, etc.
3105
ftest = open(file_name, 'rt')
3107
if e.errno != errno.ENOENT:
3110
raise errors.NoSuchFile(file_name)
3112
for test_name in ftest.readlines():
3113
test_list.append(test_name.strip())
3118
def suite_matches_id_list(test_suite, id_list):
3119
"""Warns about tests not appearing or appearing more than once.
3121
:param test_suite: A TestSuite object.
3122
:param test_id_list: The list of test ids that should be found in
3125
:return: (absents, duplicates) absents is a list containing the test found
3126
in id_list but not in test_suite, duplicates is a list containing the
3127
test found multiple times in test_suite.
3129
When using a prefined test id list, it may occurs that some tests do not
3130
exist anymore or that some tests use the same id. This function warns the
3131
tester about potential problems in his workflow (test lists are volatile)
3132
or in the test suite itself (using the same id for several tests does not
3133
help to localize defects).
3135
# Build a dict counting id occurrences
3137
for test in iter_suite_tests(test_suite):
3139
tests[id] = tests.get(id, 0) + 1
3144
occurs = tests.get(id, 0)
3146
not_found.append(id)
3148
duplicates.append(id)
3150
return not_found, duplicates
3153
class TestIdList(object):
3154
"""Test id list to filter a test suite.
3156
Relying on the assumption that test ids are built as:
3157
<module>[.<class>.<method>][(<param>+)], <module> being in python dotted
3158
notation, this class offers methods to :
3159
- avoid building a test suite for modules not refered to in the test list,
3160
- keep only the tests listed from the module test suite.
3163
def __init__(self, test_id_list):
3164
# When a test suite needs to be filtered against us we compare test ids
3165
# for equality, so a simple dict offers a quick and simple solution.
3166
self.tests = dict().fromkeys(test_id_list, True)
3168
# While unittest.TestCase have ids like:
3169
# <module>.<class>.<method>[(<param+)],
3170
# doctest.DocTestCase can have ids like:
3173
# <module>.<function>
3174
# <module>.<class>.<method>
3176
# Since we can't predict a test class from its name only, we settle on
3177
# a simple constraint: a test id always begins with its module name.
3180
for test_id in test_id_list:
3181
parts = test_id.split('.')
3182
mod_name = parts.pop(0)
3183
modules[mod_name] = True
3185
mod_name += '.' + part
3186
modules[mod_name] = True
3187
self.modules = modules
3189
def refers_to(self, module_name):
3190
"""Is there tests for the module or one of its sub modules."""
3191
return self.modules.has_key(module_name)
3193
def includes(self, test_id):
3194
return self.tests.has_key(test_id)
3197
class TestPrefixAliasRegistry(registry.Registry):
3198
"""A registry for test prefix aliases.
3200
This helps implement shorcuts for the --starting-with selftest
3201
option. Overriding existing prefixes is not allowed but not fatal (a
3202
warning will be emitted).
3205
def register(self, key, obj, help=None, info=None,
3206
override_existing=False):
3207
"""See Registry.register.
3209
Trying to override an existing alias causes a warning to be emitted,
3210
not a fatal execption.
3213
super(TestPrefixAliasRegistry, self).register(
3214
key, obj, help=help, info=info, override_existing=False)
3216
actual = self.get(key)
3217
note('Test prefix alias %s is already used for %s, ignoring %s'
3218
% (key, actual, obj))
3220
def resolve_alias(self, id_start):
3221
"""Replace the alias by the prefix in the given string.
3223
Using an unknown prefix is an error to help catching typos.
3225
parts = id_start.split('.')
3227
parts[0] = self.get(parts[0])
3229
raise errors.BzrCommandError(
3230
'%s is not a known test prefix alias' % parts[0])
3231
return '.'.join(parts)
3234
test_prefix_alias_registry = TestPrefixAliasRegistry()
3235
"""Registry of test prefix aliases."""
3238
# This alias allows to detect typos ('bzrlin.') by making all valid test ids
3239
# appear prefixed ('bzrlib.' is "replaced" by 'bzrlib.').
3240
test_prefix_alias_registry.register('bzrlib', 'bzrlib')
3242
# Obvious higest levels prefixes, feel free to add your own via a plugin
3243
test_prefix_alias_registry.register('bd', 'bzrlib.doc')
3244
test_prefix_alias_registry.register('bu', 'bzrlib.utils')
3245
test_prefix_alias_registry.register('bt', 'bzrlib.tests')
3246
test_prefix_alias_registry.register('bb', 'bzrlib.tests.blackbox')
3247
test_prefix_alias_registry.register('bp', 'bzrlib.plugins')
3250
def test_suite(keep_only=None, starting_with=None):
3251
"""Build and return TestSuite for the whole of bzrlib.
3253
:param keep_only: A list of test ids limiting the suite returned.
3255
:param starting_with: An id limiting the suite returned to the tests
3258
This function can be replaced if you need to change the default test
3259
suite on a global basis, but it is not encouraged.
3263
'bzrlib.tests.blackbox',
3264
'bzrlib.tests.branch_implementations',
3265
'bzrlib.tests.bzrdir_implementations',
3266
'bzrlib.tests.commands',
3267
'bzrlib.tests.interrepository_implementations',
3268
'bzrlib.tests.intertree_implementations',
3269
'bzrlib.tests.inventory_implementations',
3270
'bzrlib.tests.per_interbranch',
3271
'bzrlib.tests.per_lock',
3272
'bzrlib.tests.per_repository',
3273
'bzrlib.tests.per_repository_chk',
3274
'bzrlib.tests.per_repository_reference',
3275
'bzrlib.tests.test__chk_map',
3276
'bzrlib.tests.test__dirstate_helpers',
3277
'bzrlib.tests.test__groupcompress',
3278
'bzrlib.tests.test__walkdirs_win32',
3279
'bzrlib.tests.test_ancestry',
3280
'bzrlib.tests.test_annotate',
3281
'bzrlib.tests.test_api',
3282
'bzrlib.tests.test_atomicfile',
3283
'bzrlib.tests.test_bad_files',
3284
'bzrlib.tests.test_bisect_multi',
3285
'bzrlib.tests.test_branch',
3286
'bzrlib.tests.test_branchbuilder',
3287
'bzrlib.tests.test_btree_index',
3288
'bzrlib.tests.test_bugtracker',
3289
'bzrlib.tests.test_bundle',
3290
'bzrlib.tests.test_bzrdir',
3291
'bzrlib.tests.test__chunks_to_lines',
3292
'bzrlib.tests.test_cache_utf8',
3293
'bzrlib.tests.test_chk_map',
3294
'bzrlib.tests.test_chunk_writer',
3295
'bzrlib.tests.test_clean_tree',
3296
'bzrlib.tests.test_commands',
3297
'bzrlib.tests.test_commit',
3298
'bzrlib.tests.test_commit_merge',
3299
'bzrlib.tests.test_config',
3300
'bzrlib.tests.test_conflicts',
3301
'bzrlib.tests.test_counted_lock',
3302
'bzrlib.tests.test_decorators',
3303
'bzrlib.tests.test_delta',
3304
'bzrlib.tests.test_debug',
3305
'bzrlib.tests.test_deprecated_graph',
3306
'bzrlib.tests.test_diff',
3307
'bzrlib.tests.test_directory_service',
3308
'bzrlib.tests.test_dirstate',
3309
'bzrlib.tests.test_email_message',
3310
'bzrlib.tests.test_eol_filters',
3311
'bzrlib.tests.test_errors',
3312
'bzrlib.tests.test_export',
3313
'bzrlib.tests.test_extract',
3314
'bzrlib.tests.test_fetch',
3315
'bzrlib.tests.test_fifo_cache',
3316
'bzrlib.tests.test_filters',
3317
'bzrlib.tests.test_ftp_transport',
3318
'bzrlib.tests.test_foreign',
3319
'bzrlib.tests.test_generate_docs',
3320
'bzrlib.tests.test_generate_ids',
3321
'bzrlib.tests.test_globbing',
3322
'bzrlib.tests.test_gpg',
3323
'bzrlib.tests.test_graph',
3324
'bzrlib.tests.test_groupcompress',
3325
'bzrlib.tests.test_hashcache',
3326
'bzrlib.tests.test_help',
3327
'bzrlib.tests.test_hooks',
3328
'bzrlib.tests.test_http',
3329
'bzrlib.tests.test_http_implementations',
3330
'bzrlib.tests.test_http_response',
3331
'bzrlib.tests.test_https_ca_bundle',
3332
'bzrlib.tests.test_identitymap',
3333
'bzrlib.tests.test_ignores',
3334
'bzrlib.tests.test_index',
3335
'bzrlib.tests.test_info',
3336
'bzrlib.tests.test_inv',
3337
'bzrlib.tests.test_inventory_delta',
3338
'bzrlib.tests.test_knit',
3339
'bzrlib.tests.test_lazy_import',
3340
'bzrlib.tests.test_lazy_regex',
3341
'bzrlib.tests.test_lockable_files',
3342
'bzrlib.tests.test_lockdir',
3343
'bzrlib.tests.test_log',
3344
'bzrlib.tests.test_lru_cache',
3345
'bzrlib.tests.test_lsprof',
3346
'bzrlib.tests.test_mail_client',
3347
'bzrlib.tests.test_memorytree',
3348
'bzrlib.tests.test_merge',
3349
'bzrlib.tests.test_merge3',
3350
'bzrlib.tests.test_merge_core',
3351
'bzrlib.tests.test_merge_directive',
3352
'bzrlib.tests.test_missing',
3353
'bzrlib.tests.test_msgeditor',
3354
'bzrlib.tests.test_multiparent',
3355
'bzrlib.tests.test_mutabletree',
3356
'bzrlib.tests.test_nonascii',
3357
'bzrlib.tests.test_options',
3358
'bzrlib.tests.test_osutils',
3359
'bzrlib.tests.test_osutils_encodings',
3360
'bzrlib.tests.test_pack',
3361
'bzrlib.tests.test_pack_repository',
3362
'bzrlib.tests.test_patch',
3363
'bzrlib.tests.test_patches',
3364
'bzrlib.tests.test_permissions',
3365
'bzrlib.tests.test_plugins',
3366
'bzrlib.tests.test_progress',
3367
'bzrlib.tests.test_read_bundle',
3368
'bzrlib.tests.test_reconcile',
3369
'bzrlib.tests.test_reconfigure',
3370
'bzrlib.tests.test_registry',
3371
'bzrlib.tests.test_remote',
3372
'bzrlib.tests.test_rename_map',
3373
'bzrlib.tests.test_repository',
3374
'bzrlib.tests.test_revert',
3375
'bzrlib.tests.test_revision',
3376
'bzrlib.tests.test_revisionspec',
3377
'bzrlib.tests.test_revisiontree',
3378
'bzrlib.tests.test_rio',
3379
'bzrlib.tests.test_rules',
3380
'bzrlib.tests.test_sampler',
3381
'bzrlib.tests.test_selftest',
3382
'bzrlib.tests.test_serializer',
3383
'bzrlib.tests.test_setup',
3384
'bzrlib.tests.test_sftp_transport',
3385
'bzrlib.tests.test_shelf',
3386
'bzrlib.tests.test_shelf_ui',
3387
'bzrlib.tests.test_smart',
3388
'bzrlib.tests.test_smart_add',
3389
'bzrlib.tests.test_smart_request',
3390
'bzrlib.tests.test_smart_transport',
3391
'bzrlib.tests.test_smtp_connection',
3392
'bzrlib.tests.test_source',
3393
'bzrlib.tests.test_ssh_transport',
3394
'bzrlib.tests.test_status',
3395
'bzrlib.tests.test_store',
3396
'bzrlib.tests.test_strace',
3397
'bzrlib.tests.test_subsume',
3398
'bzrlib.tests.test_switch',
3399
'bzrlib.tests.test_symbol_versioning',
3400
'bzrlib.tests.test_tag',
3401
'bzrlib.tests.test_testament',
3402
'bzrlib.tests.test_textfile',
3403
'bzrlib.tests.test_textmerge',
3404
'bzrlib.tests.test_timestamp',
3405
'bzrlib.tests.test_trace',
3406
'bzrlib.tests.test_transactions',
3407
'bzrlib.tests.test_transform',
3408
'bzrlib.tests.test_transport',
3409
'bzrlib.tests.test_transport_implementations',
3410
'bzrlib.tests.test_transport_log',
3411
'bzrlib.tests.test_tree',
3412
'bzrlib.tests.test_treebuilder',
3413
'bzrlib.tests.test_tsort',
3414
'bzrlib.tests.test_tuned_gzip',
3415
'bzrlib.tests.test_ui',
3416
'bzrlib.tests.test_uncommit',
3417
'bzrlib.tests.test_upgrade',
3418
'bzrlib.tests.test_upgrade_stacked',
3419
'bzrlib.tests.test_urlutils',
3420
'bzrlib.tests.test_version',
3421
'bzrlib.tests.test_version_info',
3422
'bzrlib.tests.test_versionedfile',
3423
'bzrlib.tests.test_weave',
3424
'bzrlib.tests.test_whitebox',
3425
'bzrlib.tests.test_win32utils',
3426
'bzrlib.tests.test_workingtree',
3427
'bzrlib.tests.test_workingtree_4',
3428
'bzrlib.tests.test_wsgi',
3429
'bzrlib.tests.test_xml',
3430
'bzrlib.tests.tree_implementations',
3431
'bzrlib.tests.workingtree_implementations',
3432
'bzrlib.util.tests.test_bencode',
3435
loader = TestUtil.TestLoader()
3438
starting_with = [test_prefix_alias_registry.resolve_alias(start)
3439
for start in starting_with]
3440
# We take precedence over keep_only because *at loading time* using
3441
# both options means we will load less tests for the same final result.
3442
def interesting_module(name):
3443
for start in starting_with:
3445
# Either the module name starts with the specified string
3446
name.startswith(start)
3447
# or it may contain tests starting with the specified string
3448
or start.startswith(name)
3452
loader = TestUtil.FilteredByModuleTestLoader(interesting_module)
3454
elif keep_only is not None:
3455
id_filter = TestIdList(keep_only)
3456
loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
3457
def interesting_module(name):
3458
return id_filter.refers_to(name)
3461
loader = TestUtil.TestLoader()
3462
def interesting_module(name):
3463
# No filtering, all modules are interesting
3466
suite = loader.suiteClass()
3468
# modules building their suite with loadTestsFromModuleNames
3469
suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
3471
modules_to_doctest = [
3473
'bzrlib.branchbuilder',
3476
'bzrlib.iterablefile',
3480
'bzrlib.symbol_versioning',
3483
'bzrlib.version_info_formats.format_custom',
3486
for mod in modules_to_doctest:
3487
if not interesting_module(mod):
3488
# No tests to keep here, move along
3491
# note that this really does mean "report only" -- doctest
3492
# still runs the rest of the examples
3493
doc_suite = doctest.DocTestSuite(mod,
3494
optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
3495
except ValueError, e:
3496
print '**failed to get doctest for: %s\n%s' % (mod, e)
3498
if len(doc_suite._tests) == 0:
3499
raise errors.BzrError("no doctests found in %s" % (mod,))
3500
suite.addTest(doc_suite)
3502
default_encoding = sys.getdefaultencoding()
3503
for name, plugin in bzrlib.plugin.plugins().items():
3504
if not interesting_module(plugin.module.__name__):
3506
plugin_suite = plugin.test_suite()
3507
# We used to catch ImportError here and turn it into just a warning,
3508
# but really if you don't have --no-plugins this should be a failure.
3509
# mbp 20080213 - see http://bugs.launchpad.net/bugs/189771
3510
if plugin_suite is None:
3511
plugin_suite = plugin.load_plugin_tests(loader)
3512
if plugin_suite is not None:
3513
suite.addTest(plugin_suite)
3514
if default_encoding != sys.getdefaultencoding():
3515
bzrlib.trace.warning(
3516
'Plugin "%s" tried to reset default encoding to: %s', name,
3517
sys.getdefaultencoding())
3519
sys.setdefaultencoding(default_encoding)
3522
suite = filter_suite_by_id_startswith(suite, starting_with)
3524
if keep_only is not None:
3525
# Now that the referred modules have loaded their tests, keep only the
3527
suite = filter_suite_by_id_list(suite, id_filter)
3528
# Do some sanity checks on the id_list filtering
3529
not_found, duplicates = suite_matches_id_list(suite, keep_only)
3531
# The tester has used both keep_only and starting_with, so he is
3532
# already aware that some tests are excluded from the list, there
3533
# is no need to tell him which.
3536
# Some tests mentioned in the list are not in the test suite. The
3537
# list may be out of date, report to the tester.
3538
for id in not_found:
3539
bzrlib.trace.warning('"%s" not found in the test suite', id)
3540
for id in duplicates:
3541
bzrlib.trace.warning('"%s" is used as an id by several tests', id)
3546
def multiply_scenarios(scenarios_left, scenarios_right):
3547
"""Multiply two sets of scenarios.
3549
:returns: the cartesian product of the two sets of scenarios, that is
3550
a scenario for every possible combination of a left scenario and a
3554
('%s,%s' % (left_name, right_name),
3555
dict(left_dict.items() + right_dict.items()))
3556
for left_name, left_dict in scenarios_left
3557
for right_name, right_dict in scenarios_right]
3560
def multiply_tests(tests, scenarios, result):
3561
"""Multiply tests_list by scenarios into result.
3563
This is the core workhorse for test parameterisation.
3565
Typically the load_tests() method for a per-implementation test suite will
3566
call multiply_tests and return the result.
3568
:param tests: The tests to parameterise.
3569
:param scenarios: The scenarios to apply: pairs of (scenario_name,
3570
scenario_param_dict).
3571
:param result: A TestSuite to add created tests to.
3573
This returns the passed in result TestSuite with the cross product of all
3574
the tests repeated once for each scenario. Each test is adapted by adding
3575
the scenario name at the end of its id(), and updating the test object's
3576
__dict__ with the scenario_param_dict.
3578
>>> import bzrlib.tests.test_sampler
3579
>>> r = multiply_tests(
3580
... bzrlib.tests.test_sampler.DemoTest('test_nothing'),
3581
... [('one', dict(param=1)),
3582
... ('two', dict(param=2))],
3584
>>> tests = list(iter_suite_tests(r))
3588
'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
3594
for test in iter_suite_tests(tests):
3595
apply_scenarios(test, scenarios, result)
3599
def apply_scenarios(test, scenarios, result):
3600
"""Apply the scenarios in scenarios to test and add to result.
3602
:param test: The test to apply scenarios to.
3603
:param scenarios: An iterable of scenarios to apply to test.
3605
:seealso: apply_scenario
3607
for scenario in scenarios:
3608
result.addTest(apply_scenario(test, scenario))
3612
def apply_scenario(test, scenario):
3613
"""Copy test and apply scenario to it.
3615
:param test: A test to adapt.
3616
:param scenario: A tuple describing the scenarion.
3617
The first element of the tuple is the new test id.
3618
The second element is a dict containing attributes to set on the
3620
:return: The adapted test.
3622
new_id = "%s(%s)" % (test.id(), scenario[0])
3623
new_test = clone_test(test, new_id)
3624
for name, value in scenario[1].items():
3625
setattr(new_test, name, value)
3629
def clone_test(test, new_id):
3630
"""Clone a test giving it a new id.
3632
:param test: The test to clone.
3633
:param new_id: The id to assign to it.
3634
:return: The new test.
3636
from copy import deepcopy
3637
new_test = deepcopy(test)
3638
new_test.id = lambda: new_id
3642
def _rmtree_temp_dir(dirname):
3643
# If LANG=C we probably have created some bogus paths
3644
# which rmtree(unicode) will fail to delete
3645
# so make sure we are using rmtree(str) to delete everything
3646
# except on win32, where rmtree(str) will fail
3647
# since it doesn't have the property of byte-stream paths
3648
# (they are either ascii or mbcs)
3649
if sys.platform == 'win32':
3650
# make sure we are using the unicode win32 api
3651
dirname = unicode(dirname)
3653
dirname = dirname.encode(sys.getfilesystemencoding())
3655
osutils.rmtree(dirname)
3657
if sys.platform == 'win32' and e.errno == errno.EACCES:
3658
sys.stderr.write('Permission denied: '
3659
'unable to remove testing dir '
3661
% (os.path.basename(dirname), e))
3666
class Feature(object):
3667
"""An operating system Feature."""
3670
self._available = None
3672
def available(self):
3673
"""Is the feature available?
3675
:return: True if the feature is available.
3677
if self._available is None:
3678
self._available = self._probe()
3679
return self._available
3682
"""Implement this method in concrete features.
3684
:return: True if the feature is available.
3686
raise NotImplementedError
3689
if getattr(self, 'feature_name', None):
3690
return self.feature_name()
3691
return self.__class__.__name__
3694
class _SymlinkFeature(Feature):
3697
return osutils.has_symlinks()
3699
def feature_name(self):
3702
SymlinkFeature = _SymlinkFeature()
3705
class _HardlinkFeature(Feature):
3708
return osutils.has_hardlinks()
3710
def feature_name(self):
3713
HardlinkFeature = _HardlinkFeature()
3716
class _OsFifoFeature(Feature):
3719
return getattr(os, 'mkfifo', None)
3721
def feature_name(self):
3722
return 'filesystem fifos'
3724
OsFifoFeature = _OsFifoFeature()
3727
class _UnicodeFilenameFeature(Feature):
3728
"""Does the filesystem support Unicode filenames?"""
3732
# Check for character combinations unlikely to be covered by any
3733
# single non-unicode encoding. We use the characters
3734
# - greek small letter alpha (U+03B1) and
3735
# - braille pattern dots-123456 (U+283F).
3736
os.stat(u'\u03b1\u283f')
3737
except UnicodeEncodeError:
3739
except (IOError, OSError):
3740
# The filesystem allows the Unicode filename but the file doesn't
3744
# The filesystem allows the Unicode filename and the file exists,
3748
UnicodeFilenameFeature = _UnicodeFilenameFeature()
3751
def probe_unicode_in_user_encoding():
3752
"""Try to encode several unicode strings to use in unicode-aware tests.
3753
Return first successfull match.
3755
:return: (unicode value, encoded plain string value) or (None, None)
3757
possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
3758
for uni_val in possible_vals:
3760
str_val = uni_val.encode(osutils.get_user_encoding())
3761
except UnicodeEncodeError:
3762
# Try a different character
3765
return uni_val, str_val
3769
def probe_bad_non_ascii(encoding):
3770
"""Try to find [bad] character with code [128..255]
3771
that cannot be decoded to unicode in some encoding.
3772
Return None if all non-ascii characters is valid
3775
for i in xrange(128, 256):
3778
char.decode(encoding)
3779
except UnicodeDecodeError:
3784
class _HTTPSServerFeature(Feature):
3785
"""Some tests want an https Server, check if one is available.
3787
Right now, the only way this is available is under python2.6 which provides
3798
def feature_name(self):
3799
return 'HTTPSServer'
3802
HTTPSServerFeature = _HTTPSServerFeature()
3805
class _UnicodeFilename(Feature):
3806
"""Does the filesystem support Unicode filenames?"""
3811
except UnicodeEncodeError:
3813
except (IOError, OSError):
3814
# The filesystem allows the Unicode filename but the file doesn't
3818
# The filesystem allows the Unicode filename and the file exists,
3822
UnicodeFilename = _UnicodeFilename()
3825
class _UTF8Filesystem(Feature):
3826
"""Is the filesystem UTF-8?"""
3829
if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
3833
UTF8Filesystem = _UTF8Filesystem()
3836
class _CaseInsCasePresFilenameFeature(Feature):
3837
"""Is the file-system case insensitive, but case-preserving?"""
3840
fileno, name = tempfile.mkstemp(prefix='MixedCase')
3842
# first check truly case-preserving for created files, then check
3843
# case insensitive when opening existing files.
3844
name = osutils.normpath(name)
3845
base, rel = osutils.split(name)
3846
found_rel = osutils.canonical_relpath(base, name)
3847
return (found_rel == rel
3848
and os.path.isfile(name.upper())
3849
and os.path.isfile(name.lower()))
3854
def feature_name(self):
3855
return "case-insensitive case-preserving filesystem"
3857
CaseInsCasePresFilenameFeature = _CaseInsCasePresFilenameFeature()
3860
class _CaseInsensitiveFilesystemFeature(Feature):
3861
"""Check if underlying filesystem is case-insensitive but *not* case
3864
# Note that on Windows, Cygwin, MacOS etc, the file-systems are far
3865
# more likely to be case preserving, so this case is rare.
3868
if CaseInsCasePresFilenameFeature.available():
3871
if TestCaseWithMemoryTransport.TEST_ROOT is None:
3872
root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
3873
TestCaseWithMemoryTransport.TEST_ROOT = root
3875
root = TestCaseWithMemoryTransport.TEST_ROOT
3876
tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
3878
name_a = osutils.pathjoin(tdir, 'a')
3879
name_A = osutils.pathjoin(tdir, 'A')
3881
result = osutils.isdir(name_A)
3882
_rmtree_temp_dir(tdir)
3885
def feature_name(self):
3886
return 'case-insensitive filesystem'
3888
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
3891
class _SubUnitFeature(Feature):
3892
"""Check if subunit is available."""
3901
def feature_name(self):
3904
SubUnitFeature = _SubUnitFeature()
3905
# Only define SubUnitBzrRunner if subunit is available.
3907
from subunit import TestProtocolClient
3908
class SubUnitBzrRunner(TextTestRunner):
3909
def run(self, test):
3910
# undo out claim for testing which looks like a test start to subunit
3911
self.stream.write("success: %s\n" % (osutils.realpath(sys.argv[0]),))
3912
result = TestProtocolClient(self.stream)