1
# Copyright (C) 2005 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
from cStringIO import StringIO
32
import bzrlib.commands
33
from bzrlib.errors import BzrError
34
import bzrlib.inventory
40
from bzrlib.trace import mutter
41
from bzrlib.tests.TestUtil import TestLoader, TestSuite
42
from bzrlib.tests.treeshape import build_tree_contents
45
MODULES_TO_DOCTEST = [
54
def packages_to_test():
55
"""Return a list of packages to test.
57
The packages are not globally imported so that import failures are
58
triggered when running selftest, not when importing the command.
61
import bzrlib.tests.blackbox
68
class EarlyStoppingTestResultAdapter(object):
69
"""An adapter for TestResult to stop at the first first failure or error"""
71
def __init__(self, result):
74
def addError(self, test, err):
75
self._result.addError(test, err)
78
def addFailure(self, test, err):
79
self._result.addFailure(test, err)
82
def __getattr__(self, name):
83
return getattr(self._result, name)
85
def __setattr__(self, name, value):
87
object.__setattr__(self, name, value)
88
return setattr(self._result, name, value)
91
class _MyResult(unittest._TextTestResult):
94
Shows output in a different format, including displaying runtime for tests.
97
def _elapsedTime(self):
98
return "%5dms" % (1000 * (time.time() - self._start_time))
100
def startTest(self, test):
101
unittest.TestResult.startTest(self, test)
102
# In a short description, the important words are in
103
# the beginning, but in an id, the important words are
105
SHOW_DESCRIPTIONS = False
107
width = bzrlib.osutils.terminal_width()
108
name_width = width - 15
110
if SHOW_DESCRIPTIONS:
111
what = test.shortDescription()
113
if len(what) > name_width:
114
what = what[:name_width-3] + '...'
117
if what.startswith('bzrlib.tests.'):
119
if len(what) > name_width:
120
what = '...' + what[3-name_width:]
121
what = what.ljust(name_width)
122
self.stream.write(what)
124
self._start_time = time.time()
126
def addError(self, test, err):
127
if isinstance(err[1], TestSkipped):
128
return self.addSkipped(test, err)
129
unittest.TestResult.addError(self, test, err)
131
self.stream.writeln("ERROR %s" % self._elapsedTime())
133
self.stream.write('E')
136
def addFailure(self, test, err):
137
unittest.TestResult.addFailure(self, test, err)
139
self.stream.writeln(" FAIL %s" % self._elapsedTime())
141
self.stream.write('F')
144
def addSuccess(self, test):
146
self.stream.writeln(' OK %s' % self._elapsedTime())
148
self.stream.write('~')
150
unittest.TestResult.addSuccess(self, test)
152
def addSkipped(self, test, skip_excinfo):
154
print >>self.stream, ' SKIP %s' % self._elapsedTime()
155
print >>self.stream, ' %s' % skip_excinfo[1]
157
self.stream.write('S')
159
# seems best to treat this as success from point-of-view of unittest
160
# -- it actually does nothing so it barely matters :)
161
unittest.TestResult.addSuccess(self, test)
163
def printErrorList(self, flavour, errors):
164
for test, err in errors:
165
self.stream.writeln(self.separator1)
166
self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
167
if hasattr(test, '_get_log'):
169
print >>self.stream, \
170
('vvvv[log from %s]' % test).ljust(78,'-')
171
print >>self.stream, test._get_log()
172
print >>self.stream, \
173
('^^^^[log from %s]' % test).ljust(78,'-')
174
self.stream.writeln(self.separator2)
175
self.stream.writeln("%s" % err)
178
class TextTestRunner(unittest.TextTestRunner):
179
stop_on_failure = False
181
def _makeResult(self):
182
result = _MyResult(self.stream, self.descriptions, self.verbosity)
183
if self.stop_on_failure:
184
result = EarlyStoppingTestResultAdapter(result)
188
def iter_suite_tests(suite):
189
"""Return all tests in a suite, recursing through nested suites"""
190
for item in suite._tests:
191
if isinstance(item, unittest.TestCase):
193
elif isinstance(item, unittest.TestSuite):
194
for r in iter_suite_tests(item):
197
raise Exception('unknown object %r inside test suite %r'
201
class TestSkipped(Exception):
202
"""Indicates that a test was intentionally skipped, rather than failing."""
206
class CommandFailed(Exception):
209
class TestCase(unittest.TestCase):
210
"""Base class for bzr unit tests.
212
Tests that need access to disk resources should subclass
213
TestCaseInTempDir not TestCase.
215
Error and debug log messages are redirected from their usual
216
location into a temporary file, the contents of which can be
217
retrieved by _get_log(). We use a real OS file, not an in-memory object,
218
so that it can also capture file IO. When the test completes this file
219
is read into memory and removed from disk.
221
There are also convenience functions to invoke bzr's command-line
222
routine, and to build and check bzr trees.
224
In addition to the usual method of overriding tearDown(), this class also
225
allows subclasses to register functions into the _cleanups list, which is
226
run in order as the object is torn down. It's less likely this will be
227
accidentally overlooked.
231
_log_file_name = None
235
unittest.TestCase.setUp(self)
237
self._cleanEnvironment()
238
bzrlib.trace.disable_default_logging()
241
def _ndiff_strings(self, a, b):
242
"""Return ndiff between two strings containing lines.
244
A trailing newline is added if missing to make the strings
246
if b and b[-1] != '\n':
248
if a and a[-1] != '\n':
250
difflines = difflib.ndiff(a.splitlines(True),
252
linejunk=lambda x: False,
253
charjunk=lambda x: False)
254
return ''.join(difflines)
256
def assertEqualDiff(self, a, b):
257
"""Assert two texts are equal, if not raise an exception.
259
This is intended for use with multi-line strings where it can
260
be hard to find the differences by eye.
262
# TODO: perhaps override assertEquals to call this for strings?
265
raise AssertionError("texts not equal:\n" +
266
self._ndiff_strings(a, b))
268
def assertContainsRe(self, haystack, needle_re):
269
"""Assert that a contains something matching a regular expression."""
270
if not re.search(needle_re, haystack):
271
raise AssertionError('pattern "%s" not found in "%s"'
272
% (needle_re, haystack))
274
def AssertSubset(self, sublist, superlist):
275
"""Assert that every entry in sublist is present in superlist."""
277
for entry in sublist:
278
if entry not in superlist:
279
missing.append(entry)
281
raise AssertionError("value(s) %r not present in container %r" %
282
(missing, superlist))
284
def _startLogFile(self):
285
"""Send bzr and test log messages to a temporary file.
287
The file is removed as the test is torn down.
289
fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
290
encoder, decoder, stream_reader, stream_writer = codecs.lookup('UTF-8')
291
self._log_file = stream_writer(os.fdopen(fileno, 'w+'))
292
bzrlib.trace.enable_test_log(self._log_file)
293
self._log_file_name = name
294
self.addCleanup(self._finishLogFile)
296
def _finishLogFile(self):
297
"""Finished with the log file.
299
Read contents into memory, close, and delete.
301
bzrlib.trace.disable_test_log()
302
self._log_file.seek(0)
303
self._log_contents = self._log_file.read()
304
self._log_file.close()
305
os.remove(self._log_file_name)
306
self._log_file = self._log_file_name = None
308
def addCleanup(self, callable):
309
"""Arrange to run a callable when this case is torn down.
311
Callables are run in the reverse of the order they are registered,
312
ie last-in first-out.
314
if callable in self._cleanups:
315
raise ValueError("cleanup function %r already registered on %s"
317
self._cleanups.append(callable)
319
def _cleanEnvironment(self):
322
'APPDATA': os.getcwd(),
327
self.addCleanup(self._restoreEnvironment)
328
for name, value in new_env.iteritems():
329
self._captureVar(name, value)
332
def _captureVar(self, name, newvalue):
333
"""Set an environment variable, preparing it to be reset when finished."""
334
self.__old_env[name] = os.environ.get(name, None)
336
if name in os.environ:
339
os.environ[name] = newvalue
342
def _restoreVar(name, value):
344
if name in os.environ:
347
os.environ[name] = value
349
def _restoreEnvironment(self):
350
for name, value in self.__old_env.iteritems():
351
self._restoreVar(name, value)
355
unittest.TestCase.tearDown(self)
357
def _runCleanups(self):
358
"""Run registered cleanup functions.
360
This should only be called from TestCase.tearDown.
362
for cleanup_fn in reversed(self._cleanups):
365
def log(self, *args):
369
"""Return as a string the log for this test"""
370
if self._log_file_name:
371
return open(self._log_file_name).read()
373
return self._log_contents
374
# TODO: Delete the log after it's been read in
376
def capture(self, cmd, retcode=0):
377
"""Shortcut that splits cmd into words, runs, and returns stdout"""
378
return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
380
def run_bzr_captured(self, argv, retcode=0):
381
"""Invoke bzr and return (stdout, stderr).
383
Useful for code that wants to check the contents of the
384
output, the way error messages are presented, etc.
386
This should be the main method for tests that want to exercise the
387
overall behavior of the bzr application (rather than a unit test
388
or a functional test of the library.)
390
Much of the old code runs bzr by forking a new copy of Python, but
391
that is slower, harder to debug, and generally not necessary.
393
This runs bzr through the interface that catches and reports
394
errors, and with logging set to something approximating the
395
default, so that error reporting can be checked.
397
argv -- arguments to invoke bzr
398
retcode -- expected return code, or None for don't-care.
402
self.log('run bzr: %s', ' '.join(argv))
403
# FIXME: don't call into logging here
404
handler = logging.StreamHandler(stderr)
405
handler.setFormatter(bzrlib.trace.QuietFormatter())
406
handler.setLevel(logging.INFO)
407
logger = logging.getLogger('')
408
logger.addHandler(handler)
410
result = self.apply_redirected(None, stdout, stderr,
411
bzrlib.commands.run_bzr_catch_errors,
414
logger.removeHandler(handler)
415
out = stdout.getvalue()
416
err = stderr.getvalue()
418
self.log('output:\n%s', out)
420
self.log('errors:\n%s', err)
421
if retcode is not None:
422
self.assertEquals(result, retcode)
425
def run_bzr(self, *args, **kwargs):
426
"""Invoke bzr, as if it were run from the command line.
428
This should be the main method for tests that want to exercise the
429
overall behavior of the bzr application (rather than a unit test
430
or a functional test of the library.)
432
This sends the stdout/stderr results into the test's log,
433
where it may be useful for debugging. See also run_captured.
435
retcode = kwargs.pop('retcode', 0)
436
return self.run_bzr_captured(args, retcode)
438
def check_inventory_shape(self, inv, shape):
439
"""Compare an inventory to a list of expected names.
441
Fail if they are not precisely equal.
444
shape = list(shape) # copy
445
for path, ie in inv.entries():
446
name = path.replace('\\', '/')
454
self.fail("expected paths not found in inventory: %r" % shape)
456
self.fail("unexpected paths found in inventory: %r" % extras)
458
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
459
a_callable=None, *args, **kwargs):
460
"""Call callable with redirected std io pipes.
462
Returns the return code."""
463
if not callable(a_callable):
464
raise ValueError("a_callable must be callable.")
468
if hasattr(self, "_log_file"):
469
stdout = self._log_file
473
if hasattr(self, "_log_file"):
474
stderr = self._log_file
477
real_stdin = sys.stdin
478
real_stdout = sys.stdout
479
real_stderr = sys.stderr
484
return a_callable(*args, **kwargs)
486
sys.stdout = real_stdout
487
sys.stderr = real_stderr
488
sys.stdin = real_stdin
491
BzrTestBase = TestCase
494
class TestCaseInTempDir(TestCase):
495
"""Derived class that runs a test within a temporary directory.
497
This is useful for tests that need to create a branch, etc.
499
The directory is created in a slightly complex way: for each
500
Python invocation, a new temporary top-level directory is created.
501
All test cases create their own directory within that. If the
502
tests complete successfully, the directory is removed.
504
InTempDir is an old alias for FunctionalTestCase.
509
OVERRIDE_PYTHON = 'python'
511
def check_file_contents(self, filename, expect):
512
self.log("check contents of file %s" % filename)
513
contents = file(filename, 'r').read()
514
if contents != expect:
515
self.log("expected: %r" % expect)
516
self.log("actually: %r" % contents)
517
self.fail("contents of %s not as expected" % filename)
519
def _make_test_root(self):
520
if TestCaseInTempDir.TEST_ROOT is not None:
524
root = u'test%04d.tmp' % i
528
if e.errno == errno.EEXIST:
533
# successfully created
534
TestCaseInTempDir.TEST_ROOT = os.path.abspath(root)
536
# make a fake bzr directory there to prevent any tests propagating
537
# up onto the source directory's real branch
538
os.mkdir(os.path.join(TestCaseInTempDir.TEST_ROOT, '.bzr'))
541
super(TestCaseInTempDir, self).setUp()
542
self._make_test_root()
543
_currentdir = os.getcwdu()
544
short_id = self.id().replace('bzrlib.tests.', '') \
545
.replace('__main__.', '')
546
self.test_dir = os.path.join(self.TEST_ROOT, short_id)
547
os.mkdir(self.test_dir)
548
os.chdir(self.test_dir)
549
os.environ['HOME'] = self.test_dir
550
def _leaveDirectory():
551
os.chdir(_currentdir)
552
self.addCleanup(_leaveDirectory)
554
def build_tree(self, shape, line_endings='native'):
555
"""Build a test tree according to a pattern.
557
shape is a sequence of file specifications. If the final
558
character is '/', a directory is created.
560
This doesn't add anything to a branch.
561
:param line_endings: Either 'binary' or 'native'
562
in binary mode, exact contents are written
563
in native mode, the line endings match the
564
default platform endings.
566
# XXX: It's OK to just create them using forward slashes on windows?
568
self.assert_(isinstance(name, basestring))
572
if line_endings == 'binary':
574
elif line_endings == 'native':
577
raise BzrError('Invalid line ending request %r' % (line_endings,))
578
print >>f, "contents of", name
581
def build_tree_contents(self, shape):
582
build_tree_contents(shape)
584
def failUnlessExists(self, path):
585
"""Fail unless path, which may be abs or relative, exists."""
586
self.failUnless(bzrlib.osutils.lexists(path))
588
def assertFileEqual(self, content, path):
589
"""Fail if path does not contain 'content'."""
590
self.failUnless(bzrlib.osutils.lexists(path))
591
self.assertEqualDiff(content, open(path, 'r').read())
594
def filter_suite_by_re(suite, pattern):
596
filter_re = re.compile(pattern)
597
for test in iter_suite_tests(suite):
598
if filter_re.search(test.id()):
603
def run_suite(suite, name='test', verbose=False, pattern=".*",
604
stop_on_failure=False, keep_output=False):
605
TestCaseInTempDir._TEST_NAME = name
610
runner = TextTestRunner(stream=sys.stdout,
613
runner.stop_on_failure=stop_on_failure
615
suite = filter_suite_by_re(suite, pattern)
616
result = runner.run(suite)
617
# This is still a little bogus,
618
# but only a little. Folk not using our testrunner will
619
# have to delete their temp directories themselves.
620
if result.wasSuccessful() or not keep_output:
621
if TestCaseInTempDir.TEST_ROOT is not None:
622
shutil.rmtree(TestCaseInTempDir.TEST_ROOT)
624
print "Failed tests working directories are in '%s'\n" % TestCaseInTempDir.TEST_ROOT
625
return result.wasSuccessful()
628
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
630
"""Run the whole test suite under the enhanced runner"""
631
return run_suite(test_suite(), 'testbzr', verbose=verbose, pattern=pattern,
632
stop_on_failure=stop_on_failure, keep_output=keep_output)
636
"""Build and return TestSuite for the whole program."""
637
from doctest import DocTestSuite
639
global MODULES_TO_DOCTEST
642
'bzrlib.tests.test_ancestry',
643
'bzrlib.tests.test_annotate',
644
'bzrlib.tests.test_api',
645
'bzrlib.tests.test_bad_files',
646
'bzrlib.tests.test_branch',
647
'bzrlib.tests.test_command',
648
'bzrlib.tests.test_commit',
649
'bzrlib.tests.test_commit_merge',
650
'bzrlib.tests.test_config',
651
'bzrlib.tests.test_conflicts',
652
'bzrlib.tests.test_diff',
653
'bzrlib.tests.test_fetch',
654
'bzrlib.tests.test_gpg',
655
'bzrlib.tests.test_graph',
656
'bzrlib.tests.test_hashcache',
657
'bzrlib.tests.test_http',
658
'bzrlib.tests.test_identitymap',
659
'bzrlib.tests.test_inv',
660
'bzrlib.tests.test_log',
661
'bzrlib.tests.test_merge',
662
'bzrlib.tests.test_merge3',
663
'bzrlib.tests.test_merge_core',
664
'bzrlib.tests.test_missing',
665
'bzrlib.tests.test_msgeditor',
666
'bzrlib.tests.test_nonascii',
667
'bzrlib.tests.test_options',
668
'bzrlib.tests.test_parent',
669
'bzrlib.tests.test_plugins',
670
'bzrlib.tests.test_remove',
671
'bzrlib.tests.test_revision',
672
'bzrlib.tests.test_revision_info',
673
'bzrlib.tests.test_revisionnamespaces',
674
'bzrlib.tests.test_revprops',
675
'bzrlib.tests.test_reweave',
676
'bzrlib.tests.test_rio',
677
'bzrlib.tests.test_sampler',
678
'bzrlib.tests.test_selftest',
679
'bzrlib.tests.test_setup',
680
'bzrlib.tests.test_sftp',
681
'bzrlib.tests.test_smart_add',
682
'bzrlib.tests.test_source',
683
'bzrlib.tests.test_status',
684
'bzrlib.tests.test_store',
685
'bzrlib.tests.test_testament',
686
'bzrlib.tests.test_trace',
687
'bzrlib.tests.test_transactions',
688
'bzrlib.tests.test_transport',
689
'bzrlib.tests.test_tsort',
690
'bzrlib.tests.test_ui',
691
'bzrlib.tests.test_uncommit',
692
'bzrlib.tests.test_upgrade',
693
'bzrlib.tests.test_weave',
694
'bzrlib.tests.test_whitebox',
695
'bzrlib.tests.test_workingtree',
696
'bzrlib.tests.test_xml',
699
print '%10s: %s' % ('bzr', os.path.realpath(sys.argv[0]))
700
print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
703
# python2.4's TestLoader.loadTestsFromNames gives very poor
704
# errors if it fails to load a named module - no indication of what's
705
# actually wrong, just "no such module". We should probably override that
706
# class, but for the moment just load them ourselves. (mbp 20051202)
707
loader = TestLoader()
708
for mod_name in testmod_names:
709
mod = _load_module_by_name(mod_name)
710
suite.addTest(loader.loadTestsFromModule(mod))
711
for package in packages_to_test():
712
suite.addTest(package.test_suite())
713
for m in MODULES_TO_TEST:
714
suite.addTest(loader.loadTestsFromModule(m))
715
for m in (MODULES_TO_DOCTEST):
716
suite.addTest(DocTestSuite(m))
717
for name, plugin in bzrlib.plugin.all_plugins().items():
718
if hasattr(plugin, 'test_suite'):
719
suite.addTest(plugin.test_suite())
723
def _load_module_by_name(mod_name):
724
parts = mod_name.split('.')
725
module = __import__(mod_name)
727
# for historical reasons python returns the top-level module even though
728
# it loads the submodule; we need to walk down to get the one we want.
730
module = getattr(module, parts.pop(0))