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
66
from bzrlib.revisionspec import RevisionSpec
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 = [
88
bzrlib.bundle.serializer,
101
def packages_to_test():
102
"""Return a list of packages to test.
104
The packages are not globally imported so that import failures are
105
triggered when running selftest, not when importing the command.
108
import bzrlib.tests.blackbox
109
import bzrlib.tests.branch_implementations
110
import bzrlib.tests.bzrdir_implementations
111
import bzrlib.tests.interrepository_implementations
112
import bzrlib.tests.interversionedfile_implementations
113
import bzrlib.tests.intertree_implementations
114
import bzrlib.tests.repository_implementations
115
import bzrlib.tests.revisionstore_implementations
116
import bzrlib.tests.tree_implementations
117
import bzrlib.tests.workingtree_implementations
120
bzrlib.tests.blackbox,
121
bzrlib.tests.branch_implementations,
122
bzrlib.tests.bzrdir_implementations,
123
bzrlib.tests.interrepository_implementations,
124
bzrlib.tests.interversionedfile_implementations,
125
bzrlib.tests.intertree_implementations,
126
bzrlib.tests.repository_implementations,
127
bzrlib.tests.revisionstore_implementations,
128
bzrlib.tests.tree_implementations,
129
bzrlib.tests.workingtree_implementations,
133
class _MyResult(unittest._TextTestResult):
134
"""Custom TestResult.
136
Shows output in a different format, including displaying runtime for tests.
140
def __init__(self, stream, descriptions, verbosity, pb=None,
142
unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
144
if bench_history is not None:
145
#XXX is there a simpler way to get the revison id?
146
branch = bzrlib.branch.Branch.open_containing('.')[0]
147
revision_id = RevisionSpec(branch.revno()).in_history(branch).rev_id
148
bench_history.write("--date %s %s\n" % (time.time(), revision_id))
149
self._bench_history = bench_history
151
def extractBenchmarkTime(self, testCase):
152
"""Add a benchmark time for the current test case."""
153
self._benchmarkTime = getattr(testCase, "_benchtime", None)
155
def _elapsedTestTimeString(self):
156
"""Return a time string for the overall time the current test has taken."""
157
return self._formatTime(time.time() - self._start_time)
159
def _testTimeString(self):
160
if self._benchmarkTime is not None:
162
self._formatTime(self._benchmarkTime),
163
self._elapsedTestTimeString())
165
return " %s" % self._elapsedTestTimeString()
167
def _formatTime(self, seconds):
168
"""Format seconds as milliseconds with leading spaces."""
169
return "%5dms" % (1000 * seconds)
171
def _ellipsise_unimportant_words(self, a_string, final_width,
173
"""Add ellipses (sp?) for overly long strings.
175
:param keep_start: If true preserve the start of a_string rather
179
if len(a_string) > final_width:
180
result = a_string[:final_width-3] + '...'
184
if len(a_string) > final_width:
185
result = '...' + a_string[3-final_width:]
188
return result.ljust(final_width)
190
def startTest(self, test):
191
unittest.TestResult.startTest(self, test)
192
# In a short description, the important words are in
193
# the beginning, but in an id, the important words are
195
SHOW_DESCRIPTIONS = False
197
if not self.showAll and self.dots and self.pb is not None:
200
final_width = osutils.terminal_width()
201
final_width = final_width - 15 - 8
203
if SHOW_DESCRIPTIONS:
204
what = test.shortDescription()
206
what = self._ellipsise_unimportant_words(what, final_width, keep_start=True)
209
if what.startswith('bzrlib.tests.'):
211
what = self._ellipsise_unimportant_words(what, final_width)
213
self.stream.write(what)
214
elif self.dots and self.pb is not None:
215
self.pb.update(what, self.testsRun - 1, None)
217
self._recordTestStartTime()
219
def _recordTestStartTime(self):
220
"""Record that a test has started."""
221
self._start_time = time.time()
223
def addError(self, test, err):
224
if isinstance(err[1], TestSkipped):
225
return self.addSkipped(test, err)
226
unittest.TestResult.addError(self, test, err)
227
self.extractBenchmarkTime(test)
229
self.stream.writeln("ERROR %s" % self._testTimeString())
230
elif self.dots and self.pb is None:
231
self.stream.write('E')
233
self.pb.update(self._ellipsise_unimportant_words('ERROR', 13), self.testsRun, None)
234
self.pb.note(self._ellipsise_unimportant_words(
235
test.id() + ': ERROR',
236
osutils.terminal_width()))
241
def addFailure(self, test, err):
242
unittest.TestResult.addFailure(self, test, err)
243
self.extractBenchmarkTime(test)
245
self.stream.writeln(" FAIL %s" % self._testTimeString())
246
elif self.dots and self.pb is None:
247
self.stream.write('F')
249
self.pb.update(self._ellipsise_unimportant_words('FAIL', 13), self.testsRun, None)
250
self.pb.note(self._ellipsise_unimportant_words(
251
test.id() + ': FAIL',
252
osutils.terminal_width()))
257
def addSuccess(self, test):
258
self.extractBenchmarkTime(test)
259
if self._bench_history is not None:
260
if self._benchmarkTime is not None:
261
self._bench_history.write("%s %s\n" % (
262
self._formatTime(self._benchmarkTime),
265
self.stream.writeln(' OK %s' % self._testTimeString())
266
for bench_called, stats in getattr(test, '_benchcalls', []):
267
self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
268
stats.pprint(file=self.stream)
269
elif self.dots and self.pb is None:
270
self.stream.write('~')
272
self.pb.update(self._ellipsise_unimportant_words('OK', 13), self.testsRun, None)
274
unittest.TestResult.addSuccess(self, test)
276
def addSkipped(self, test, skip_excinfo):
277
self.extractBenchmarkTime(test)
279
print >>self.stream, ' SKIP %s' % self._testTimeString()
280
print >>self.stream, ' %s' % skip_excinfo[1]
281
elif self.dots and self.pb is None:
282
self.stream.write('S')
284
self.pb.update(self._ellipsise_unimportant_words('SKIP', 13), self.testsRun, None)
286
# seems best to treat this as success from point-of-view of unittest
287
# -- it actually does nothing so it barely matters :)
290
except KeyboardInterrupt:
293
self.addError(test, test.__exc_info())
295
unittest.TestResult.addSuccess(self, test)
297
def printErrorList(self, flavour, errors):
298
for test, err in errors:
299
self.stream.writeln(self.separator1)
300
self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
301
if getattr(test, '_get_log', None) is not None:
303
print >>self.stream, \
304
('vvvv[log from %s]' % test.id()).ljust(78,'-')
305
print >>self.stream, test._get_log()
306
print >>self.stream, \
307
('^^^^[log from %s]' % test.id()).ljust(78,'-')
308
self.stream.writeln(self.separator2)
309
self.stream.writeln("%s" % err)
312
class TextTestRunner(object):
313
stop_on_failure = False
322
self.stream = unittest._WritelnDecorator(stream)
323
self.descriptions = descriptions
324
self.verbosity = verbosity
325
self.keep_output = keep_output
327
self._bench_history = bench_history
329
def _makeResult(self):
330
result = _MyResult(self.stream,
334
bench_history=self._bench_history)
335
result.stop_early = self.stop_on_failure
339
"Run the given test case or test suite."
340
result = self._makeResult()
341
startTime = time.time()
342
if self.pb is not None:
343
self.pb.update('Running tests', 0, test.countTestCases())
345
stopTime = time.time()
346
timeTaken = stopTime - startTime
348
self.stream.writeln(result.separator2)
349
run = result.testsRun
350
self.stream.writeln("Ran %d test%s in %.3fs" %
351
(run, run != 1 and "s" or "", timeTaken))
352
self.stream.writeln()
353
if not result.wasSuccessful():
354
self.stream.write("FAILED (")
355
failed, errored = map(len, (result.failures, result.errors))
357
self.stream.write("failures=%d" % failed)
359
if failed: self.stream.write(", ")
360
self.stream.write("errors=%d" % errored)
361
self.stream.writeln(")")
363
self.stream.writeln("OK")
364
if self.pb is not None:
365
self.pb.update('Cleaning up', 0, 1)
366
# This is still a little bogus,
367
# but only a little. Folk not using our testrunner will
368
# have to delete their temp directories themselves.
369
test_root = TestCaseInTempDir.TEST_ROOT
370
if result.wasSuccessful() or not self.keep_output:
371
if test_root is not None:
372
# If LANG=C we probably have created some bogus paths
373
# which rmtree(unicode) will fail to delete
374
# so make sure we are using rmtree(str) to delete everything
375
# except on win32, where rmtree(str) will fail
376
# since it doesn't have the property of byte-stream paths
377
# (they are either ascii or mbcs)
378
if sys.platform == 'win32':
379
# make sure we are using the unicode win32 api
380
test_root = unicode(test_root)
382
test_root = test_root.encode(
383
sys.getfilesystemencoding())
384
osutils.rmtree(test_root)
386
if self.pb is not None:
387
self.pb.note("Failed tests working directories are in '%s'\n",
391
"Failed tests working directories are in '%s'\n" %
393
TestCaseInTempDir.TEST_ROOT = None
394
if self.pb is not None:
399
def iter_suite_tests(suite):
400
"""Return all tests in a suite, recursing through nested suites"""
401
for item in suite._tests:
402
if isinstance(item, unittest.TestCase):
404
elif isinstance(item, unittest.TestSuite):
405
for r in iter_suite_tests(item):
408
raise Exception('unknown object %r inside test suite %r'
412
class TestSkipped(Exception):
413
"""Indicates that a test was intentionally skipped, rather than failing."""
417
class CommandFailed(Exception):
421
class StringIOWrapper(object):
422
"""A wrapper around cStringIO which just adds an encoding attribute.
424
Internally we can check sys.stdout to see what the output encoding
425
should be. However, cStringIO has no encoding attribute that we can
426
set. So we wrap it instead.
431
def __init__(self, s=None):
433
self.__dict__['_cstring'] = StringIO(s)
435
self.__dict__['_cstring'] = StringIO()
437
def __getattr__(self, name, getattr=getattr):
438
return getattr(self.__dict__['_cstring'], name)
440
def __setattr__(self, name, val):
441
if name == 'encoding':
442
self.__dict__['encoding'] = val
444
return setattr(self._cstring, name, val)
447
class TestCase(unittest.TestCase):
448
"""Base class for bzr unit tests.
450
Tests that need access to disk resources should subclass
451
TestCaseInTempDir not TestCase.
453
Error and debug log messages are redirected from their usual
454
location into a temporary file, the contents of which can be
455
retrieved by _get_log(). We use a real OS file, not an in-memory object,
456
so that it can also capture file IO. When the test completes this file
457
is read into memory and removed from disk.
459
There are also convenience functions to invoke bzr's command-line
460
routine, and to build and check bzr trees.
462
In addition to the usual method of overriding tearDown(), this class also
463
allows subclasses to register functions into the _cleanups list, which is
464
run in order as the object is torn down. It's less likely this will be
465
accidentally overlooked.
468
_log_file_name = None
470
# record lsprof data when performing benchmark calls.
471
_gather_lsprof_in_benchmarks = False
473
def __init__(self, methodName='testMethod'):
474
super(TestCase, self).__init__(methodName)
478
unittest.TestCase.setUp(self)
479
self._cleanEnvironment()
480
bzrlib.trace.disable_default_logging()
482
self._benchcalls = []
483
self._benchtime = None
485
def _ndiff_strings(self, a, b):
486
"""Return ndiff between two strings containing lines.
488
A trailing newline is added if missing to make the strings
490
if b and b[-1] != '\n':
492
if a and a[-1] != '\n':
494
difflines = difflib.ndiff(a.splitlines(True),
496
linejunk=lambda x: False,
497
charjunk=lambda x: False)
498
return ''.join(difflines)
500
def assertEqualDiff(self, a, b, message=None):
501
"""Assert two texts are equal, if not raise an exception.
503
This is intended for use with multi-line strings where it can
504
be hard to find the differences by eye.
506
# TODO: perhaps override assertEquals to call this for strings?
510
message = "texts not equal:\n"
511
raise AssertionError(message +
512
self._ndiff_strings(a, b))
514
def assertEqualMode(self, mode, mode_test):
515
self.assertEqual(mode, mode_test,
516
'mode mismatch %o != %o' % (mode, mode_test))
518
def assertStartsWith(self, s, prefix):
519
if not s.startswith(prefix):
520
raise AssertionError('string %r does not start with %r' % (s, prefix))
522
def assertEndsWith(self, s, suffix):
523
"""Asserts that s ends with suffix."""
524
if not s.endswith(suffix):
525
raise AssertionError('string %r does not end with %r' % (s, suffix))
527
def assertContainsRe(self, haystack, needle_re):
528
"""Assert that a contains something matching a regular expression."""
529
if not re.search(needle_re, haystack):
530
raise AssertionError('pattern "%s" not found in "%s"'
531
% (needle_re, haystack))
533
def assertNotContainsRe(self, haystack, needle_re):
534
"""Assert that a does not match a regular expression"""
535
if re.search(needle_re, haystack):
536
raise AssertionError('pattern "%s" found in "%s"'
537
% (needle_re, haystack))
539
def assertSubset(self, sublist, superlist):
540
"""Assert that every entry in sublist is present in superlist."""
542
for entry in sublist:
543
if entry not in superlist:
544
missing.append(entry)
546
raise AssertionError("value(s) %r not present in container %r" %
547
(missing, superlist))
549
def assertIs(self, left, right):
550
if not (left is right):
551
raise AssertionError("%r is not %r." % (left, right))
553
def assertTransportMode(self, transport, path, mode):
554
"""Fail if a path does not have mode mode.
556
If modes are not supported on this transport, the assertion is ignored.
558
if not transport._can_roundtrip_unix_modebits():
560
path_stat = transport.stat(path)
561
actual_mode = stat.S_IMODE(path_stat.st_mode)
562
self.assertEqual(mode, actual_mode,
563
'mode of %r incorrect (%o != %o)' % (path, mode, actual_mode))
565
def assertIsInstance(self, obj, kls):
566
"""Fail if obj is not an instance of kls"""
567
if not isinstance(obj, kls):
568
self.fail("%r is an instance of %s rather than %s" % (
569
obj, obj.__class__, kls))
571
def _startLogFile(self):
572
"""Send bzr and test log messages to a temporary file.
574
The file is removed as the test is torn down.
576
fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
577
encoder, decoder, stream_reader, stream_writer = codecs.lookup('UTF-8')
578
self._log_file = stream_writer(os.fdopen(fileno, 'w+'))
579
self._log_nonce = bzrlib.trace.enable_test_log(self._log_file)
580
self._log_file_name = name
581
self.addCleanup(self._finishLogFile)
583
def _finishLogFile(self):
584
"""Finished with the log file.
586
Read contents into memory, close, and delete.
588
if self._log_file is None:
590
bzrlib.trace.disable_test_log(self._log_nonce)
591
self._log_file.seek(0)
592
self._log_contents = self._log_file.read()
593
self._log_file.close()
594
os.remove(self._log_file_name)
595
self._log_file = self._log_file_name = None
597
def addCleanup(self, callable):
598
"""Arrange to run a callable when this case is torn down.
600
Callables are run in the reverse of the order they are registered,
601
ie last-in first-out.
603
if callable in self._cleanups:
604
raise ValueError("cleanup function %r already registered on %s"
606
self._cleanups.append(callable)
608
def _cleanEnvironment(self):
611
'APPDATA': os.getcwd(),
613
'BZREMAIL': None, # may still be present in the environment
617
self.addCleanup(self._restoreEnvironment)
618
for name, value in new_env.iteritems():
619
self._captureVar(name, value)
622
def _captureVar(self, name, newvalue):
623
"""Set an environment variable, preparing it to be reset when finished."""
624
self.__old_env[name] = os.environ.get(name, None)
626
if name in os.environ:
629
os.environ[name] = newvalue
632
def _restoreVar(name, value):
634
if name in os.environ:
637
os.environ[name] = value
639
def _restoreEnvironment(self):
640
for name, value in self.__old_env.iteritems():
641
self._restoreVar(name, value)
645
unittest.TestCase.tearDown(self)
647
def time(self, callable, *args, **kwargs):
648
"""Run callable and accrue the time it takes to the benchmark time.
650
If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
651
this will cause lsprofile statistics to be gathered and stored in
654
if self._benchtime is None:
658
if not self._gather_lsprof_in_benchmarks:
659
return callable(*args, **kwargs)
661
# record this benchmark
662
ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
664
self._benchcalls.append(((callable, args, kwargs), stats))
667
self._benchtime += time.time() - start
669
def _runCleanups(self):
670
"""Run registered cleanup functions.
672
This should only be called from TestCase.tearDown.
674
# TODO: Perhaps this should keep running cleanups even if
676
for cleanup_fn in reversed(self._cleanups):
679
def log(self, *args):
683
"""Return as a string the log for this test"""
684
if self._log_file_name:
685
return open(self._log_file_name).read()
687
return self._log_contents
688
# TODO: Delete the log after it's been read in
690
def capture(self, cmd, retcode=0):
691
"""Shortcut that splits cmd into words, runs, and returns stdout"""
692
return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
694
def run_bzr_captured(self, argv, retcode=0, encoding=None, stdin=None):
695
"""Invoke bzr and return (stdout, stderr).
697
Useful for code that wants to check the contents of the
698
output, the way error messages are presented, etc.
700
This should be the main method for tests that want to exercise the
701
overall behavior of the bzr application (rather than a unit test
702
or a functional test of the library.)
704
Much of the old code runs bzr by forking a new copy of Python, but
705
that is slower, harder to debug, and generally not necessary.
707
This runs bzr through the interface that catches and reports
708
errors, and with logging set to something approximating the
709
default, so that error reporting can be checked.
711
:param argv: arguments to invoke bzr
712
:param retcode: expected return code, or None for don't-care.
713
:param encoding: encoding for sys.stdout and sys.stderr
714
:param stdin: A string to be used as stdin for the command.
717
encoding = bzrlib.user_encoding
718
if stdin is not None:
719
stdin = StringIO(stdin)
720
stdout = StringIOWrapper()
721
stderr = StringIOWrapper()
722
stdout.encoding = encoding
723
stderr.encoding = encoding
725
self.log('run bzr: %r', argv)
726
# FIXME: don't call into logging here
727
handler = logging.StreamHandler(stderr)
728
handler.setLevel(logging.INFO)
729
logger = logging.getLogger('')
730
logger.addHandler(handler)
731
old_ui_factory = bzrlib.ui.ui_factory
732
bzrlib.ui.ui_factory = bzrlib.tests.blackbox.TestUIFactory(
735
bzrlib.ui.ui_factory.stdin = stdin
737
result = self.apply_redirected(stdin, stdout, stderr,
738
bzrlib.commands.run_bzr_catch_errors,
741
logger.removeHandler(handler)
742
bzrlib.ui.ui_factory = old_ui_factory
744
out = stdout.getvalue()
745
err = stderr.getvalue()
747
self.log('output:\n%r', out)
749
self.log('errors:\n%r', err)
750
if retcode is not None:
751
self.assertEquals(retcode, result)
754
def run_bzr(self, *args, **kwargs):
755
"""Invoke bzr, as if it were run from the command line.
757
This should be the main method for tests that want to exercise the
758
overall behavior of the bzr application (rather than a unit test
759
or a functional test of the library.)
761
This sends the stdout/stderr results into the test's log,
762
where it may be useful for debugging. See also run_captured.
764
:param stdin: A string to be used as stdin for the command.
766
retcode = kwargs.pop('retcode', 0)
767
encoding = kwargs.pop('encoding', None)
768
stdin = kwargs.pop('stdin', None)
769
return self.run_bzr_captured(args, retcode=retcode, encoding=encoding, stdin=stdin)
771
def run_bzr_decode(self, *args, **kwargs):
772
if kwargs.has_key('encoding'):
773
encoding = kwargs['encoding']
775
encoding = bzrlib.user_encoding
776
return self.run_bzr(*args, **kwargs)[0].decode(encoding)
778
def run_bzr_error(self, error_regexes, *args, **kwargs):
779
"""Run bzr, and check that stderr contains the supplied regexes
781
:param error_regexes: Sequence of regular expressions which
782
must each be found in the error output. The relative ordering
784
:param args: command-line arguments for bzr
785
:param kwargs: Keyword arguments which are interpreted by run_bzr
786
This function changes the default value of retcode to be 3,
787
since in most cases this is run when you expect bzr to fail.
788
:return: (out, err) The actual output of running the command (in case you
789
want to do more inspection)
792
# Make sure that commit is failing because there is nothing to do
793
self.run_bzr_error(['no changes to commit'],
794
'commit', '-m', 'my commit comment')
795
# Make sure --strict is handling an unknown file, rather than
796
# giving us the 'nothing to do' error
797
self.build_tree(['unknown'])
798
self.run_bzr_error(['Commit refused because there are unknown files'],
799
'commit', '--strict', '-m', 'my commit comment')
801
kwargs.setdefault('retcode', 3)
802
out, err = self.run_bzr(*args, **kwargs)
803
for regex in error_regexes:
804
self.assertContainsRe(err, regex)
807
def run_bzr_subprocess(self, *args, **kwargs):
808
"""Run bzr in a subprocess for testing.
810
This starts a new Python interpreter and runs bzr in there.
811
This should only be used for tests that have a justifiable need for
812
this isolation: e.g. they are testing startup time, or signal
813
handling, or early startup code, etc. Subprocess code can't be
814
profiled or debugged so easily.
816
:param retcode: The status code that is expected. Defaults to 0. If
817
None is supplied, the status code is not checked.
819
bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
821
process = Popen([sys.executable, bzr_path]+args, stdout=PIPE,
823
out = process.stdout.read()
824
err = process.stderr.read()
825
retcode = process.wait()
826
supplied_retcode = kwargs.get('retcode', 0)
827
if supplied_retcode is not None:
828
assert supplied_retcode == retcode
831
def check_inventory_shape(self, inv, shape):
832
"""Compare an inventory to a list of expected names.
834
Fail if they are not precisely equal.
837
shape = list(shape) # copy
838
for path, ie in inv.entries():
839
name = path.replace('\\', '/')
847
self.fail("expected paths not found in inventory: %r" % shape)
849
self.fail("unexpected paths found in inventory: %r" % extras)
851
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
852
a_callable=None, *args, **kwargs):
853
"""Call callable with redirected std io pipes.
855
Returns the return code."""
856
if not callable(a_callable):
857
raise ValueError("a_callable must be callable.")
861
if getattr(self, "_log_file", None) is not None:
862
stdout = self._log_file
866
if getattr(self, "_log_file", None is not None):
867
stderr = self._log_file
870
real_stdin = sys.stdin
871
real_stdout = sys.stdout
872
real_stderr = sys.stderr
877
return a_callable(*args, **kwargs)
879
sys.stdout = real_stdout
880
sys.stderr = real_stderr
881
sys.stdin = real_stdin
883
def merge(self, branch_from, wt_to):
884
"""A helper for tests to do a ui-less merge.
886
This should move to the main library when someone has time to integrate
889
# minimal ui-less merge.
890
wt_to.branch.fetch(branch_from)
891
base_rev = common_ancestor(branch_from.last_revision(),
892
wt_to.branch.last_revision(),
893
wt_to.branch.repository)
894
merge_inner(wt_to.branch, branch_from.basis_tree(),
895
wt_to.branch.repository.revision_tree(base_rev),
897
wt_to.add_pending_merge(branch_from.last_revision())
900
BzrTestBase = TestCase
903
class TestCaseInTempDir(TestCase):
904
"""Derived class that runs a test within a temporary directory.
906
This is useful for tests that need to create a branch, etc.
908
The directory is created in a slightly complex way: for each
909
Python invocation, a new temporary top-level directory is created.
910
All test cases create their own directory within that. If the
911
tests complete successfully, the directory is removed.
913
InTempDir is an old alias for FunctionalTestCase.
918
OVERRIDE_PYTHON = 'python'
920
def check_file_contents(self, filename, expect):
921
self.log("check contents of file %s" % filename)
922
contents = file(filename, 'r').read()
923
if contents != expect:
924
self.log("expected: %r" % expect)
925
self.log("actually: %r" % contents)
926
self.fail("contents of %s not as expected" % filename)
928
def _make_test_root(self):
929
if TestCaseInTempDir.TEST_ROOT is not None:
933
root = u'test%04d.tmp' % i
937
if e.errno == errno.EEXIST:
942
# successfully created
943
TestCaseInTempDir.TEST_ROOT = osutils.abspath(root)
945
# make a fake bzr directory there to prevent any tests propagating
946
# up onto the source directory's real branch
947
bzrdir.BzrDir.create_standalone_workingtree(TestCaseInTempDir.TEST_ROOT)
950
super(TestCaseInTempDir, self).setUp()
951
self._make_test_root()
952
_currentdir = os.getcwdu()
953
# shorten the name, to avoid test failures due to path length
954
short_id = self.id().replace('bzrlib.tests.', '') \
955
.replace('__main__.', '')[-100:]
956
# it's possible the same test class is run several times for
957
# parameterized tests, so make sure the names don't collide.
961
candidate_dir = '%s/%s.%d' % (self.TEST_ROOT, short_id, i)
963
candidate_dir = '%s/%s' % (self.TEST_ROOT, short_id)
964
if os.path.exists(candidate_dir):
968
self.test_dir = candidate_dir
969
os.mkdir(self.test_dir)
970
os.chdir(self.test_dir)
972
os.environ['HOME'] = self.test_dir
973
os.environ['APPDATA'] = self.test_dir
974
def _leaveDirectory():
975
os.chdir(_currentdir)
976
self.addCleanup(_leaveDirectory)
978
def build_tree(self, shape, line_endings='native', transport=None):
979
"""Build a test tree according to a pattern.
981
shape is a sequence of file specifications. If the final
982
character is '/', a directory is created.
984
This assumes that all the elements in the tree being built are new.
986
This doesn't add anything to a branch.
987
:param line_endings: Either 'binary' or 'native'
988
in binary mode, exact contents are written
989
in native mode, the line endings match the
990
default platform endings.
992
:param transport: A transport to write to, for building trees on
993
VFS's. If the transport is readonly or None,
994
"." is opened automatically.
996
# It's OK to just create them using forward slashes on windows.
997
if transport is None or transport.is_readonly():
998
transport = get_transport(".")
1000
self.assert_(isinstance(name, basestring))
1002
transport.mkdir(urlutils.escape(name[:-1]))
1004
if line_endings == 'binary':
1006
elif line_endings == 'native':
1009
raise errors.BzrError('Invalid line ending request %r' % (line_endings,))
1010
content = "contents of %s%s" % (name.encode('utf-8'), end)
1011
# Technically 'put()' is the right command. However, put
1012
# uses an AtomicFile, which requires an extra rename into place
1013
# As long as the files didn't exist in the past, append() will
1014
# do the same thing as put()
1015
# On jam's machine, make_kernel_like_tree is:
1016
# put: 4.5-7.5s (averaging 6s)
1018
transport.append(urlutils.escape(name), StringIO(content))
1020
def build_tree_contents(self, shape):
1021
build_tree_contents(shape)
1023
def failUnlessExists(self, path):
1024
"""Fail unless path, which may be abs or relative, exists."""
1025
self.failUnless(osutils.lexists(path))
1027
def failIfExists(self, path):
1028
"""Fail if path, which may be abs or relative, exists."""
1029
self.failIf(osutils.lexists(path))
1031
def assertFileEqual(self, content, path):
1032
"""Fail if path does not contain 'content'."""
1033
self.failUnless(osutils.lexists(path))
1034
# TODO: jam 20060427 Shouldn't this be 'rb'?
1035
self.assertEqualDiff(content, open(path, 'r').read())
1038
class TestCaseWithTransport(TestCaseInTempDir):
1039
"""A test case that provides get_url and get_readonly_url facilities.
1041
These back onto two transport servers, one for readonly access and one for
1044
If no explicit class is provided for readonly access, a
1045
ReadonlyTransportDecorator is used instead which allows the use of non disk
1046
based read write transports.
1048
If an explicit class is provided for readonly access, that server and the
1049
readwrite one must both define get_url() as resolving to os.getcwd().
1052
def __init__(self, methodName='testMethod'):
1053
super(TestCaseWithTransport, self).__init__(methodName)
1054
self.__readonly_server = None
1055
self.__server = None
1056
self.transport_server = default_transport
1057
self.transport_readonly_server = None
1059
def get_readonly_url(self, relpath=None):
1060
"""Get a URL for the readonly transport.
1062
This will either be backed by '.' or a decorator to the transport
1063
used by self.get_url()
1064
relpath provides for clients to get a path relative to the base url.
1065
These should only be downwards relative, not upwards.
1067
base = self.get_readonly_server().get_url()
1068
if relpath is not None:
1069
if not base.endswith('/'):
1071
base = base + relpath
1074
def get_readonly_server(self):
1075
"""Get the server instance for the readonly transport
1077
This is useful for some tests with specific servers to do diagnostics.
1079
if self.__readonly_server is None:
1080
if self.transport_readonly_server is None:
1081
# readonly decorator requested
1082
# bring up the server
1084
self.__readonly_server = ReadonlyServer()
1085
self.__readonly_server.setUp(self.__server)
1087
self.__readonly_server = self.transport_readonly_server()
1088
self.__readonly_server.setUp()
1089
self.addCleanup(self.__readonly_server.tearDown)
1090
return self.__readonly_server
1092
def get_server(self):
1093
"""Get the read/write server instance.
1095
This is useful for some tests with specific servers that need
1098
if self.__server is None:
1099
self.__server = self.transport_server()
1100
self.__server.setUp()
1101
self.addCleanup(self.__server.tearDown)
1102
return self.__server
1104
def get_url(self, relpath=None):
1105
"""Get a URL for the readwrite transport.
1107
This will either be backed by '.' or to an equivalent non-file based
1109
relpath provides for clients to get a path relative to the base url.
1110
These should only be downwards relative, not upwards.
1112
base = self.get_server().get_url()
1113
if relpath is not None and relpath != '.':
1114
if not base.endswith('/'):
1116
base = base + urlutils.escape(relpath)
1119
def get_transport(self):
1120
"""Return a writeable transport for the test scratch space"""
1121
t = get_transport(self.get_url())
1122
self.assertFalse(t.is_readonly())
1125
def get_readonly_transport(self):
1126
"""Return a readonly transport for the test scratch space
1128
This can be used to test that operations which should only need
1129
readonly access in fact do not try to write.
1131
t = get_transport(self.get_readonly_url())
1132
self.assertTrue(t.is_readonly())
1135
def make_branch(self, relpath, format=None):
1136
"""Create a branch on the transport at relpath."""
1137
repo = self.make_repository(relpath, format=format)
1138
return repo.bzrdir.create_branch()
1140
def make_bzrdir(self, relpath, format=None):
1142
url = self.get_url(relpath)
1143
mutter('relpath %r => url %r', relpath, url)
1144
segments = url.split('/')
1145
if segments and segments[-1] not in ('', '.'):
1146
parent = '/'.join(segments[:-1])
1147
t = get_transport(parent)
1149
t.mkdir(segments[-1])
1150
except errors.FileExists:
1153
format=bzrlib.bzrdir.BzrDirFormat.get_default_format()
1154
# FIXME: make this use a single transport someday. RBC 20060418
1155
return format.initialize_on_transport(get_transport(relpath))
1156
except errors.UninitializableFormat:
1157
raise TestSkipped("Format %s is not initializable." % format)
1159
def make_repository(self, relpath, shared=False, format=None):
1160
"""Create a repository on our default transport at relpath."""
1161
made_control = self.make_bzrdir(relpath, format=format)
1162
return made_control.create_repository(shared=shared)
1164
def make_branch_and_tree(self, relpath, format=None):
1165
"""Create a branch on the transport and a tree locally.
1169
# TODO: always use the local disk path for the working tree,
1170
# this obviously requires a format that supports branch references
1171
# so check for that by checking bzrdir.BzrDirFormat.get_default_format()
1173
b = self.make_branch(relpath, format=format)
1175
return b.bzrdir.create_workingtree()
1176
except errors.NotLocalUrl:
1177
# new formats - catch No tree error and create
1178
# a branch reference and a checkout.
1179
# old formats at that point - raise TestSkipped.
1180
# TODO: rbc 20060208
1181
return WorkingTreeFormat2().initialize(bzrdir.BzrDir.open(relpath))
1183
def assertIsDirectory(self, relpath, transport):
1184
"""Assert that relpath within transport is a directory.
1186
This may not be possible on all transports; in that case it propagates
1187
a TransportNotPossible.
1190
mode = transport.stat(relpath).st_mode
1191
except errors.NoSuchFile:
1192
self.fail("path %s is not a directory; no such file"
1194
if not stat.S_ISDIR(mode):
1195
self.fail("path %s is not a directory; has mode %#o"
1199
class ChrootedTestCase(TestCaseWithTransport):
1200
"""A support class that provides readonly urls outside the local namespace.
1202
This is done by checking if self.transport_server is a MemoryServer. if it
1203
is then we are chrooted already, if it is not then an HttpServer is used
1206
TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
1207
be used without needed to redo it when a different
1208
subclass is in use ?
1212
super(ChrootedTestCase, self).setUp()
1213
if not self.transport_server == bzrlib.transport.memory.MemoryServer:
1214
self.transport_readonly_server = bzrlib.transport.http.HttpServer
1217
def filter_suite_by_re(suite, pattern):
1218
result = TestUtil.TestSuite()
1219
filter_re = re.compile(pattern)
1220
for test in iter_suite_tests(suite):
1221
if filter_re.search(test.id()):
1222
result.addTest(test)
1226
def run_suite(suite, name='test', verbose=False, pattern=".*",
1227
stop_on_failure=False, keep_output=False,
1228
transport=None, lsprof_timed=None, bench_history=None):
1229
TestCaseInTempDir._TEST_NAME = name
1230
TestCase._gather_lsprof_in_benchmarks = lsprof_timed
1236
pb = progress.ProgressBar()
1237
runner = TextTestRunner(stream=sys.stdout,
1239
verbosity=verbosity,
1240
keep_output=keep_output,
1242
bench_history=bench_history)
1243
runner.stop_on_failure=stop_on_failure
1245
suite = filter_suite_by_re(suite, pattern)
1246
result = runner.run(suite)
1247
return result.wasSuccessful()
1250
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
1253
test_suite_factory=None,
1255
bench_history=None):
1256
"""Run the whole test suite under the enhanced runner"""
1257
# XXX: Very ugly way to do this...
1258
# Disable warning about old formats because we don't want it to disturb
1259
# any blackbox tests.
1260
from bzrlib import repository
1261
repository._deprecation_warning_done = True
1263
global default_transport
1264
if transport is None:
1265
transport = default_transport
1266
old_transport = default_transport
1267
default_transport = transport
1269
if test_suite_factory is None:
1270
suite = test_suite()
1272
suite = test_suite_factory()
1273
return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
1274
stop_on_failure=stop_on_failure, keep_output=keep_output,
1275
transport=transport,
1276
lsprof_timed=lsprof_timed,
1277
bench_history=bench_history)
1279
default_transport = old_transport
1283
"""Build and return TestSuite for the whole of bzrlib.
1285
This function can be replaced if you need to change the default test
1286
suite on a global basis, but it is not encouraged.
1289
'bzrlib.tests.test_ancestry',
1290
'bzrlib.tests.test_api',
1291
'bzrlib.tests.test_atomicfile',
1292
'bzrlib.tests.test_bad_files',
1293
'bzrlib.tests.test_branch',
1294
'bzrlib.tests.test_bundle',
1295
'bzrlib.tests.test_bzrdir',
1296
'bzrlib.tests.test_command',
1297
'bzrlib.tests.test_commit',
1298
'bzrlib.tests.test_commit_merge',
1299
'bzrlib.tests.test_config',
1300
'bzrlib.tests.test_conflicts',
1301
'bzrlib.tests.test_decorators',
1302
'bzrlib.tests.test_diff',
1303
'bzrlib.tests.test_doc_generate',
1304
'bzrlib.tests.test_errors',
1305
'bzrlib.tests.test_escaped_store',
1306
'bzrlib.tests.test_fetch',
1307
'bzrlib.tests.test_gpg',
1308
'bzrlib.tests.test_graph',
1309
'bzrlib.tests.test_hashcache',
1310
'bzrlib.tests.test_http',
1311
'bzrlib.tests.test_http_response',
1312
'bzrlib.tests.test_identitymap',
1313
'bzrlib.tests.test_ignores',
1314
'bzrlib.tests.test_inv',
1315
'bzrlib.tests.test_knit',
1316
'bzrlib.tests.test_lockdir',
1317
'bzrlib.tests.test_lockable_files',
1318
'bzrlib.tests.test_log',
1319
'bzrlib.tests.test_merge',
1320
'bzrlib.tests.test_merge3',
1321
'bzrlib.tests.test_merge_core',
1322
'bzrlib.tests.test_missing',
1323
'bzrlib.tests.test_msgeditor',
1324
'bzrlib.tests.test_nonascii',
1325
'bzrlib.tests.test_options',
1326
'bzrlib.tests.test_osutils',
1327
'bzrlib.tests.test_patch',
1328
'bzrlib.tests.test_patches',
1329
'bzrlib.tests.test_permissions',
1330
'bzrlib.tests.test_plugins',
1331
'bzrlib.tests.test_progress',
1332
'bzrlib.tests.test_reconcile',
1333
'bzrlib.tests.test_repository',
1334
'bzrlib.tests.test_revision',
1335
'bzrlib.tests.test_revisionnamespaces',
1336
'bzrlib.tests.test_revisiontree',
1337
'bzrlib.tests.test_rio',
1338
'bzrlib.tests.test_sampler',
1339
'bzrlib.tests.test_selftest',
1340
'bzrlib.tests.test_setup',
1341
'bzrlib.tests.test_sftp_transport',
1342
'bzrlib.tests.test_smart_add',
1343
'bzrlib.tests.test_source',
1344
'bzrlib.tests.test_status',
1345
'bzrlib.tests.test_store',
1346
'bzrlib.tests.test_symbol_versioning',
1347
'bzrlib.tests.test_testament',
1348
'bzrlib.tests.test_textfile',
1349
'bzrlib.tests.test_textmerge',
1350
'bzrlib.tests.test_trace',
1351
'bzrlib.tests.test_transactions',
1352
'bzrlib.tests.test_transform',
1353
'bzrlib.tests.test_transport',
1354
'bzrlib.tests.test_tree',
1355
'bzrlib.tests.test_tsort',
1356
'bzrlib.tests.test_tuned_gzip',
1357
'bzrlib.tests.test_ui',
1358
'bzrlib.tests.test_upgrade',
1359
'bzrlib.tests.test_urlutils',
1360
'bzrlib.tests.test_versionedfile',
1361
'bzrlib.tests.test_weave',
1362
'bzrlib.tests.test_whitebox',
1363
'bzrlib.tests.test_workingtree',
1364
'bzrlib.tests.test_xml',
1366
test_transport_implementations = [
1367
'bzrlib.tests.test_transport_implementations',
1368
'bzrlib.tests.test_read_bundle',
1370
suite = TestUtil.TestSuite()
1371
loader = TestUtil.TestLoader()
1372
suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
1373
from bzrlib.transport import TransportTestProviderAdapter
1374
adapter = TransportTestProviderAdapter()
1375
adapt_modules(test_transport_implementations, adapter, loader, suite)
1376
for package in packages_to_test():
1377
suite.addTest(package.test_suite())
1378
for m in MODULES_TO_TEST:
1379
suite.addTest(loader.loadTestsFromModule(m))
1380
for m in MODULES_TO_DOCTEST:
1381
suite.addTest(doctest.DocTestSuite(m))
1382
for name, plugin in bzrlib.plugin.all_plugins().items():
1383
if getattr(plugin, 'test_suite', None) is not None:
1384
suite.addTest(plugin.test_suite())
1388
def adapt_modules(mods_list, adapter, loader, suite):
1389
"""Adapt the modules in mods_list using adapter and add to suite."""
1390
for test in iter_suite_tests(loader.loadTestsFromModuleNames(mods_list)):
1391
suite.addTests(adapter.adapt(test))