1
# Copyright (C) 2005, 2006 by 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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.
30
from cStringIO import StringIO
39
from subprocess import Popen, PIPE
47
import bzrlib.bzrdir as bzrdir
48
import bzrlib.commands
49
import bzrlib.bundle.serializer
50
import bzrlib.errors as errors
51
import bzrlib.inventory
52
import bzrlib.iterablefile
57
# lsprof not available
59
from bzrlib.merge import merge_inner
62
import bzrlib.osutils as osutils
64
import bzrlib.progress as progress
65
from bzrlib.revision import common_ancestor
67
from bzrlib import symbol_versioning
69
from bzrlib.transport import get_transport
70
import bzrlib.transport
71
from bzrlib.transport.local import LocalRelpathServer
72
from bzrlib.transport.readonly import ReadonlyServer
73
from bzrlib.trace import mutter
74
from bzrlib.tests import TestUtil
75
from bzrlib.tests.TestUtil import (
79
from bzrlib.tests.treeshape import build_tree_contents
80
import bzrlib.urlutils as urlutils
81
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
83
default_transport = LocalRelpathServer
86
MODULES_TO_DOCTEST = [
87
bzrlib.bundle.serializer,
98
def packages_to_test():
99
"""Return a list of packages to test.
101
The packages are not globally imported so that import failures are
102
triggered when running selftest, not when importing the command.
105
import bzrlib.tests.blackbox
106
import bzrlib.tests.branch_implementations
107
import bzrlib.tests.bzrdir_implementations
108
import bzrlib.tests.interrepository_implementations
109
import bzrlib.tests.interversionedfile_implementations
110
import bzrlib.tests.intertree_implementations
111
import bzrlib.tests.repository_implementations
112
import bzrlib.tests.revisionstore_implementations
113
import bzrlib.tests.tree_implementations
114
import bzrlib.tests.workingtree_implementations
117
bzrlib.tests.blackbox,
118
bzrlib.tests.branch_implementations,
119
bzrlib.tests.bzrdir_implementations,
120
bzrlib.tests.interrepository_implementations,
121
bzrlib.tests.interversionedfile_implementations,
122
bzrlib.tests.intertree_implementations,
123
bzrlib.tests.repository_implementations,
124
bzrlib.tests.revisionstore_implementations,
125
bzrlib.tests.tree_implementations,
126
bzrlib.tests.workingtree_implementations,
130
class _MyResult(unittest._TextTestResult):
131
"""Custom TestResult.
133
Shows output in a different format, including displaying runtime for tests.
137
def __init__(self, stream, descriptions, verbosity, pb=None,
139
"""Construct new TestResult.
141
:param bench_history: Optionally, a writable file object to accumulate
144
unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
146
if bench_history is not None:
147
from bzrlib.version import _get_bzr_source_tree
148
src_tree = _get_bzr_source_tree()
151
revision_id = src_tree.get_parent_ids()[0]
153
# XXX: if this is a brand new tree, do the same as if there
157
# XXX: If there's no branch, what should we do?
159
bench_history.write("--date %s %s\n" % (time.time(), revision_id))
160
self._bench_history = bench_history
162
def extractBenchmarkTime(self, testCase):
163
"""Add a benchmark time for the current test case."""
164
self._benchmarkTime = getattr(testCase, "_benchtime", None)
166
def _elapsedTestTimeString(self):
167
"""Return a time string for the overall time the current test has taken."""
168
return self._formatTime(time.time() - self._start_time)
170
def _testTimeString(self):
171
if self._benchmarkTime is not None:
173
self._formatTime(self._benchmarkTime),
174
self._elapsedTestTimeString())
176
return " %s" % self._elapsedTestTimeString()
178
def _formatTime(self, seconds):
179
"""Format seconds as milliseconds with leading spaces."""
180
return "%5dms" % (1000 * seconds)
182
def _ellipsise_unimportant_words(self, a_string, final_width,
184
"""Add ellipses (sp?) for overly long strings.
186
:param keep_start: If true preserve the start of a_string rather
190
if len(a_string) > final_width:
191
result = a_string[:final_width-3] + '...'
195
if len(a_string) > final_width:
196
result = '...' + a_string[3-final_width:]
199
return result.ljust(final_width)
201
def startTest(self, test):
202
unittest.TestResult.startTest(self, test)
203
# In a short description, the important words are in
204
# the beginning, but in an id, the important words are
206
SHOW_DESCRIPTIONS = False
208
if not self.showAll and self.dots and self.pb is not None:
211
final_width = osutils.terminal_width()
212
final_width = final_width - 15 - 8
214
if SHOW_DESCRIPTIONS:
215
what = test.shortDescription()
217
what = self._ellipsise_unimportant_words(what, final_width, keep_start=True)
220
if what.startswith('bzrlib.tests.'):
222
what = self._ellipsise_unimportant_words(what, final_width)
224
self.stream.write(what)
225
elif self.dots and self.pb is not None:
226
self.pb.update(what, self.testsRun - 1, None)
228
self._recordTestStartTime()
230
def _recordTestStartTime(self):
231
"""Record that a test has started."""
232
self._start_time = time.time()
234
def addError(self, test, err):
235
if isinstance(err[1], TestSkipped):
236
return self.addSkipped(test, err)
237
unittest.TestResult.addError(self, test, err)
238
self.extractBenchmarkTime(test)
240
self.stream.writeln("ERROR %s" % self._testTimeString())
241
elif self.dots and self.pb is None:
242
self.stream.write('E')
244
self.pb.update(self._ellipsise_unimportant_words('ERROR', 13), self.testsRun, None)
245
self.pb.note(self._ellipsise_unimportant_words(
246
test.id() + ': ERROR',
247
osutils.terminal_width()))
252
def addFailure(self, test, err):
253
unittest.TestResult.addFailure(self, test, err)
254
self.extractBenchmarkTime(test)
256
self.stream.writeln(" FAIL %s" % self._testTimeString())
257
elif self.dots and self.pb is None:
258
self.stream.write('F')
260
self.pb.update(self._ellipsise_unimportant_words('FAIL', 13), self.testsRun, None)
261
self.pb.note(self._ellipsise_unimportant_words(
262
test.id() + ': FAIL',
263
osutils.terminal_width()))
268
def addSuccess(self, test):
269
self.extractBenchmarkTime(test)
270
if self._bench_history is not None:
271
if self._benchmarkTime is not None:
272
self._bench_history.write("%s %s\n" % (
273
self._formatTime(self._benchmarkTime),
276
self.stream.writeln(' OK %s' % self._testTimeString())
277
for bench_called, stats in getattr(test, '_benchcalls', []):
278
self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
279
stats.pprint(file=self.stream)
280
elif self.dots and self.pb is None:
281
self.stream.write('~')
283
self.pb.update(self._ellipsise_unimportant_words('OK', 13), self.testsRun, None)
285
unittest.TestResult.addSuccess(self, test)
287
def addSkipped(self, test, skip_excinfo):
288
self.extractBenchmarkTime(test)
290
print >>self.stream, ' SKIP %s' % self._testTimeString()
291
print >>self.stream, ' %s' % skip_excinfo[1]
292
elif self.dots and self.pb is None:
293
self.stream.write('S')
295
self.pb.update(self._ellipsise_unimportant_words('SKIP', 13), self.testsRun, None)
297
# seems best to treat this as success from point-of-view of unittest
298
# -- it actually does nothing so it barely matters :)
301
except KeyboardInterrupt:
304
self.addError(test, test.__exc_info())
306
unittest.TestResult.addSuccess(self, test)
308
def printErrorList(self, flavour, errors):
309
for test, err in errors:
310
self.stream.writeln(self.separator1)
311
self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
312
if getattr(test, '_get_log', None) is not None:
314
print >>self.stream, \
315
('vvvv[log from %s]' % test.id()).ljust(78,'-')
316
print >>self.stream, test._get_log()
317
print >>self.stream, \
318
('^^^^[log from %s]' % test.id()).ljust(78,'-')
319
self.stream.writeln(self.separator2)
320
self.stream.writeln("%s" % err)
323
class TextTestRunner(object):
324
stop_on_failure = False
333
self.stream = unittest._WritelnDecorator(stream)
334
self.descriptions = descriptions
335
self.verbosity = verbosity
336
self.keep_output = keep_output
338
self._bench_history = bench_history
340
def _makeResult(self):
341
result = _MyResult(self.stream,
345
bench_history=self._bench_history)
346
result.stop_early = self.stop_on_failure
350
"Run the given test case or test suite."
351
result = self._makeResult()
352
startTime = time.time()
353
if self.pb is not None:
354
self.pb.update('Running tests', 0, test.countTestCases())
356
stopTime = time.time()
357
timeTaken = stopTime - startTime
359
self.stream.writeln(result.separator2)
360
run = result.testsRun
361
self.stream.writeln("Ran %d test%s in %.3fs" %
362
(run, run != 1 and "s" or "", timeTaken))
363
self.stream.writeln()
364
if not result.wasSuccessful():
365
self.stream.write("FAILED (")
366
failed, errored = map(len, (result.failures, result.errors))
368
self.stream.write("failures=%d" % failed)
370
if failed: self.stream.write(", ")
371
self.stream.write("errors=%d" % errored)
372
self.stream.writeln(")")
374
self.stream.writeln("OK")
375
if self.pb is not None:
376
self.pb.update('Cleaning up', 0, 1)
377
# This is still a little bogus,
378
# but only a little. Folk not using our testrunner will
379
# have to delete their temp directories themselves.
380
test_root = TestCaseInTempDir.TEST_ROOT
381
if result.wasSuccessful() or not self.keep_output:
382
if test_root is not None:
383
# If LANG=C we probably have created some bogus paths
384
# which rmtree(unicode) will fail to delete
385
# so make sure we are using rmtree(str) to delete everything
386
# except on win32, where rmtree(str) will fail
387
# since it doesn't have the property of byte-stream paths
388
# (they are either ascii or mbcs)
389
if sys.platform == 'win32':
390
# make sure we are using the unicode win32 api
391
test_root = unicode(test_root)
393
test_root = test_root.encode(
394
sys.getfilesystemencoding())
395
osutils.rmtree(test_root)
397
if self.pb is not None:
398
self.pb.note("Failed tests working directories are in '%s'\n",
402
"Failed tests working directories are in '%s'\n" %
404
TestCaseInTempDir.TEST_ROOT = None
405
if self.pb is not None:
410
def iter_suite_tests(suite):
411
"""Return all tests in a suite, recursing through nested suites"""
412
for item in suite._tests:
413
if isinstance(item, unittest.TestCase):
415
elif isinstance(item, unittest.TestSuite):
416
for r in iter_suite_tests(item):
419
raise Exception('unknown object %r inside test suite %r'
423
class TestSkipped(Exception):
424
"""Indicates that a test was intentionally skipped, rather than failing."""
427
class CommandFailed(Exception):
431
class StringIOWrapper(object):
432
"""A wrapper around cStringIO which just adds an encoding attribute.
434
Internally we can check sys.stdout to see what the output encoding
435
should be. However, cStringIO has no encoding attribute that we can
436
set. So we wrap it instead.
441
def __init__(self, s=None):
443
self.__dict__['_cstring'] = StringIO(s)
445
self.__dict__['_cstring'] = StringIO()
447
def __getattr__(self, name, getattr=getattr):
448
return getattr(self.__dict__['_cstring'], name)
450
def __setattr__(self, name, val):
451
if name == 'encoding':
452
self.__dict__['encoding'] = val
454
return setattr(self._cstring, name, val)
457
class TestCase(unittest.TestCase):
458
"""Base class for bzr unit tests.
460
Tests that need access to disk resources should subclass
461
TestCaseInTempDir not TestCase.
463
Error and debug log messages are redirected from their usual
464
location into a temporary file, the contents of which can be
465
retrieved by _get_log(). We use a real OS file, not an in-memory object,
466
so that it can also capture file IO. When the test completes this file
467
is read into memory and removed from disk.
469
There are also convenience functions to invoke bzr's command-line
470
routine, and to build and check bzr trees.
472
In addition to the usual method of overriding tearDown(), this class also
473
allows subclasses to register functions into the _cleanups list, which is
474
run in order as the object is torn down. It's less likely this will be
475
accidentally overlooked.
478
_log_file_name = None
480
# record lsprof data when performing benchmark calls.
481
_gather_lsprof_in_benchmarks = False
483
def __init__(self, methodName='testMethod'):
484
super(TestCase, self).__init__(methodName)
488
unittest.TestCase.setUp(self)
489
self._cleanEnvironment()
490
bzrlib.trace.disable_default_logging()
492
self._benchcalls = []
493
self._benchtime = None
495
def _ndiff_strings(self, a, b):
496
"""Return ndiff between two strings containing lines.
498
A trailing newline is added if missing to make the strings
500
if b and b[-1] != '\n':
502
if a and a[-1] != '\n':
504
difflines = difflib.ndiff(a.splitlines(True),
506
linejunk=lambda x: False,
507
charjunk=lambda x: False)
508
return ''.join(difflines)
510
def assertEqualDiff(self, a, b, message=None):
511
"""Assert two texts are equal, if not raise an exception.
513
This is intended for use with multi-line strings where it can
514
be hard to find the differences by eye.
516
# TODO: perhaps override assertEquals to call this for strings?
520
message = "texts not equal:\n"
521
raise AssertionError(message +
522
self._ndiff_strings(a, b))
524
def assertEqualMode(self, mode, mode_test):
525
self.assertEqual(mode, mode_test,
526
'mode mismatch %o != %o' % (mode, mode_test))
528
def assertStartsWith(self, s, prefix):
529
if not s.startswith(prefix):
530
raise AssertionError('string %r does not start with %r' % (s, prefix))
532
def assertEndsWith(self, s, suffix):
533
"""Asserts that s ends with suffix."""
534
if not s.endswith(suffix):
535
raise AssertionError('string %r does not end with %r' % (s, suffix))
537
def assertContainsRe(self, haystack, needle_re):
538
"""Assert that a contains something matching a regular expression."""
539
if not re.search(needle_re, haystack):
540
raise AssertionError('pattern "%s" not found in "%s"'
541
% (needle_re, haystack))
543
def assertNotContainsRe(self, haystack, needle_re):
544
"""Assert that a does not match a regular expression"""
545
if re.search(needle_re, haystack):
546
raise AssertionError('pattern "%s" found in "%s"'
547
% (needle_re, haystack))
549
def assertSubset(self, sublist, superlist):
550
"""Assert that every entry in sublist is present in superlist."""
552
for entry in sublist:
553
if entry not in superlist:
554
missing.append(entry)
556
raise AssertionError("value(s) %r not present in container %r" %
557
(missing, superlist))
559
def assertIs(self, left, right):
560
if not (left is right):
561
raise AssertionError("%r is not %r." % (left, right))
563
def assertTransportMode(self, transport, path, mode):
564
"""Fail if a path does not have mode mode.
566
If modes are not supported on this transport, the assertion is ignored.
568
if not transport._can_roundtrip_unix_modebits():
570
path_stat = transport.stat(path)
571
actual_mode = stat.S_IMODE(path_stat.st_mode)
572
self.assertEqual(mode, actual_mode,
573
'mode of %r incorrect (%o != %o)' % (path, mode, actual_mode))
575
def assertIsInstance(self, obj, kls):
576
"""Fail if obj is not an instance of kls"""
577
if not isinstance(obj, kls):
578
self.fail("%r is an instance of %s rather than %s" % (
579
obj, obj.__class__, kls))
581
def _capture_warnings(self, a_callable, *args, **kwargs):
582
"""A helper for callDeprecated and applyDeprecated.
584
:param a_callable: A callable to call.
585
:param args: The positional arguments for the callable
586
:param kwargs: The keyword arguments for the callable
587
:return: A tuple (warnings, result). result is the result of calling
588
a_callable(*args, **kwargs).
591
def capture_warnings(msg, cls, stacklevel=None):
592
# we've hooked into a deprecation specific callpath,
593
# only deprecations should getting sent via it.
594
self.assertEqual(cls, DeprecationWarning)
595
local_warnings.append(msg)
596
original_warning_method = symbol_versioning.warn
597
symbol_versioning.set_warning_method(capture_warnings)
599
result = a_callable(*args, **kwargs)
601
symbol_versioning.set_warning_method(original_warning_method)
602
return (local_warnings, result)
604
def applyDeprecated(self, deprecation_format, a_callable, *args, **kwargs):
605
"""Call a deprecated callable without warning the user.
607
:param deprecation_format: The deprecation format that the callable
608
should have been deprecated with. This is the same type as the
609
parameter to deprecated_method/deprecated_function. If the
610
callable is not deprecated with this format, an assertion error
612
:param a_callable: A callable to call. This may be a bound method or
613
a regular function. It will be called with *args and **kwargs.
614
:param args: The positional arguments for the callable
615
:param kwargs: The keyword arguments for the callable
616
:return: The result of a_callable(*args, **kwargs)
618
call_warnings, result = self._capture_warnings(a_callable,
620
expected_first_warning = symbol_versioning.deprecation_string(
621
a_callable, deprecation_format)
622
if len(call_warnings) == 0:
623
self.fail("No assertion generated by call to %s" %
625
self.assertEqual(expected_first_warning, call_warnings[0])
628
def callDeprecated(self, expected, callable, *args, **kwargs):
629
"""Assert that a callable is deprecated in a particular way.
631
This is a very precise test for unusual requirements. The
632
applyDeprecated helper function is probably more suited for most tests
633
as it allows you to simply specify the deprecation format being used
634
and will ensure that that is issued for the function being called.
636
:param expected: a list of the deprecation warnings expected, in order
637
:param callable: The callable to call
638
:param args: The positional arguments for the callable
639
:param kwargs: The keyword arguments for the callable
641
call_warnings, result = self._capture_warnings(callable,
643
self.assertEqual(expected, call_warnings)
646
def _startLogFile(self):
647
"""Send bzr and test log messages to a temporary file.
649
The file is removed as the test is torn down.
651
fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
652
self._log_file = os.fdopen(fileno, 'w+')
653
self._log_nonce = bzrlib.trace.enable_test_log(self._log_file)
654
self._log_file_name = name
655
self.addCleanup(self._finishLogFile)
657
def _finishLogFile(self):
658
"""Finished with the log file.
660
Read contents into memory, close, and delete.
662
if self._log_file is None:
664
bzrlib.trace.disable_test_log(self._log_nonce)
665
self._log_file.seek(0)
666
self._log_contents = self._log_file.read()
667
self._log_file.close()
668
os.remove(self._log_file_name)
669
self._log_file = self._log_file_name = None
671
def addCleanup(self, callable):
672
"""Arrange to run a callable when this case is torn down.
674
Callables are run in the reverse of the order they are registered,
675
ie last-in first-out.
677
if callable in self._cleanups:
678
raise ValueError("cleanup function %r already registered on %s"
680
self._cleanups.append(callable)
682
def _cleanEnvironment(self):
685
'APPDATA': os.getcwd(),
687
'BZREMAIL': None, # may still be present in the environment
689
'BZR_PROGRESS_BAR': None,
692
self.addCleanup(self._restoreEnvironment)
693
for name, value in new_env.iteritems():
694
self._captureVar(name, value)
696
def _captureVar(self, name, newvalue):
697
"""Set an environment variable, and reset it when finished."""
698
self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
700
def _restoreEnvironment(self):
701
for name, value in self.__old_env.iteritems():
702
osutils.set_or_unset_env(name, value)
706
unittest.TestCase.tearDown(self)
708
def time(self, callable, *args, **kwargs):
709
"""Run callable and accrue the time it takes to the benchmark time.
711
If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
712
this will cause lsprofile statistics to be gathered and stored in
715
if self._benchtime is None:
719
if not self._gather_lsprof_in_benchmarks:
720
return callable(*args, **kwargs)
722
# record this benchmark
723
ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
725
self._benchcalls.append(((callable, args, kwargs), stats))
728
self._benchtime += time.time() - start
730
def _runCleanups(self):
731
"""Run registered cleanup functions.
733
This should only be called from TestCase.tearDown.
735
# TODO: Perhaps this should keep running cleanups even if
737
for cleanup_fn in reversed(self._cleanups):
740
def log(self, *args):
744
"""Return as a string the log for this test"""
745
if self._log_file_name:
746
return open(self._log_file_name).read()
748
return self._log_contents
749
# TODO: Delete the log after it's been read in
751
def capture(self, cmd, retcode=0):
752
"""Shortcut that splits cmd into words, runs, and returns stdout"""
753
return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
755
def run_bzr_captured(self, argv, retcode=0, encoding=None, stdin=None):
756
"""Invoke bzr and return (stdout, stderr).
758
Useful for code that wants to check the contents of the
759
output, the way error messages are presented, etc.
761
This should be the main method for tests that want to exercise the
762
overall behavior of the bzr application (rather than a unit test
763
or a functional test of the library.)
765
Much of the old code runs bzr by forking a new copy of Python, but
766
that is slower, harder to debug, and generally not necessary.
768
This runs bzr through the interface that catches and reports
769
errors, and with logging set to something approximating the
770
default, so that error reporting can be checked.
772
:param argv: arguments to invoke bzr
773
:param retcode: expected return code, or None for don't-care.
774
:param encoding: encoding for sys.stdout and sys.stderr
775
:param stdin: A string to be used as stdin for the command.
778
encoding = bzrlib.user_encoding
779
if stdin is not None:
780
stdin = StringIO(stdin)
781
stdout = StringIOWrapper()
782
stderr = StringIOWrapper()
783
stdout.encoding = encoding
784
stderr.encoding = encoding
786
self.log('run bzr: %r', argv)
787
# FIXME: don't call into logging here
788
handler = logging.StreamHandler(stderr)
789
handler.setLevel(logging.INFO)
790
logger = logging.getLogger('')
791
logger.addHandler(handler)
792
old_ui_factory = bzrlib.ui.ui_factory
793
bzrlib.ui.ui_factory = bzrlib.tests.blackbox.TestUIFactory(
796
bzrlib.ui.ui_factory.stdin = stdin
798
result = self.apply_redirected(stdin, stdout, stderr,
799
bzrlib.commands.run_bzr_catch_errors,
802
logger.removeHandler(handler)
803
bzrlib.ui.ui_factory = old_ui_factory
805
out = stdout.getvalue()
806
err = stderr.getvalue()
808
self.log('output:\n%r', out)
810
self.log('errors:\n%r', err)
811
if retcode is not None:
812
self.assertEquals(retcode, result)
815
def run_bzr(self, *args, **kwargs):
816
"""Invoke bzr, as if it were run from the command line.
818
This should be the main method for tests that want to exercise the
819
overall behavior of the bzr application (rather than a unit test
820
or a functional test of the library.)
822
This sends the stdout/stderr results into the test's log,
823
where it may be useful for debugging. See also run_captured.
825
:param stdin: A string to be used as stdin for the command.
827
retcode = kwargs.pop('retcode', 0)
828
encoding = kwargs.pop('encoding', None)
829
stdin = kwargs.pop('stdin', None)
830
return self.run_bzr_captured(args, retcode=retcode, encoding=encoding, stdin=stdin)
832
def run_bzr_decode(self, *args, **kwargs):
833
if 'encoding' in kwargs:
834
encoding = kwargs['encoding']
836
encoding = bzrlib.user_encoding
837
return self.run_bzr(*args, **kwargs)[0].decode(encoding)
839
def run_bzr_error(self, error_regexes, *args, **kwargs):
840
"""Run bzr, and check that stderr contains the supplied regexes
842
:param error_regexes: Sequence of regular expressions which
843
must each be found in the error output. The relative ordering
845
:param args: command-line arguments for bzr
846
:param kwargs: Keyword arguments which are interpreted by run_bzr
847
This function changes the default value of retcode to be 3,
848
since in most cases this is run when you expect bzr to fail.
849
:return: (out, err) The actual output of running the command (in case you
850
want to do more inspection)
853
# Make sure that commit is failing because there is nothing to do
854
self.run_bzr_error(['no changes to commit'],
855
'commit', '-m', 'my commit comment')
856
# Make sure --strict is handling an unknown file, rather than
857
# giving us the 'nothing to do' error
858
self.build_tree(['unknown'])
859
self.run_bzr_error(['Commit refused because there are unknown files'],
860
'commit', '--strict', '-m', 'my commit comment')
862
kwargs.setdefault('retcode', 3)
863
out, err = self.run_bzr(*args, **kwargs)
864
for regex in error_regexes:
865
self.assertContainsRe(err, regex)
868
def run_bzr_subprocess(self, *args, **kwargs):
869
"""Run bzr in a subprocess for testing.
871
This starts a new Python interpreter and runs bzr in there.
872
This should only be used for tests that have a justifiable need for
873
this isolation: e.g. they are testing startup time, or signal
874
handling, or early startup code, etc. Subprocess code can't be
875
profiled or debugged so easily.
877
:param retcode: The status code that is expected. Defaults to 0. If
878
None is supplied, the status code is not checked.
879
:param env_changes: A dictionary which lists changes to environment
880
variables. A value of None will unset the env variable.
881
The values must be strings. The change will only occur in the
882
child, so you don't need to fix the environment after running.
883
:param universal_newlines: Convert CRLF => LF
885
env_changes = kwargs.get('env_changes', {})
889
def cleanup_environment():
890
for env_var, value in env_changes.iteritems():
891
old_env[env_var] = osutils.set_or_unset_env(env_var, value)
893
def restore_environment():
894
for env_var, value in old_env.iteritems():
895
osutils.set_or_unset_env(env_var, value)
897
bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
901
# win32 subprocess doesn't support preexec_fn
902
# so we will avoid using it on all platforms, just to
903
# make sure the code path is used, and we don't break on win32
904
cleanup_environment()
905
process = Popen([sys.executable, bzr_path]+args,
906
stdout=PIPE, stderr=PIPE)
908
restore_environment()
910
out = process.stdout.read()
911
err = process.stderr.read()
913
if kwargs.get('universal_newlines', False):
914
out = out.replace('\r\n', '\n')
915
err = err.replace('\r\n', '\n')
917
retcode = process.wait()
918
supplied_retcode = kwargs.get('retcode', 0)
919
if supplied_retcode is not None:
920
assert supplied_retcode == retcode
923
def check_inventory_shape(self, inv, shape):
924
"""Compare an inventory to a list of expected names.
926
Fail if they are not precisely equal.
929
shape = list(shape) # copy
930
for path, ie in inv.entries():
931
name = path.replace('\\', '/')
939
self.fail("expected paths not found in inventory: %r" % shape)
941
self.fail("unexpected paths found in inventory: %r" % extras)
943
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
944
a_callable=None, *args, **kwargs):
945
"""Call callable with redirected std io pipes.
947
Returns the return code."""
948
if not callable(a_callable):
949
raise ValueError("a_callable must be callable.")
953
if getattr(self, "_log_file", None) is not None:
954
stdout = self._log_file
958
if getattr(self, "_log_file", None is not None):
959
stderr = self._log_file
962
real_stdin = sys.stdin
963
real_stdout = sys.stdout
964
real_stderr = sys.stderr
969
return a_callable(*args, **kwargs)
971
sys.stdout = real_stdout
972
sys.stderr = real_stderr
973
sys.stdin = real_stdin
975
@symbol_versioning.deprecated_method(symbol_versioning.zero_eleven)
976
def merge(self, branch_from, wt_to):
977
"""A helper for tests to do a ui-less merge.
979
This should move to the main library when someone has time to integrate
982
# minimal ui-less merge.
983
wt_to.branch.fetch(branch_from)
984
base_rev = common_ancestor(branch_from.last_revision(),
985
wt_to.branch.last_revision(),
986
wt_to.branch.repository)
987
merge_inner(wt_to.branch, branch_from.basis_tree(),
988
wt_to.branch.repository.revision_tree(base_rev),
990
wt_to.add_parent_tree_id(branch_from.last_revision())
993
BzrTestBase = TestCase
996
class TestCaseInTempDir(TestCase):
997
"""Derived class that runs a test within a temporary directory.
999
This is useful for tests that need to create a branch, etc.
1001
The directory is created in a slightly complex way: for each
1002
Python invocation, a new temporary top-level directory is created.
1003
All test cases create their own directory within that. If the
1004
tests complete successfully, the directory is removed.
1006
InTempDir is an old alias for FunctionalTestCase.
1011
OVERRIDE_PYTHON = 'python'
1013
def check_file_contents(self, filename, expect):
1014
self.log("check contents of file %s" % filename)
1015
contents = file(filename, 'r').read()
1016
if contents != expect:
1017
self.log("expected: %r" % expect)
1018
self.log("actually: %r" % contents)
1019
self.fail("contents of %s not as expected" % filename)
1021
def _make_test_root(self):
1022
if TestCaseInTempDir.TEST_ROOT is not None:
1026
root = u'test%04d.tmp' % i
1030
if e.errno == errno.EEXIST:
1035
# successfully created
1036
TestCaseInTempDir.TEST_ROOT = osutils.abspath(root)
1038
# make a fake bzr directory there to prevent any tests propagating
1039
# up onto the source directory's real branch
1040
bzrdir.BzrDir.create_standalone_workingtree(TestCaseInTempDir.TEST_ROOT)
1043
super(TestCaseInTempDir, self).setUp()
1044
self._make_test_root()
1045
_currentdir = os.getcwdu()
1046
# shorten the name, to avoid test failures due to path length
1047
short_id = self.id().replace('bzrlib.tests.', '') \
1048
.replace('__main__.', '')[-100:]
1049
# it's possible the same test class is run several times for
1050
# parameterized tests, so make sure the names don't collide.
1054
candidate_dir = '%s/%s.%d' % (self.TEST_ROOT, short_id, i)
1056
candidate_dir = '%s/%s' % (self.TEST_ROOT, short_id)
1057
if os.path.exists(candidate_dir):
1061
os.mkdir(candidate_dir)
1062
self.test_home_dir = candidate_dir + '/home'
1063
os.mkdir(self.test_home_dir)
1064
self.test_dir = candidate_dir + '/work'
1065
os.mkdir(self.test_dir)
1066
os.chdir(self.test_dir)
1068
os.environ['HOME'] = self.test_home_dir
1069
os.environ['APPDATA'] = self.test_home_dir
1070
def _leaveDirectory():
1071
os.chdir(_currentdir)
1072
self.addCleanup(_leaveDirectory)
1074
def build_tree(self, shape, line_endings='native', transport=None):
1075
"""Build a test tree according to a pattern.
1077
shape is a sequence of file specifications. If the final
1078
character is '/', a directory is created.
1080
This assumes that all the elements in the tree being built are new.
1082
This doesn't add anything to a branch.
1083
:param line_endings: Either 'binary' or 'native'
1084
in binary mode, exact contents are written
1085
in native mode, the line endings match the
1086
default platform endings.
1088
:param transport: A transport to write to, for building trees on
1089
VFS's. If the transport is readonly or None,
1090
"." is opened automatically.
1092
# It's OK to just create them using forward slashes on windows.
1093
if transport is None or transport.is_readonly():
1094
transport = get_transport(".")
1096
self.assert_(isinstance(name, basestring))
1098
transport.mkdir(urlutils.escape(name[:-1]))
1100
if line_endings == 'binary':
1102
elif line_endings == 'native':
1105
raise errors.BzrError('Invalid line ending request %r' % (line_endings,))
1106
content = "contents of %s%s" % (name.encode('utf-8'), end)
1107
# Technically 'put()' is the right command. However, put
1108
# uses an AtomicFile, which requires an extra rename into place
1109
# As long as the files didn't exist in the past, append() will
1110
# do the same thing as put()
1111
# On jam's machine, make_kernel_like_tree is:
1112
# put: 4.5-7.5s (averaging 6s)
1114
# put_non_atomic: 2.9-4.5s
1115
transport.put_bytes_non_atomic(urlutils.escape(name), content)
1117
def build_tree_contents(self, shape):
1118
build_tree_contents(shape)
1120
def failUnlessExists(self, path):
1121
"""Fail unless path, which may be abs or relative, exists."""
1122
self.failUnless(osutils.lexists(path))
1124
def failIfExists(self, path):
1125
"""Fail if path, which may be abs or relative, exists."""
1126
self.failIf(osutils.lexists(path))
1128
def assertFileEqual(self, content, path):
1129
"""Fail if path does not contain 'content'."""
1130
self.failUnless(osutils.lexists(path))
1131
# TODO: jam 20060427 Shouldn't this be 'rb'?
1132
self.assertEqualDiff(content, open(path, 'r').read())
1135
class TestCaseWithTransport(TestCaseInTempDir):
1136
"""A test case that provides get_url and get_readonly_url facilities.
1138
These back onto two transport servers, one for readonly access and one for
1141
If no explicit class is provided for readonly access, a
1142
ReadonlyTransportDecorator is used instead which allows the use of non disk
1143
based read write transports.
1145
If an explicit class is provided for readonly access, that server and the
1146
readwrite one must both define get_url() as resolving to os.getcwd().
1149
def __init__(self, methodName='testMethod'):
1150
super(TestCaseWithTransport, self).__init__(methodName)
1151
self.__readonly_server = None
1152
self.__server = None
1153
self.transport_server = default_transport
1154
self.transport_readonly_server = None
1156
def get_readonly_url(self, relpath=None):
1157
"""Get a URL for the readonly transport.
1159
This will either be backed by '.' or a decorator to the transport
1160
used by self.get_url()
1161
relpath provides for clients to get a path relative to the base url.
1162
These should only be downwards relative, not upwards.
1164
base = self.get_readonly_server().get_url()
1165
if relpath is not None:
1166
if not base.endswith('/'):
1168
base = base + relpath
1171
def get_readonly_server(self):
1172
"""Get the server instance for the readonly transport
1174
This is useful for some tests with specific servers to do diagnostics.
1176
if self.__readonly_server is None:
1177
if self.transport_readonly_server is None:
1178
# readonly decorator requested
1179
# bring up the server
1181
self.__readonly_server = ReadonlyServer()
1182
self.__readonly_server.setUp(self.__server)
1184
self.__readonly_server = self.transport_readonly_server()
1185
self.__readonly_server.setUp()
1186
self.addCleanup(self.__readonly_server.tearDown)
1187
return self.__readonly_server
1189
def get_server(self):
1190
"""Get the read/write server instance.
1192
This is useful for some tests with specific servers that need
1195
if self.__server is None:
1196
self.__server = self.transport_server()
1197
self.__server.setUp()
1198
self.addCleanup(self.__server.tearDown)
1199
return self.__server
1201
def get_url(self, relpath=None):
1202
"""Get a URL for the readwrite transport.
1204
This will either be backed by '.' or to an equivalent non-file based
1206
relpath provides for clients to get a path relative to the base url.
1207
These should only be downwards relative, not upwards.
1209
base = self.get_server().get_url()
1210
if relpath is not None and relpath != '.':
1211
if not base.endswith('/'):
1213
base = base + urlutils.escape(relpath)
1216
def get_transport(self):
1217
"""Return a writeable transport for the test scratch space"""
1218
t = get_transport(self.get_url())
1219
self.assertFalse(t.is_readonly())
1222
def get_readonly_transport(self):
1223
"""Return a readonly transport for the test scratch space
1225
This can be used to test that operations which should only need
1226
readonly access in fact do not try to write.
1228
t = get_transport(self.get_readonly_url())
1229
self.assertTrue(t.is_readonly())
1232
def make_branch(self, relpath, format=None):
1233
"""Create a branch on the transport at relpath."""
1234
repo = self.make_repository(relpath, format=format)
1235
return repo.bzrdir.create_branch()
1237
def make_bzrdir(self, relpath, format=None):
1239
url = self.get_url(relpath)
1240
mutter('relpath %r => url %r', relpath, url)
1241
segments = url.split('/')
1242
if segments and segments[-1] not in ('', '.'):
1243
parent = '/'.join(segments[:-1])
1244
t = get_transport(parent)
1246
t.mkdir(segments[-1])
1247
except errors.FileExists:
1250
format=bzrlib.bzrdir.BzrDirFormat.get_default_format()
1251
# FIXME: make this use a single transport someday. RBC 20060418
1252
return format.initialize_on_transport(get_transport(relpath))
1253
except errors.UninitializableFormat:
1254
raise TestSkipped("Format %s is not initializable." % format)
1256
def make_repository(self, relpath, shared=False, format=None):
1257
"""Create a repository on our default transport at relpath."""
1258
made_control = self.make_bzrdir(relpath, format=format)
1259
return made_control.create_repository(shared=shared)
1261
def make_branch_and_tree(self, relpath, format=None):
1262
"""Create a branch on the transport and a tree locally.
1266
# TODO: always use the local disk path for the working tree,
1267
# this obviously requires a format that supports branch references
1268
# so check for that by checking bzrdir.BzrDirFormat.get_default_format()
1270
b = self.make_branch(relpath, format=format)
1272
return b.bzrdir.create_workingtree()
1273
except errors.NotLocalUrl:
1274
# new formats - catch No tree error and create
1275
# a branch reference and a checkout.
1276
# old formats at that point - raise TestSkipped.
1277
# TODO: rbc 20060208
1278
return WorkingTreeFormat2().initialize(bzrdir.BzrDir.open(relpath))
1280
def assertIsDirectory(self, relpath, transport):
1281
"""Assert that relpath within transport is a directory.
1283
This may not be possible on all transports; in that case it propagates
1284
a TransportNotPossible.
1287
mode = transport.stat(relpath).st_mode
1288
except errors.NoSuchFile:
1289
self.fail("path %s is not a directory; no such file"
1291
if not stat.S_ISDIR(mode):
1292
self.fail("path %s is not a directory; has mode %#o"
1296
class ChrootedTestCase(TestCaseWithTransport):
1297
"""A support class that provides readonly urls outside the local namespace.
1299
This is done by checking if self.transport_server is a MemoryServer. if it
1300
is then we are chrooted already, if it is not then an HttpServer is used
1303
TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
1304
be used without needed to redo it when a different
1305
subclass is in use ?
1309
super(ChrootedTestCase, self).setUp()
1310
if not self.transport_server == bzrlib.transport.memory.MemoryServer:
1311
self.transport_readonly_server = bzrlib.transport.http.HttpServer
1314
def filter_suite_by_re(suite, pattern):
1315
result = TestUtil.TestSuite()
1316
filter_re = re.compile(pattern)
1317
for test in iter_suite_tests(suite):
1318
if filter_re.search(test.id()):
1319
result.addTest(test)
1323
def run_suite(suite, name='test', verbose=False, pattern=".*",
1324
stop_on_failure=False, keep_output=False,
1325
transport=None, lsprof_timed=None, bench_history=None):
1326
TestCaseInTempDir._TEST_NAME = name
1327
TestCase._gather_lsprof_in_benchmarks = lsprof_timed
1333
pb = progress.ProgressBar()
1334
runner = TextTestRunner(stream=sys.stdout,
1336
verbosity=verbosity,
1337
keep_output=keep_output,
1339
bench_history=bench_history)
1340
runner.stop_on_failure=stop_on_failure
1342
suite = filter_suite_by_re(suite, pattern)
1343
result = runner.run(suite)
1344
return result.wasSuccessful()
1347
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
1350
test_suite_factory=None,
1352
bench_history=None):
1353
"""Run the whole test suite under the enhanced runner"""
1354
# XXX: Very ugly way to do this...
1355
# Disable warning about old formats because we don't want it to disturb
1356
# any blackbox tests.
1357
from bzrlib import repository
1358
repository._deprecation_warning_done = True
1360
global default_transport
1361
if transport is None:
1362
transport = default_transport
1363
old_transport = default_transport
1364
default_transport = transport
1366
if test_suite_factory is None:
1367
suite = test_suite()
1369
suite = test_suite_factory()
1370
return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
1371
stop_on_failure=stop_on_failure, keep_output=keep_output,
1372
transport=transport,
1373
lsprof_timed=lsprof_timed,
1374
bench_history=bench_history)
1376
default_transport = old_transport
1380
"""Build and return TestSuite for the whole of bzrlib.
1382
This function can be replaced if you need to change the default test
1383
suite on a global basis, but it is not encouraged.
1386
'bzrlib.tests.test_ancestry',
1387
'bzrlib.tests.test_api',
1388
'bzrlib.tests.test_atomicfile',
1389
'bzrlib.tests.test_bad_files',
1390
'bzrlib.tests.test_branch',
1391
'bzrlib.tests.test_bundle',
1392
'bzrlib.tests.test_bzrdir',
1393
'bzrlib.tests.test_cache_utf8',
1394
'bzrlib.tests.test_command',
1395
'bzrlib.tests.test_commit',
1396
'bzrlib.tests.test_commit_merge',
1397
'bzrlib.tests.test_config',
1398
'bzrlib.tests.test_conflicts',
1399
'bzrlib.tests.test_decorators',
1400
'bzrlib.tests.test_diff',
1401
'bzrlib.tests.test_doc_generate',
1402
'bzrlib.tests.test_errors',
1403
'bzrlib.tests.test_escaped_store',
1404
'bzrlib.tests.test_fetch',
1405
'bzrlib.tests.test_gpg',
1406
'bzrlib.tests.test_graph',
1407
'bzrlib.tests.test_hashcache',
1408
'bzrlib.tests.test_http',
1409
'bzrlib.tests.test_http_response',
1410
'bzrlib.tests.test_identitymap',
1411
'bzrlib.tests.test_ignores',
1412
'bzrlib.tests.test_inv',
1413
'bzrlib.tests.test_knit',
1414
'bzrlib.tests.test_lazy_import',
1415
'bzrlib.tests.test_lockdir',
1416
'bzrlib.tests.test_lockable_files',
1417
'bzrlib.tests.test_log',
1418
'bzrlib.tests.test_merge',
1419
'bzrlib.tests.test_merge3',
1420
'bzrlib.tests.test_merge_core',
1421
'bzrlib.tests.test_missing',
1422
'bzrlib.tests.test_msgeditor',
1423
'bzrlib.tests.test_nonascii',
1424
'bzrlib.tests.test_options',
1425
'bzrlib.tests.test_osutils',
1426
'bzrlib.tests.test_patch',
1427
'bzrlib.tests.test_patches',
1428
'bzrlib.tests.test_permissions',
1429
'bzrlib.tests.test_plugins',
1430
'bzrlib.tests.test_progress',
1431
'bzrlib.tests.test_reconcile',
1432
'bzrlib.tests.test_repository',
1433
'bzrlib.tests.test_revert',
1434
'bzrlib.tests.test_revision',
1435
'bzrlib.tests.test_revisionnamespaces',
1436
'bzrlib.tests.test_revisiontree',
1437
'bzrlib.tests.test_rio',
1438
'bzrlib.tests.test_sampler',
1439
'bzrlib.tests.test_selftest',
1440
'bzrlib.tests.test_setup',
1441
'bzrlib.tests.test_sftp_transport',
1442
'bzrlib.tests.test_ftp_transport',
1443
'bzrlib.tests.test_smart_add',
1444
'bzrlib.tests.test_source',
1445
'bzrlib.tests.test_status',
1446
'bzrlib.tests.test_store',
1447
'bzrlib.tests.test_symbol_versioning',
1448
'bzrlib.tests.test_testament',
1449
'bzrlib.tests.test_textfile',
1450
'bzrlib.tests.test_textmerge',
1451
'bzrlib.tests.test_trace',
1452
'bzrlib.tests.test_transactions',
1453
'bzrlib.tests.test_transform',
1454
'bzrlib.tests.test_transport',
1455
'bzrlib.tests.test_tree',
1456
'bzrlib.tests.test_tsort',
1457
'bzrlib.tests.test_tuned_gzip',
1458
'bzrlib.tests.test_ui',
1459
'bzrlib.tests.test_upgrade',
1460
'bzrlib.tests.test_urlutils',
1461
'bzrlib.tests.test_versionedfile',
1462
'bzrlib.tests.test_version',
1463
'bzrlib.tests.test_weave',
1464
'bzrlib.tests.test_whitebox',
1465
'bzrlib.tests.test_workingtree',
1466
'bzrlib.tests.test_xml',
1468
test_transport_implementations = [
1469
'bzrlib.tests.test_transport_implementations',
1470
'bzrlib.tests.test_read_bundle',
1472
suite = TestUtil.TestSuite()
1473
loader = TestUtil.TestLoader()
1474
suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
1475
from bzrlib.transport import TransportTestProviderAdapter
1476
adapter = TransportTestProviderAdapter()
1477
adapt_modules(test_transport_implementations, adapter, loader, suite)
1478
for package in packages_to_test():
1479
suite.addTest(package.test_suite())
1480
for m in MODULES_TO_TEST:
1481
suite.addTest(loader.loadTestsFromModule(m))
1482
for m in MODULES_TO_DOCTEST:
1484
suite.addTest(doctest.DocTestSuite(m))
1485
except ValueError, e:
1486
print '**failed to get doctest for: %s\n%s' %(m,e)
1488
for name, plugin in bzrlib.plugin.all_plugins().items():
1489
if getattr(plugin, 'test_suite', None) is not None:
1490
suite.addTest(plugin.test_suite())
1494
def adapt_modules(mods_list, adapter, loader, suite):
1495
"""Adapt the modules in mods_list using adapter and add to suite."""
1496
for test in iter_suite_tests(loader.loadTestsFromModuleNames(mods_list)):
1497
suite.addTests(adapter.adapt(test))