1
# Copyright (C) 2005, 2006 by Canonical Ltd
1
# Copyright (C) 2005 by Canonical Ltd
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
11
# GNU General Public License for more details.
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
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
18
from cStringIO import StringIO
39
from subprocess import Popen, PIPE
47
import bzrlib.bzrdir as bzrdir
48
28
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
68
from bzrlib import symbol_versioning
69
29
import bzrlib.trace
70
from bzrlib.transport import get_transport
71
import bzrlib.transport
72
from bzrlib.transport.local import LocalRelpathServer
73
from bzrlib.transport.readonly import ReadonlyServer
74
from bzrlib.trace import mutter
75
from bzrlib.tests import TestUtil
76
from bzrlib.tests.TestUtil import (
80
from bzrlib.tests.treeshape import build_tree_contents
81
import bzrlib.urlutils as urlutils
82
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
31
from bzrlib.selftest import TestUtil
32
from bzrlib.selftest.TestUtil import TestLoader, TestSuite
84
default_transport = LocalRelpathServer
86
35
MODULES_TO_TEST = []
87
MODULES_TO_DOCTEST = [
89
bzrlib.bundle.serializer,
102
def packages_to_test():
103
"""Return a list of packages to test.
105
The packages are not globally imported so that import failures are
106
triggered when running selftest, not when importing the command.
109
import bzrlib.tests.blackbox
110
import bzrlib.tests.branch_implementations
111
import bzrlib.tests.bzrdir_implementations
112
import bzrlib.tests.interrepository_implementations
113
import bzrlib.tests.interversionedfile_implementations
114
import bzrlib.tests.intertree_implementations
115
import bzrlib.tests.repository_implementations
116
import bzrlib.tests.revisionstore_implementations
117
import bzrlib.tests.tree_implementations
118
import bzrlib.tests.workingtree_implementations
121
bzrlib.tests.blackbox,
122
bzrlib.tests.branch_implementations,
123
bzrlib.tests.bzrdir_implementations,
124
bzrlib.tests.interrepository_implementations,
125
bzrlib.tests.interversionedfile_implementations,
126
bzrlib.tests.intertree_implementations,
127
bzrlib.tests.repository_implementations,
128
bzrlib.tests.revisionstore_implementations,
129
bzrlib.tests.tree_implementations,
130
bzrlib.tests.workingtree_implementations,
36
MODULES_TO_DOCTEST = []
38
from logging import debug, warning, error
42
class EarlyStoppingTestResultAdapter(object):
43
"""An adapter for TestResult to stop at the first first failure or error"""
45
def __init__(self, result):
48
def addError(self, test, err):
49
self._result.addError(test, err)
52
def addFailure(self, test, err):
53
self._result.addFailure(test, err)
56
def __getattr__(self, name):
57
return getattr(self._result, name)
59
def __setattr__(self, name, value):
61
object.__setattr__(self, name, value)
62
return setattr(self._result, name, value)
134
65
class _MyResult(unittest._TextTestResult):
135
"""Custom TestResult.
137
Shows output in a different format, including displaying runtime for tests.
141
def __init__(self, stream, descriptions, verbosity, pb=None,
143
"""Construct new TestResult.
145
:param bench_history: Optionally, a writable file object to accumulate
148
unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
150
if bench_history is not None:
151
from bzrlib.version import _get_bzr_source_tree
152
src_tree = _get_bzr_source_tree()
154
revision_id = src_tree.last_revision()
156
# XXX: If there's no branch, what should we do?
158
bench_history.write("--date %s %s\n" % (time.time(), revision_id))
159
self._bench_history = bench_history
161
def extractBenchmarkTime(self, testCase):
162
"""Add a benchmark time for the current test case."""
163
self._benchmarkTime = getattr(testCase, "_benchtime", None)
165
def _elapsedTestTimeString(self):
166
"""Return a time string for the overall time the current test has taken."""
167
return self._formatTime(time.time() - self._start_time)
169
def _testTimeString(self):
170
if self._benchmarkTime is not None:
172
self._formatTime(self._benchmarkTime),
173
self._elapsedTestTimeString())
175
return " %s" % self._elapsedTestTimeString()
177
def _formatTime(self, seconds):
178
"""Format seconds as milliseconds with leading spaces."""
179
return "%5dms" % (1000 * seconds)
181
def _ellipsise_unimportant_words(self, a_string, final_width,
183
"""Add ellipses (sp?) for overly long strings.
185
:param keep_start: If true preserve the start of a_string rather
189
if len(a_string) > final_width:
190
result = a_string[:final_width-3] + '...'
194
if len(a_string) > final_width:
195
result = '...' + a_string[3-final_width:]
198
return result.ljust(final_width)
69
No special behaviour for now.
200
72
def startTest(self, test):
201
73
unittest.TestResult.startTest(self, test)
202
# In a short description, the important words are in
203
# the beginning, but in an id, the important words are
205
SHOW_DESCRIPTIONS = False
207
if not self.showAll and self.dots and self.pb is not None:
210
final_width = osutils.terminal_width()
211
final_width = final_width - 15 - 8
213
if SHOW_DESCRIPTIONS:
214
what = test.shortDescription()
216
what = self._ellipsise_unimportant_words(what, final_width, keep_start=True)
219
if what.startswith('bzrlib.tests.'):
221
what = self._ellipsise_unimportant_words(what, final_width)
74
# TODO: Maybe show test.shortDescription somewhere?
75
what = test.shortDescription() or test.id()
223
self.stream.write(what)
224
elif self.dots and self.pb is not None:
225
self.pb.update(what, self.testsRun - 1, None)
77
self.stream.write('%-70.70s' % what)
226
78
self.stream.flush()
227
self._recordTestStartTime()
229
def _recordTestStartTime(self):
230
"""Record that a test has started."""
231
self._start_time = time.time()
233
80
def addError(self, test, err):
234
if isinstance(err[1], TestSkipped):
235
return self.addSkipped(test, err)
236
unittest.TestResult.addError(self, test, err)
237
self.extractBenchmarkTime(test)
239
self.stream.writeln("ERROR %s" % self._testTimeString())
240
elif self.dots and self.pb is None:
241
self.stream.write('E')
243
self.pb.update(self._ellipsise_unimportant_words('ERROR', 13), self.testsRun, None)
244
self.pb.note(self._ellipsise_unimportant_words(
245
test.id() + ': ERROR',
246
osutils.terminal_width()))
81
super(_MyResult, self).addError(test, err)
247
82
self.stream.flush()
251
84
def addFailure(self, test, err):
252
unittest.TestResult.addFailure(self, test, err)
253
self.extractBenchmarkTime(test)
255
self.stream.writeln(" FAIL %s" % self._testTimeString())
256
elif self.dots and self.pb is None:
257
self.stream.write('F')
259
self.pb.update(self._ellipsise_unimportant_words('FAIL', 13), self.testsRun, None)
260
self.pb.note(self._ellipsise_unimportant_words(
261
test.id() + ': FAIL',
262
osutils.terminal_width()))
85
super(_MyResult, self).addFailure(test, err)
263
86
self.stream.flush()
267
88
def addSuccess(self, test):
268
self.extractBenchmarkTime(test)
269
if self._bench_history is not None:
270
if self._benchmarkTime is not None:
271
self._bench_history.write("%s %s\n" % (
272
self._formatTime(self._benchmarkTime),
275
self.stream.writeln(' OK %s' % self._testTimeString())
276
for bench_called, stats in getattr(test, '_benchcalls', []):
277
self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
278
stats.pprint(file=self.stream)
279
elif self.dots and self.pb is None:
90
self.stream.writeln('OK')
280
92
self.stream.write('~')
282
self.pb.update(self._ellipsise_unimportant_words('OK', 13), self.testsRun, None)
283
93
self.stream.flush()
284
94
unittest.TestResult.addSuccess(self, test)
286
def addSkipped(self, test, skip_excinfo):
287
self.extractBenchmarkTime(test)
289
print >>self.stream, ' SKIP %s' % self._testTimeString()
290
print >>self.stream, ' %s' % skip_excinfo[1]
291
elif self.dots and self.pb is None:
292
self.stream.write('S')
294
self.pb.update(self._ellipsise_unimportant_words('SKIP', 13), self.testsRun, None)
296
# seems best to treat this as success from point-of-view of unittest
297
# -- it actually does nothing so it barely matters :)
300
except KeyboardInterrupt:
303
self.addError(test, test.__exc_info())
305
unittest.TestResult.addSuccess(self, test)
307
96
def printErrorList(self, flavour, errors):
308
97
for test, err in errors:
309
98
self.stream.writeln(self.separator1)
310
self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
311
if getattr(test, '_get_log', None) is not None:
313
print >>self.stream, \
314
('vvvv[log from %s]' % test.id()).ljust(78,'-')
99
self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
100
if hasattr(test, '_get_log'):
101
self.stream.writeln()
102
self.stream.writeln('log from this test:')
315
103
print >>self.stream, test._get_log()
316
print >>self.stream, \
317
('^^^^[log from %s]' % test.id()).ljust(78,'-')
318
104
self.stream.writeln(self.separator2)
319
105
self.stream.writeln("%s" % err)
322
class TextTestRunner(object):
323
stop_on_failure = False
332
self.stream = unittest._WritelnDecorator(stream)
333
self.descriptions = descriptions
334
self.verbosity = verbosity
335
self.keep_output = keep_output
337
self._bench_history = bench_history
108
class TextTestRunner(unittest.TextTestRunner):
339
110
def _makeResult(self):
340
result = _MyResult(self.stream,
344
bench_history=self._bench_history)
345
result.stop_early = self.stop_on_failure
349
"Run the given test case or test suite."
350
result = self._makeResult()
351
startTime = time.time()
352
if self.pb is not None:
353
self.pb.update('Running tests', 0, test.countTestCases())
355
stopTime = time.time()
356
timeTaken = stopTime - startTime
358
self.stream.writeln(result.separator2)
359
run = result.testsRun
360
self.stream.writeln("Ran %d test%s in %.3fs" %
361
(run, run != 1 and "s" or "", timeTaken))
362
self.stream.writeln()
363
if not result.wasSuccessful():
364
self.stream.write("FAILED (")
365
failed, errored = map(len, (result.failures, result.errors))
367
self.stream.write("failures=%d" % failed)
369
if failed: self.stream.write(", ")
370
self.stream.write("errors=%d" % errored)
371
self.stream.writeln(")")
373
self.stream.writeln("OK")
374
if self.pb is not None:
375
self.pb.update('Cleaning up', 0, 1)
376
# This is still a little bogus,
377
# but only a little. Folk not using our testrunner will
378
# have to delete their temp directories themselves.
379
test_root = TestCaseInTempDir.TEST_ROOT
380
if result.wasSuccessful() or not self.keep_output:
381
if test_root is not None:
382
# If LANG=C we probably have created some bogus paths
383
# which rmtree(unicode) will fail to delete
384
# so make sure we are using rmtree(str) to delete everything
385
# except on win32, where rmtree(str) will fail
386
# since it doesn't have the property of byte-stream paths
387
# (they are either ascii or mbcs)
388
if sys.platform == 'win32':
389
# make sure we are using the unicode win32 api
390
test_root = unicode(test_root)
392
test_root = test_root.encode(
393
sys.getfilesystemencoding())
394
osutils.rmtree(test_root)
396
if self.pb is not None:
397
self.pb.note("Failed tests working directories are in '%s'\n",
401
"Failed tests working directories are in '%s'\n" %
403
TestCaseInTempDir.TEST_ROOT = None
404
if self.pb is not None:
409
def iter_suite_tests(suite):
410
"""Return all tests in a suite, recursing through nested suites"""
411
for item in suite._tests:
412
if isinstance(item, unittest.TestCase):
414
elif isinstance(item, unittest.TestSuite):
415
for r in iter_suite_tests(item):
418
raise Exception('unknown object %r inside test suite %r'
111
result = _MyResult(self.stream, self.descriptions, self.verbosity)
112
return EarlyStoppingTestResultAdapter(result)
115
class filteringVisitor(TestUtil.TestVisitor):
116
"""I accruse all the testCases I visit that pass a regexp filter on id
120
def __init__(self, filter):
122
TestUtil.TestVisitor.__init__(self)
124
self.filter=re.compile(filter)
127
"""answer the suite we are building"""
128
if self._suite is None:
129
self._suite=TestUtil.TestSuite()
132
def visitCase(self, aCase):
133
if self.filter.match(aCase.id()):
134
self.suite().addTest(aCase)
422
136
class TestSkipped(Exception):
423
137
"""Indicates that a test was intentionally skipped, rather than failing."""
426
141
class CommandFailed(Exception):
430
class StringIOWrapper(object):
431
"""A wrapper around cStringIO which just adds an encoding attribute.
433
Internally we can check sys.stdout to see what the output encoding
434
should be. However, cStringIO has no encoding attribute that we can
435
set. So we wrap it instead.
440
def __init__(self, s=None):
442
self.__dict__['_cstring'] = StringIO(s)
444
self.__dict__['_cstring'] = StringIO()
446
def __getattr__(self, name, getattr=getattr):
447
return getattr(self.__dict__['_cstring'], name)
449
def __setattr__(self, name, val):
450
if name == 'encoding':
451
self.__dict__['encoding'] = val
453
return setattr(self._cstring, name, val)
456
144
class TestCase(unittest.TestCase):
457
145
"""Base class for bzr unit tests.
462
150
Error and debug log messages are redirected from their usual
463
151
location into a temporary file, the contents of which can be
464
retrieved by _get_log(). We use a real OS file, not an in-memory object,
465
so that it can also capture file IO. When the test completes this file
466
is read into memory and removed from disk.
152
retrieved by _get_log().
468
154
There are also convenience functions to invoke bzr's command-line
469
routine, and to build and check bzr trees.
471
In addition to the usual method of overriding tearDown(), this class also
472
allows subclasses to register functions into the _cleanups list, which is
473
run in order as the object is torn down. It's less likely this will be
474
accidentally overlooked.
477
_log_file_name = None
479
# record lsprof data when performing benchmark calls.
480
_gather_lsprof_in_benchmarks = False
482
def __init__(self, methodName='testMethod'):
483
super(TestCase, self).__init__(methodName)
155
routine, and to build and check bzr trees."""
487
160
unittest.TestCase.setUp(self)
488
self._cleanEnvironment()
489
161
bzrlib.trace.disable_default_logging()
491
self._benchcalls = []
492
self._benchtime = None
494
def _ndiff_strings(self, a, b):
495
"""Return ndiff between two strings containing lines.
497
A trailing newline is added if missing to make the strings
499
if b and b[-1] != '\n':
501
if a and a[-1] != '\n':
503
difflines = difflib.ndiff(a.splitlines(True),
505
linejunk=lambda x: False,
506
charjunk=lambda x: False)
507
return ''.join(difflines)
509
def assertEqualDiff(self, a, b, message=None):
510
"""Assert two texts are equal, if not raise an exception.
512
This is intended for use with multi-line strings where it can
513
be hard to find the differences by eye.
515
# TODO: perhaps override assertEquals to call this for strings?
519
message = "texts not equal:\n"
520
raise AssertionError(message +
521
self._ndiff_strings(a, b))
523
def assertEqualMode(self, mode, mode_test):
524
self.assertEqual(mode, mode_test,
525
'mode mismatch %o != %o' % (mode, mode_test))
527
def assertStartsWith(self, s, prefix):
528
if not s.startswith(prefix):
529
raise AssertionError('string %r does not start with %r' % (s, prefix))
531
def assertEndsWith(self, s, suffix):
532
"""Asserts that s ends with suffix."""
533
if not s.endswith(suffix):
534
raise AssertionError('string %r does not end with %r' % (s, suffix))
536
def assertContainsRe(self, haystack, needle_re):
537
"""Assert that a contains something matching a regular expression."""
538
if not re.search(needle_re, haystack):
539
raise AssertionError('pattern "%s" not found in "%s"'
540
% (needle_re, haystack))
542
def assertNotContainsRe(self, haystack, needle_re):
543
"""Assert that a does not match a regular expression"""
544
if re.search(needle_re, haystack):
545
raise AssertionError('pattern "%s" found in "%s"'
546
% (needle_re, haystack))
548
def assertSubset(self, sublist, superlist):
549
"""Assert that every entry in sublist is present in superlist."""
551
for entry in sublist:
552
if entry not in superlist:
553
missing.append(entry)
555
raise AssertionError("value(s) %r not present in container %r" %
556
(missing, superlist))
558
def assertIs(self, left, right):
559
if not (left is right):
560
raise AssertionError("%r is not %r." % (left, right))
562
def assertTransportMode(self, transport, path, mode):
563
"""Fail if a path does not have mode mode.
565
If modes are not supported on this transport, the assertion is ignored.
567
if not transport._can_roundtrip_unix_modebits():
569
path_stat = transport.stat(path)
570
actual_mode = stat.S_IMODE(path_stat.st_mode)
571
self.assertEqual(mode, actual_mode,
572
'mode of %r incorrect (%o != %o)' % (path, mode, actual_mode))
574
def assertIsInstance(self, obj, kls):
575
"""Fail if obj is not an instance of kls"""
576
if not isinstance(obj, kls):
577
self.fail("%r is an instance of %s rather than %s" % (
578
obj, obj.__class__, kls))
580
def assertDeprecated(self, expected, callable, *args, **kwargs):
581
"""Assert that a callable is deprecated in a particular way.
583
:param expected: a list of the deprecation warnings expected, in order
584
:param callable: The callable to call
585
:param args: The positional arguments for the callable
586
:param kwargs: The keyword arguments for the callable
589
def capture_warnings(msg, cls, stacklevel=None):
590
self.assertEqual(cls, DeprecationWarning)
591
local_warnings.append(msg)
592
method = symbol_versioning.warn
593
symbol_versioning.set_warning_method(capture_warnings)
595
callable(*args, **kwargs)
597
result = symbol_versioning.set_warning_method(method)
598
self.assertEqual(expected, local_warnings)
601
def _startLogFile(self):
602
"""Send bzr and test log messages to a temporary file.
604
The file is removed as the test is torn down.
162
self._enable_file_logging()
165
def _enable_file_logging(self):
606
166
fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
607
encoder, decoder, stream_reader, stream_writer = codecs.lookup('UTF-8')
608
self._log_file = stream_writer(os.fdopen(fileno, 'w+'))
609
self._log_nonce = bzrlib.trace.enable_test_log(self._log_file)
168
self._log_file = os.fdopen(fileno, 'w+')
170
hdlr = logging.StreamHandler(self._log_file)
171
hdlr.setLevel(logging.DEBUG)
172
hdlr.setFormatter(logging.Formatter('%(levelname)8s %(message)s'))
173
logging.getLogger('').addHandler(hdlr)
174
logging.getLogger('').setLevel(logging.DEBUG)
175
self._log_hdlr = hdlr
176
debug('opened log file %s', name)
610
178
self._log_file_name = name
611
self.addCleanup(self._finishLogFile)
613
def _finishLogFile(self):
614
"""Finished with the log file.
616
Read contents into memory, close, and delete.
618
if self._log_file is None:
620
bzrlib.trace.disable_test_log(self._log_nonce)
621
self._log_file.seek(0)
622
self._log_contents = self._log_file.read()
181
logging.getLogger('').removeHandler(self._log_hdlr)
182
bzrlib.trace.enable_default_logging()
183
logging.debug('%s teardown', self.id())
623
184
self._log_file.close()
624
os.remove(self._log_file_name)
625
self._log_file = self._log_file_name = None
627
def addCleanup(self, callable):
628
"""Arrange to run a callable when this case is torn down.
630
Callables are run in the reverse of the order they are registered,
631
ie last-in first-out.
633
if callable in self._cleanups:
634
raise ValueError("cleanup function %r already registered on %s"
636
self._cleanups.append(callable)
638
def _cleanEnvironment(self):
641
'APPDATA': os.getcwd(),
643
'BZREMAIL': None, # may still be present in the environment
647
self.addCleanup(self._restoreEnvironment)
648
for name, value in new_env.iteritems():
649
self._captureVar(name, value)
652
def _captureVar(self, name, newvalue):
653
"""Set an environment variable, preparing it to be reset when finished."""
654
self.__old_env[name] = os.environ.get(name, None)
656
if name in os.environ:
659
os.environ[name] = newvalue
662
def _restoreVar(name, value):
664
if name in os.environ:
667
os.environ[name] = value
669
def _restoreEnvironment(self):
670
for name, value in self.__old_env.iteritems():
671
self._restoreVar(name, value)
675
185
unittest.TestCase.tearDown(self)
677
def time(self, callable, *args, **kwargs):
678
"""Run callable and accrue the time it takes to the benchmark time.
680
If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
681
this will cause lsprofile statistics to be gathered and stored in
684
if self._benchtime is None:
688
if not self._gather_lsprof_in_benchmarks:
689
return callable(*args, **kwargs)
691
# record this benchmark
692
ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
694
self._benchcalls.append(((callable, args, kwargs), stats))
697
self._benchtime += time.time() - start
699
def _runCleanups(self):
700
"""Run registered cleanup functions.
702
This should only be called from TestCase.tearDown.
704
# TODO: Perhaps this should keep running cleanups even if
706
for cleanup_fn in reversed(self._cleanups):
709
187
def log(self, *args):
712
190
def _get_log(self):
713
191
"""Return as a string the log for this test"""
714
if self._log_file_name:
715
return open(self._log_file_name).read()
717
return self._log_contents
718
# TODO: Delete the log after it's been read in
720
def capture(self, cmd, retcode=0):
192
return open(self._log_file_name).read()
195
def capture(self, cmd):
721
196
"""Shortcut that splits cmd into words, runs, and returns stdout"""
722
return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
197
return self.run_bzr_captured(cmd.split())[0]
724
def run_bzr_captured(self, argv, retcode=0, encoding=None, stdin=None):
725
"""Invoke bzr and return (stdout, stderr).
199
def run_bzr_captured(self, argv, retcode=0):
200
"""Invoke bzr and return (result, stdout, stderr).
727
202
Useful for code that wants to check the contents of the
728
203
output, the way error messages are presented, etc.
972
351
# successfully created
973
TestCaseInTempDir.TEST_ROOT = osutils.abspath(root)
352
TestCaseInTempDir.TEST_ROOT = os.path.abspath(root)
975
354
# make a fake bzr directory there to prevent any tests propagating
976
355
# up onto the source directory's real branch
977
bzrdir.BzrDir.create_standalone_workingtree(TestCaseInTempDir.TEST_ROOT)
356
os.mkdir(os.path.join(TestCaseInTempDir.TEST_ROOT, '.bzr'))
980
359
super(TestCaseInTempDir, self).setUp()
981
360
self._make_test_root()
982
_currentdir = os.getcwdu()
983
# shorten the name, to avoid test failures due to path length
984
short_id = self.id().replace('bzrlib.tests.', '') \
985
.replace('__main__.', '')[-100:]
986
# it's possible the same test class is run several times for
987
# parameterized tests, so make sure the names don't collide.
991
candidate_dir = '%s/%s.%d' % (self.TEST_ROOT, short_id, i)
993
candidate_dir = '%s/%s' % (self.TEST_ROOT, short_id)
994
if os.path.exists(candidate_dir):
998
self.test_dir = candidate_dir
999
os.mkdir(self.test_dir)
1000
os.chdir(self.test_dir)
1002
os.environ['HOME'] = self.test_dir
1003
os.environ['APPDATA'] = self.test_dir
1004
def _leaveDirectory():
1005
os.chdir(_currentdir)
1006
self.addCleanup(_leaveDirectory)
361
self._currentdir = os.getcwdu()
362
short_id = self.id().replace('bzrlib.selftest.', '') \
363
.replace('__main__.', '')
364
self.test_dir = os.path.join(self.TEST_ROOT, short_id)
365
os.mkdir(self.test_dir)
366
os.chdir(self.test_dir)
1008
def build_tree(self, shape, line_endings='native', transport=None):
369
os.chdir(self._currentdir)
370
super(TestCaseInTempDir, self).tearDown()
372
def build_tree(self, shape):
1009
373
"""Build a test tree according to a pattern.
1011
375
shape is a sequence of file specifications. If the final
1012
376
character is '/', a directory is created.
1014
This assumes that all the elements in the tree being built are new.
1016
378
This doesn't add anything to a branch.
1017
:param line_endings: Either 'binary' or 'native'
1018
in binary mode, exact contents are written
1019
in native mode, the line endings match the
1020
default platform endings.
1022
:param transport: A transport to write to, for building trees on
1023
VFS's. If the transport is readonly or None,
1024
"." is opened automatically.
1026
# It's OK to just create them using forward slashes on windows.
1027
if transport is None or transport.is_readonly():
1028
transport = get_transport(".")
380
# XXX: It's OK to just create them using forward slashes on windows?
1029
381
for name in shape:
1030
self.assert_(isinstance(name, basestring))
382
assert isinstance(name, basestring)
1031
383
if name[-1] == '/':
1032
transport.mkdir(urlutils.escape(name[:-1]))
1034
if line_endings == 'binary':
1036
elif line_endings == 'native':
1039
raise errors.BzrError('Invalid line ending request %r' % (line_endings,))
1040
content = "contents of %s%s" % (name.encode('utf-8'), end)
1041
# Technically 'put()' is the right command. However, put
1042
# uses an AtomicFile, which requires an extra rename into place
1043
# As long as the files didn't exist in the past, append() will
1044
# do the same thing as put()
1045
# On jam's machine, make_kernel_like_tree is:
1046
# put: 4.5-7.5s (averaging 6s)
1048
transport.append(urlutils.escape(name), StringIO(content))
1050
def build_tree_contents(self, shape):
1051
build_tree_contents(shape)
1053
def failUnlessExists(self, path):
1054
"""Fail unless path, which may be abs or relative, exists."""
1055
self.failUnless(osutils.lexists(path))
1057
def failIfExists(self, path):
1058
"""Fail if path, which may be abs or relative, exists."""
1059
self.failIf(osutils.lexists(path))
1061
def assertFileEqual(self, content, path):
1062
"""Fail if path does not contain 'content'."""
1063
self.failUnless(osutils.lexists(path))
1064
# TODO: jam 20060427 Shouldn't this be 'rb'?
1065
self.assertEqualDiff(content, open(path, 'r').read())
1068
class TestCaseWithTransport(TestCaseInTempDir):
1069
"""A test case that provides get_url and get_readonly_url facilities.
1071
These back onto two transport servers, one for readonly access and one for
1074
If no explicit class is provided for readonly access, a
1075
ReadonlyTransportDecorator is used instead which allows the use of non disk
1076
based read write transports.
1078
If an explicit class is provided for readonly access, that server and the
1079
readwrite one must both define get_url() as resolving to os.getcwd().
1082
def __init__(self, methodName='testMethod'):
1083
super(TestCaseWithTransport, self).__init__(methodName)
1084
self.__readonly_server = None
1085
self.__server = None
1086
self.transport_server = default_transport
1087
self.transport_readonly_server = None
1089
def get_readonly_url(self, relpath=None):
1090
"""Get a URL for the readonly transport.
1092
This will either be backed by '.' or a decorator to the transport
1093
used by self.get_url()
1094
relpath provides for clients to get a path relative to the base url.
1095
These should only be downwards relative, not upwards.
1097
base = self.get_readonly_server().get_url()
1098
if relpath is not None:
1099
if not base.endswith('/'):
1101
base = base + relpath
1104
def get_readonly_server(self):
1105
"""Get the server instance for the readonly transport
1107
This is useful for some tests with specific servers to do diagnostics.
1109
if self.__readonly_server is None:
1110
if self.transport_readonly_server is None:
1111
# readonly decorator requested
1112
# bring up the server
1114
self.__readonly_server = ReadonlyServer()
1115
self.__readonly_server.setUp(self.__server)
1117
self.__readonly_server = self.transport_readonly_server()
1118
self.__readonly_server.setUp()
1119
self.addCleanup(self.__readonly_server.tearDown)
1120
return self.__readonly_server
1122
def get_server(self):
1123
"""Get the read/write server instance.
1125
This is useful for some tests with specific servers that need
1128
if self.__server is None:
1129
self.__server = self.transport_server()
1130
self.__server.setUp()
1131
self.addCleanup(self.__server.tearDown)
1132
return self.__server
1134
def get_url(self, relpath=None):
1135
"""Get a URL for the readwrite transport.
1137
This will either be backed by '.' or to an equivalent non-file based
1139
relpath provides for clients to get a path relative to the base url.
1140
These should only be downwards relative, not upwards.
1142
base = self.get_server().get_url()
1143
if relpath is not None and relpath != '.':
1144
if not base.endswith('/'):
1146
base = base + urlutils.escape(relpath)
1149
def get_transport(self):
1150
"""Return a writeable transport for the test scratch space"""
1151
t = get_transport(self.get_url())
1152
self.assertFalse(t.is_readonly())
1155
def get_readonly_transport(self):
1156
"""Return a readonly transport for the test scratch space
1158
This can be used to test that operations which should only need
1159
readonly access in fact do not try to write.
1161
t = get_transport(self.get_readonly_url())
1162
self.assertTrue(t.is_readonly())
1165
def make_branch(self, relpath, format=None):
1166
"""Create a branch on the transport at relpath."""
1167
repo = self.make_repository(relpath, format=format)
1168
return repo.bzrdir.create_branch()
1170
def make_bzrdir(self, relpath, format=None):
1172
url = self.get_url(relpath)
1173
mutter('relpath %r => url %r', relpath, url)
1174
segments = url.split('/')
1175
if segments and segments[-1] not in ('', '.'):
1176
parent = '/'.join(segments[:-1])
1177
t = get_transport(parent)
1179
t.mkdir(segments[-1])
1180
except errors.FileExists:
1183
format=bzrlib.bzrdir.BzrDirFormat.get_default_format()
1184
# FIXME: make this use a single transport someday. RBC 20060418
1185
return format.initialize_on_transport(get_transport(relpath))
1186
except errors.UninitializableFormat:
1187
raise TestSkipped("Format %s is not initializable." % format)
1189
def make_repository(self, relpath, shared=False, format=None):
1190
"""Create a repository on our default transport at relpath."""
1191
made_control = self.make_bzrdir(relpath, format=format)
1192
return made_control.create_repository(shared=shared)
1194
def make_branch_and_tree(self, relpath, format=None):
1195
"""Create a branch on the transport and a tree locally.
1199
# TODO: always use the local disk path for the working tree,
1200
# this obviously requires a format that supports branch references
1201
# so check for that by checking bzrdir.BzrDirFormat.get_default_format()
1203
b = self.make_branch(relpath, format=format)
1205
return b.bzrdir.create_workingtree()
1206
except errors.NotLocalUrl:
1207
# new formats - catch No tree error and create
1208
# a branch reference and a checkout.
1209
# old formats at that point - raise TestSkipped.
1210
# TODO: rbc 20060208
1211
return WorkingTreeFormat2().initialize(bzrdir.BzrDir.open(relpath))
1213
def assertIsDirectory(self, relpath, transport):
1214
"""Assert that relpath within transport is a directory.
1216
This may not be possible on all transports; in that case it propagates
1217
a TransportNotPossible.
1220
mode = transport.stat(relpath).st_mode
1221
except errors.NoSuchFile:
1222
self.fail("path %s is not a directory; no such file"
1224
if not stat.S_ISDIR(mode):
1225
self.fail("path %s is not a directory; has mode %#o"
1229
class ChrootedTestCase(TestCaseWithTransport):
1230
"""A support class that provides readonly urls outside the local namespace.
1232
This is done by checking if self.transport_server is a MemoryServer. if it
1233
is then we are chrooted already, if it is not then an HttpServer is used
1236
TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
1237
be used without needed to redo it when a different
1238
subclass is in use ?
1242
super(ChrootedTestCase, self).setUp()
1243
if not self.transport_server == bzrlib.transport.memory.MemoryServer:
1244
self.transport_readonly_server = bzrlib.transport.http.HttpServer
1247
def filter_suite_by_re(suite, pattern):
1248
result = TestUtil.TestSuite()
1249
filter_re = re.compile(pattern)
1250
for test in iter_suite_tests(suite):
1251
if filter_re.search(test.id()):
1252
result.addTest(test)
1256
def run_suite(suite, name='test', verbose=False, pattern=".*",
1257
stop_on_failure=False, keep_output=False,
1258
transport=None, lsprof_timed=None, bench_history=None):
387
print >>f, "contents of", name
391
class MetaTestLog(TestCase):
392
def test_logging(self):
393
"""Test logs are captured when a test fails."""
394
logging.info('an info message')
395
warning('something looks dodgy...')
396
logging.debug('hello, test is running')
401
def run_suite(suite, name='test', verbose=False, pattern=".*"):
1259
402
TestCaseInTempDir._TEST_NAME = name
1260
TestCase._gather_lsprof_in_benchmarks = lsprof_timed
1266
pb = progress.ProgressBar()
1267
407
runner = TextTestRunner(stream=sys.stdout,
1269
verbosity=verbosity,
1270
keep_output=keep_output,
1272
bench_history=bench_history)
1273
runner.stop_on_failure=stop_on_failure
1275
suite = filter_suite_by_re(suite, pattern)
1276
result = runner.run(suite)
410
visitor = filteringVisitor(pattern)
412
result = runner.run(visitor.suite())
413
# This is still a little bogus,
414
# but only a little. Folk not using our testrunner will
415
# have to delete their temp directories themselves.
416
if result.wasSuccessful():
417
if TestCaseInTempDir.TEST_ROOT is not None:
418
shutil.rmtree(TestCaseInTempDir.TEST_ROOT)
420
print "Failed tests working directories are in '%s'\n" % TestCaseInTempDir.TEST_ROOT
1277
421
return result.wasSuccessful()
1280
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
1283
test_suite_factory=None,
1285
bench_history=None):
424
def selftest(verbose=False, pattern=".*"):
1286
425
"""Run the whole test suite under the enhanced runner"""
1287
# XXX: Very ugly way to do this...
1288
# Disable warning about old formats because we don't want it to disturb
1289
# any blackbox tests.
1290
from bzrlib import repository
1291
repository._deprecation_warning_done = True
1293
global default_transport
1294
if transport is None:
1295
transport = default_transport
1296
old_transport = default_transport
1297
default_transport = transport
1299
if test_suite_factory is None:
1300
suite = test_suite()
1302
suite = test_suite_factory()
1303
return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
1304
stop_on_failure=stop_on_failure, keep_output=keep_output,
1305
transport=transport,
1306
lsprof_timed=lsprof_timed,
1307
bench_history=bench_history)
1309
default_transport = old_transport
426
return run_suite(test_suite(), 'testbzr', verbose=verbose, pattern=pattern)
1312
429
def test_suite():
1313
"""Build and return TestSuite for the whole of bzrlib.
1315
This function can be replaced if you need to change the default test
1316
suite on a global basis, but it is not encouraged.
1319
'bzrlib.tests.test_ancestry',
1320
'bzrlib.tests.test_api',
1321
'bzrlib.tests.test_atomicfile',
1322
'bzrlib.tests.test_bad_files',
1323
'bzrlib.tests.test_branch',
1324
'bzrlib.tests.test_bundle',
1325
'bzrlib.tests.test_bzrdir',
1326
'bzrlib.tests.test_cache_utf8',
1327
'bzrlib.tests.test_command',
1328
'bzrlib.tests.test_commit',
1329
'bzrlib.tests.test_commit_merge',
1330
'bzrlib.tests.test_config',
1331
'bzrlib.tests.test_conflicts',
1332
'bzrlib.tests.test_decorators',
1333
'bzrlib.tests.test_diff',
1334
'bzrlib.tests.test_doc_generate',
1335
'bzrlib.tests.test_errors',
1336
'bzrlib.tests.test_escaped_store',
1337
'bzrlib.tests.test_fetch',
1338
'bzrlib.tests.test_gpg',
1339
'bzrlib.tests.test_graph',
1340
'bzrlib.tests.test_hashcache',
1341
'bzrlib.tests.test_http',
1342
'bzrlib.tests.test_http_response',
1343
'bzrlib.tests.test_identitymap',
1344
'bzrlib.tests.test_ignores',
1345
'bzrlib.tests.test_inv',
1346
'bzrlib.tests.test_knit',
1347
'bzrlib.tests.test_lockdir',
1348
'bzrlib.tests.test_lockable_files',
1349
'bzrlib.tests.test_log',
1350
'bzrlib.tests.test_merge',
1351
'bzrlib.tests.test_merge3',
1352
'bzrlib.tests.test_merge_core',
1353
'bzrlib.tests.test_missing',
1354
'bzrlib.tests.test_msgeditor',
1355
'bzrlib.tests.test_nonascii',
1356
'bzrlib.tests.test_options',
1357
'bzrlib.tests.test_osutils',
1358
'bzrlib.tests.test_patch',
1359
'bzrlib.tests.test_patches',
1360
'bzrlib.tests.test_permissions',
1361
'bzrlib.tests.test_plugins',
1362
'bzrlib.tests.test_progress',
1363
'bzrlib.tests.test_reconcile',
1364
'bzrlib.tests.test_repository',
1365
'bzrlib.tests.test_revision',
1366
'bzrlib.tests.test_revisionnamespaces',
1367
'bzrlib.tests.test_revisiontree',
1368
'bzrlib.tests.test_rio',
1369
'bzrlib.tests.test_sampler',
1370
'bzrlib.tests.test_selftest',
1371
'bzrlib.tests.test_setup',
1372
'bzrlib.tests.test_sftp_transport',
1373
'bzrlib.tests.test_smart_add',
1374
'bzrlib.tests.test_source',
1375
'bzrlib.tests.test_status',
1376
'bzrlib.tests.test_store',
1377
'bzrlib.tests.test_symbol_versioning',
1378
'bzrlib.tests.test_testament',
1379
'bzrlib.tests.test_textfile',
1380
'bzrlib.tests.test_textmerge',
1381
'bzrlib.tests.test_trace',
1382
'bzrlib.tests.test_transactions',
1383
'bzrlib.tests.test_transform',
1384
'bzrlib.tests.test_transport',
1385
'bzrlib.tests.test_tree',
1386
'bzrlib.tests.test_tsort',
1387
'bzrlib.tests.test_tuned_gzip',
1388
'bzrlib.tests.test_ui',
1389
'bzrlib.tests.test_upgrade',
1390
'bzrlib.tests.test_urlutils',
1391
'bzrlib.tests.test_versionedfile',
1392
'bzrlib.tests.test_version',
1393
'bzrlib.tests.test_weave',
1394
'bzrlib.tests.test_whitebox',
1395
'bzrlib.tests.test_workingtree',
1396
'bzrlib.tests.test_xml',
430
"""Build and return TestSuite for the whole program."""
431
import bzrlib.store, bzrlib.inventory, bzrlib.branch
432
import bzrlib.osutils, bzrlib.merge3, bzrlib.plugin
433
from doctest import DocTestSuite
435
global MODULES_TO_TEST, MODULES_TO_DOCTEST
438
['bzrlib.selftest.MetaTestLog',
439
'bzrlib.selftest.testinv',
440
'bzrlib.selftest.test_ancestry',
441
'bzrlib.selftest.test_commit',
442
'bzrlib.selftest.test_commit_merge',
443
'bzrlib.selftest.versioning',
444
'bzrlib.selftest.testmerge3',
445
'bzrlib.selftest.testmerge',
446
'bzrlib.selftest.testhashcache',
447
'bzrlib.selftest.teststatus',
448
'bzrlib.selftest.testlog',
449
'bzrlib.selftest.testrevisionnamespaces',
450
'bzrlib.selftest.testbranch',
451
'bzrlib.selftest.testrevision',
452
'bzrlib.selftest.test_revision_info',
453
'bzrlib.selftest.test_merge_core',
454
'bzrlib.selftest.test_smart_add',
455
'bzrlib.selftest.test_bad_files',
456
'bzrlib.selftest.testdiff',
457
'bzrlib.selftest.test_parent',
458
'bzrlib.selftest.test_xml',
459
'bzrlib.selftest.test_weave',
460
'bzrlib.selftest.testfetch',
461
'bzrlib.selftest.whitebox',
462
'bzrlib.selftest.teststore',
463
'bzrlib.selftest.blackbox',
464
'bzrlib.selftest.testtransport',
465
'bzrlib.selftest.testgraph',
1398
test_transport_implementations = [
1399
'bzrlib.tests.test_transport_implementations',
1400
'bzrlib.tests.test_read_bundle',
1402
suite = TestUtil.TestSuite()
1403
loader = TestUtil.TestLoader()
1404
suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
1405
from bzrlib.transport import TransportTestProviderAdapter
1406
adapter = TransportTestProviderAdapter()
1407
adapt_modules(test_transport_implementations, adapter, loader, suite)
1408
for package in packages_to_test():
1409
suite.addTest(package.test_suite())
468
for m in (bzrlib.store, bzrlib.inventory, bzrlib.branch,
469
bzrlib.osutils, bzrlib.commands, bzrlib.merge3):
470
if m not in MODULES_TO_DOCTEST:
471
MODULES_TO_DOCTEST.append(m)
473
TestCase.BZRPATH = os.path.join(os.path.realpath(os.path.dirname(bzrlib.__path__[0])), 'bzr')
474
print '%-30s %s' % ('bzr binary', TestCase.BZRPATH)
477
suite.addTest(TestLoader().loadTestsFromNames(testmod_names))
1410
478
for m in MODULES_TO_TEST:
1411
suite.addTest(loader.loadTestsFromModule(m))
1412
for m in MODULES_TO_DOCTEST:
1413
suite.addTest(doctest.DocTestSuite(m))
1414
for name, plugin in bzrlib.plugin.all_plugins().items():
1415
if getattr(plugin, 'test_suite', None) is not None:
1416
suite.addTest(plugin.test_suite())
479
suite.addTest(TestLoader().loadTestsFromModule(m))
480
for m in (MODULES_TO_DOCTEST):
481
suite.addTest(DocTestSuite(m))
482
for p in bzrlib.plugin.all_plugins:
483
if hasattr(p, 'test_suite'):
484
suite.addTest(p.test_suite())
1420
def adapt_modules(mods_list, adapter, loader, suite):
1421
"""Adapt the modules in mods_list using adapter and add to suite."""
1422
for test in iter_suite_tests(loader.loadTestsFromModuleNames(mods_list)):
1423
suite.addTests(adapter.adapt(test))