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
45
import bzrlib.bzrdir as bzrdir
46
import bzrlib.commands
47
import bzrlib.errors as errors
48
import bzrlib.inventory
49
import bzrlib.iterablefile
53
import bzrlib.osutils as osutils
57
from bzrlib.transport import urlescape, get_transport
58
import bzrlib.transport
59
from bzrlib.transport.local import LocalRelpathServer
60
from bzrlib.transport.readonly import ReadonlyServer
61
from bzrlib.trace import mutter
62
from bzrlib.tests.TestUtil import TestLoader, TestSuite
63
from bzrlib.tests.treeshape import build_tree_contents
64
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
66
default_transport = LocalRelpathServer
69
MODULES_TO_DOCTEST = [
81
def packages_to_test():
82
"""Return a list of packages to test.
84
The packages are not globally imported so that import failures are
85
triggered when running selftest, not when importing the command.
88
import bzrlib.tests.blackbox
89
import bzrlib.tests.branch_implementations
90
import bzrlib.tests.bzrdir_implementations
91
import bzrlib.tests.interrepository_implementations
92
import bzrlib.tests.repository_implementations
93
import bzrlib.tests.workingtree_implementations
96
bzrlib.tests.blackbox,
97
bzrlib.tests.branch_implementations,
98
bzrlib.tests.bzrdir_implementations,
99
bzrlib.tests.interrepository_implementations,
100
bzrlib.tests.repository_implementations,
101
bzrlib.tests.workingtree_implementations,
105
class _MyResult(unittest._TextTestResult):
106
"""Custom TestResult.
108
Shows output in a different format, including displaying runtime for tests.
112
def _elapsedTime(self):
113
return "%5dms" % (1000 * (time.time() - self._start_time))
115
def startTest(self, test):
116
unittest.TestResult.startTest(self, test)
117
# In a short description, the important words are in
118
# the beginning, but in an id, the important words are
120
SHOW_DESCRIPTIONS = False
122
width = osutils.terminal_width()
123
name_width = width - 15
125
if SHOW_DESCRIPTIONS:
126
what = test.shortDescription()
128
if len(what) > name_width:
129
what = what[:name_width-3] + '...'
132
if what.startswith('bzrlib.tests.'):
134
if len(what) > name_width:
135
what = '...' + what[3-name_width:]
136
what = what.ljust(name_width)
137
self.stream.write(what)
139
self._start_time = time.time()
141
def addError(self, test, err):
142
if isinstance(err[1], TestSkipped):
143
return self.addSkipped(test, err)
144
unittest.TestResult.addError(self, test, err)
146
self.stream.writeln("ERROR %s" % self._elapsedTime())
148
self.stream.write('E')
153
def addFailure(self, test, err):
154
unittest.TestResult.addFailure(self, test, err)
156
self.stream.writeln(" FAIL %s" % self._elapsedTime())
158
self.stream.write('F')
163
def addSuccess(self, test):
165
self.stream.writeln(' OK %s' % self._elapsedTime())
167
self.stream.write('~')
169
unittest.TestResult.addSuccess(self, test)
171
def addSkipped(self, test, skip_excinfo):
173
print >>self.stream, ' SKIP %s' % self._elapsedTime()
174
print >>self.stream, ' %s' % skip_excinfo[1]
176
self.stream.write('S')
178
# seems best to treat this as success from point-of-view of unittest
179
# -- it actually does nothing so it barely matters :)
180
unittest.TestResult.addSuccess(self, test)
182
def printErrorList(self, flavour, errors):
183
for test, err in errors:
184
self.stream.writeln(self.separator1)
185
self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
186
if getattr(test, '_get_log', None) is not None:
188
print >>self.stream, \
189
('vvvv[log from %s]' % test.id()).ljust(78,'-')
190
print >>self.stream, test._get_log()
191
print >>self.stream, \
192
('^^^^[log from %s]' % test.id()).ljust(78,'-')
193
self.stream.writeln(self.separator2)
194
self.stream.writeln("%s" % err)
197
class TextTestRunner(unittest.TextTestRunner):
198
stop_on_failure = False
200
def _makeResult(self):
201
result = _MyResult(self.stream, self.descriptions, self.verbosity)
202
result.stop_early = self.stop_on_failure
206
def iter_suite_tests(suite):
207
"""Return all tests in a suite, recursing through nested suites"""
208
for item in suite._tests:
209
if isinstance(item, unittest.TestCase):
211
elif isinstance(item, unittest.TestSuite):
212
for r in iter_suite_tests(item):
215
raise Exception('unknown object %r inside test suite %r'
219
class TestSkipped(Exception):
220
"""Indicates that a test was intentionally skipped, rather than failing."""
224
class CommandFailed(Exception):
227
class TestCase(unittest.TestCase):
228
"""Base class for bzr unit tests.
230
Tests that need access to disk resources should subclass
231
TestCaseInTempDir not TestCase.
233
Error and debug log messages are redirected from their usual
234
location into a temporary file, the contents of which can be
235
retrieved by _get_log(). We use a real OS file, not an in-memory object,
236
so that it can also capture file IO. When the test completes this file
237
is read into memory and removed from disk.
239
There are also convenience functions to invoke bzr's command-line
240
routine, and to build and check bzr trees.
242
In addition to the usual method of overriding tearDown(), this class also
243
allows subclasses to register functions into the _cleanups list, which is
244
run in order as the object is torn down. It's less likely this will be
245
accidentally overlooked.
249
_log_file_name = None
252
def __init__(self, methodName='testMethod'):
253
super(TestCase, self).__init__(methodName)
257
unittest.TestCase.setUp(self)
258
self._cleanEnvironment()
259
bzrlib.trace.disable_default_logging()
262
def _ndiff_strings(self, a, b):
263
"""Return ndiff between two strings containing lines.
265
A trailing newline is added if missing to make the strings
267
if b and b[-1] != '\n':
269
if a and a[-1] != '\n':
271
difflines = difflib.ndiff(a.splitlines(True),
273
linejunk=lambda x: False,
274
charjunk=lambda x: False)
275
return ''.join(difflines)
277
def assertEqualDiff(self, a, b, message=None):
278
"""Assert two texts are equal, if not raise an exception.
280
This is intended for use with multi-line strings where it can
281
be hard to find the differences by eye.
283
# TODO: perhaps override assertEquals to call this for strings?
287
message = "texts not equal:\n"
288
raise AssertionError(message +
289
self._ndiff_strings(a, b))
291
def assertEqualMode(self, mode, mode_test):
292
self.assertEqual(mode, mode_test,
293
'mode mismatch %o != %o' % (mode, mode_test))
295
def assertStartsWith(self, s, prefix):
296
if not s.startswith(prefix):
297
raise AssertionError('string %r does not start with %r' % (s, prefix))
299
def assertEndsWith(self, s, suffix):
300
if not s.endswith(prefix):
301
raise AssertionError('string %r does not end with %r' % (s, suffix))
303
def assertContainsRe(self, haystack, needle_re):
304
"""Assert that a contains something matching a regular expression."""
305
if not re.search(needle_re, haystack):
306
raise AssertionError('pattern "%s" not found in "%s"'
307
% (needle_re, haystack))
309
def assertSubset(self, sublist, superlist):
310
"""Assert that every entry in sublist is present in superlist."""
312
for entry in sublist:
313
if entry not in superlist:
314
missing.append(entry)
316
raise AssertionError("value(s) %r not present in container %r" %
317
(missing, superlist))
319
def assertIs(self, left, right):
320
if not (left is right):
321
raise AssertionError("%r is not %r." % (left, right))
323
def assertTransportMode(self, transport, path, mode):
324
"""Fail if a path does not have mode mode.
326
If modes are not supported on this platform, the test is skipped.
328
if sys.platform == 'win32':
330
path_stat = transport.stat(path)
331
actual_mode = stat.S_IMODE(path_stat.st_mode)
332
self.assertEqual(mode, actual_mode,
333
'mode of %r incorrect (%o != %o)' % (path, mode, actual_mode))
335
def _startLogFile(self):
336
"""Send bzr and test log messages to a temporary file.
338
The file is removed as the test is torn down.
340
fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
341
encoder, decoder, stream_reader, stream_writer = codecs.lookup('UTF-8')
342
self._log_file = stream_writer(os.fdopen(fileno, 'w+'))
343
self._log_nonce = bzrlib.trace.enable_test_log(self._log_file)
344
self._log_file_name = name
345
self.addCleanup(self._finishLogFile)
347
def _finishLogFile(self):
348
"""Finished with the log file.
350
Read contents into memory, close, and delete.
352
bzrlib.trace.disable_test_log(self._log_nonce)
353
self._log_file.seek(0)
354
self._log_contents = self._log_file.read()
355
self._log_file.close()
356
os.remove(self._log_file_name)
357
self._log_file = self._log_file_name = None
359
def addCleanup(self, callable):
360
"""Arrange to run a callable when this case is torn down.
362
Callables are run in the reverse of the order they are registered,
363
ie last-in first-out.
365
if callable in self._cleanups:
366
raise ValueError("cleanup function %r already registered on %s"
368
self._cleanups.append(callable)
370
def _cleanEnvironment(self):
373
'APPDATA': os.getcwd(),
378
self.addCleanup(self._restoreEnvironment)
379
for name, value in new_env.iteritems():
380
self._captureVar(name, value)
383
def _captureVar(self, name, newvalue):
384
"""Set an environment variable, preparing it to be reset when finished."""
385
self.__old_env[name] = os.environ.get(name, None)
387
if name in os.environ:
390
os.environ[name] = newvalue
393
def _restoreVar(name, value):
395
if name in os.environ:
398
os.environ[name] = value
400
def _restoreEnvironment(self):
401
for name, value in self.__old_env.iteritems():
402
self._restoreVar(name, value)
406
unittest.TestCase.tearDown(self)
408
def _runCleanups(self):
409
"""Run registered cleanup functions.
411
This should only be called from TestCase.tearDown.
413
# TODO: Perhaps this should keep running cleanups even if
415
for cleanup_fn in reversed(self._cleanups):
418
def log(self, *args):
422
"""Return as a string the log for this test"""
423
if self._log_file_name:
424
return open(self._log_file_name).read()
426
return self._log_contents
427
# TODO: Delete the log after it's been read in
429
def capture(self, cmd, retcode=0):
430
"""Shortcut that splits cmd into words, runs, and returns stdout"""
431
return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
433
def run_bzr_captured(self, argv, retcode=0):
434
"""Invoke bzr and return (stdout, stderr).
436
Useful for code that wants to check the contents of the
437
output, the way error messages are presented, etc.
439
This should be the main method for tests that want to exercise the
440
overall behavior of the bzr application (rather than a unit test
441
or a functional test of the library.)
443
Much of the old code runs bzr by forking a new copy of Python, but
444
that is slower, harder to debug, and generally not necessary.
446
This runs bzr through the interface that catches and reports
447
errors, and with logging set to something approximating the
448
default, so that error reporting can be checked.
450
argv -- arguments to invoke bzr
451
retcode -- expected return code, or None for don't-care.
455
self.log('run bzr: %s', ' '.join(argv))
456
# FIXME: don't call into logging here
457
handler = logging.StreamHandler(stderr)
458
handler.setFormatter(bzrlib.trace.QuietFormatter())
459
handler.setLevel(logging.INFO)
460
logger = logging.getLogger('')
461
logger.addHandler(handler)
463
result = self.apply_redirected(None, stdout, stderr,
464
bzrlib.commands.run_bzr_catch_errors,
467
logger.removeHandler(handler)
468
out = stdout.getvalue()
469
err = stderr.getvalue()
471
self.log('output:\n%s', out)
473
self.log('errors:\n%s', err)
474
if retcode is not None:
475
self.assertEquals(result, retcode)
478
def run_bzr(self, *args, **kwargs):
479
"""Invoke bzr, as if it were run from the command line.
481
This should be the main method for tests that want to exercise the
482
overall behavior of the bzr application (rather than a unit test
483
or a functional test of the library.)
485
This sends the stdout/stderr results into the test's log,
486
where it may be useful for debugging. See also run_captured.
488
retcode = kwargs.pop('retcode', 0)
489
return self.run_bzr_captured(args, retcode)
491
def check_inventory_shape(self, inv, shape):
492
"""Compare an inventory to a list of expected names.
494
Fail if they are not precisely equal.
497
shape = list(shape) # copy
498
for path, ie in inv.entries():
499
name = path.replace('\\', '/')
507
self.fail("expected paths not found in inventory: %r" % shape)
509
self.fail("unexpected paths found in inventory: %r" % extras)
511
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
512
a_callable=None, *args, **kwargs):
513
"""Call callable with redirected std io pipes.
515
Returns the return code."""
516
if not callable(a_callable):
517
raise ValueError("a_callable must be callable.")
521
if getattr(self, "_log_file", None) is not None:
522
stdout = self._log_file
526
if getattr(self, "_log_file", None is not None):
527
stderr = self._log_file
530
real_stdin = sys.stdin
531
real_stdout = sys.stdout
532
real_stderr = sys.stderr
537
return a_callable(*args, **kwargs)
539
sys.stdout = real_stdout
540
sys.stderr = real_stderr
541
sys.stdin = real_stdin
544
BzrTestBase = TestCase
547
class TestCaseInTempDir(TestCase):
548
"""Derived class that runs a test within a temporary directory.
550
This is useful for tests that need to create a branch, etc.
552
The directory is created in a slightly complex way: for each
553
Python invocation, a new temporary top-level directory is created.
554
All test cases create their own directory within that. If the
555
tests complete successfully, the directory is removed.
557
InTempDir is an old alias for FunctionalTestCase.
562
OVERRIDE_PYTHON = 'python'
564
def check_file_contents(self, filename, expect):
565
self.log("check contents of file %s" % filename)
566
contents = file(filename, 'r').read()
567
if contents != expect:
568
self.log("expected: %r" % expect)
569
self.log("actually: %r" % contents)
570
self.fail("contents of %s not as expected" % filename)
572
def _make_test_root(self):
573
if TestCaseInTempDir.TEST_ROOT is not None:
577
root = u'test%04d.tmp' % i
581
if e.errno == errno.EEXIST:
586
# successfully created
587
TestCaseInTempDir.TEST_ROOT = osutils.abspath(root)
589
# make a fake bzr directory there to prevent any tests propagating
590
# up onto the source directory's real branch
591
bzrdir.BzrDir.create_standalone_workingtree(TestCaseInTempDir.TEST_ROOT)
594
super(TestCaseInTempDir, self).setUp()
595
self._make_test_root()
596
_currentdir = os.getcwdu()
597
short_id = self.id().replace('bzrlib.tests.', '') \
598
.replace('__main__.', '')
599
self.test_dir = osutils.pathjoin(self.TEST_ROOT, short_id)
600
os.mkdir(self.test_dir)
601
os.chdir(self.test_dir)
602
os.environ['HOME'] = self.test_dir
603
os.environ['APPDATA'] = self.test_dir
604
def _leaveDirectory():
605
os.chdir(_currentdir)
606
self.addCleanup(_leaveDirectory)
608
def build_tree(self, shape, line_endings='native', transport=None):
609
"""Build a test tree according to a pattern.
611
shape is a sequence of file specifications. If the final
612
character is '/', a directory is created.
614
This doesn't add anything to a branch.
615
:param line_endings: Either 'binary' or 'native'
616
in binary mode, exact contents are written
617
in native mode, the line endings match the
618
default platform endings.
620
:param transport: A transport to write to, for building trees on
621
VFS's. If the transport is readonly or None,
622
"." is opened automatically.
624
# XXX: It's OK to just create them using forward slashes on windows?
625
if transport is None or transport.is_readonly():
626
transport = get_transport(".")
628
self.assert_(isinstance(name, basestring))
630
transport.mkdir(urlescape(name[:-1]))
632
if line_endings == 'binary':
634
elif line_endings == 'native':
637
raise errors.BzrError('Invalid line ending request %r' % (line_endings,))
638
content = "contents of %s%s" % (name, end)
639
transport.put(urlescape(name), StringIO(content))
641
def build_tree_contents(self, shape):
642
build_tree_contents(shape)
644
def failUnlessExists(self, path):
645
"""Fail unless path, which may be abs or relative, exists."""
646
self.failUnless(osutils.lexists(path))
648
def failIfExists(self, path):
649
"""Fail if path, which may be abs or relative, exists."""
650
self.failIf(osutils.lexists(path))
652
def assertFileEqual(self, content, path):
653
"""Fail if path does not contain 'content'."""
654
self.failUnless(osutils.lexists(path))
655
self.assertEqualDiff(content, open(path, 'r').read())
658
class TestCaseWithTransport(TestCaseInTempDir):
659
"""A test case that provides get_url and get_readonly_url facilities.
661
These back onto two transport servers, one for readonly access and one for
664
If no explicit class is provided for readonly access, a
665
ReadonlyTransportDecorator is used instead which allows the use of non disk
666
based read write transports.
668
If an explicit class is provided for readonly access, that server and the
669
readwrite one must both define get_url() as resolving to os.getcwd().
672
def __init__(self, methodName='testMethod'):
673
super(TestCaseWithTransport, self).__init__(methodName)
674
self.__readonly_server = None
676
self.transport_server = default_transport
677
self.transport_readonly_server = None
679
def get_readonly_url(self, relpath=None):
680
"""Get a URL for the readonly transport.
682
This will either be backed by '.' or a decorator to the transport
683
used by self.get_url()
684
relpath provides for clients to get a path relative to the base url.
685
These should only be downwards relative, not upwards.
687
base = self.get_readonly_server().get_url()
688
if relpath is not None:
689
if not base.endswith('/'):
691
base = base + relpath
694
def get_readonly_server(self):
695
"""Get the server instance for the readonly transport
697
This is useful for some tests with specific servers to do diagnostics.
699
if self.__readonly_server is None:
700
if self.transport_readonly_server is None:
701
# readonly decorator requested
702
# bring up the server
704
self.__readonly_server = ReadonlyServer()
705
self.__readonly_server.setUp(self.__server)
707
self.__readonly_server = self.transport_readonly_server()
708
self.__readonly_server.setUp()
709
self.addCleanup(self.__readonly_server.tearDown)
710
return self.__readonly_server
712
def get_server(self):
713
"""Get the read/write server instance.
715
This is useful for some tests with specific servers that need
718
if self.__server is None:
719
self.__server = self.transport_server()
720
self.__server.setUp()
721
self.addCleanup(self.__server.tearDown)
724
def get_url(self, relpath=None):
725
"""Get a URL for the readwrite transport.
727
This will either be backed by '.' or to an equivalent non-file based
729
relpath provides for clients to get a path relative to the base url.
730
These should only be downwards relative, not upwards.
732
base = self.get_server().get_url()
733
if relpath is not None and relpath != '.':
734
if not base.endswith('/'):
736
base = base + relpath
739
def get_transport(self):
740
"""Return a writeable transport for the test scratch space"""
741
t = get_transport(self.get_url())
742
self.assertFalse(t.is_readonly())
745
def get_readonly_transport(self):
746
"""Return a readonly transport for the test scratch space
748
This can be used to test that operations which should only need
749
readonly access in fact do not try to write.
751
t = get_transport(self.get_readonly_url())
752
self.assertTrue(t.is_readonly())
755
def make_branch(self, relpath):
756
"""Create a branch on the transport at relpath."""
757
repo = self.make_repository(relpath)
758
return repo.bzrdir.create_branch()
760
def make_bzrdir(self, relpath):
762
url = self.get_url(relpath)
763
segments = relpath.split('/')
764
if segments and segments[-1] not in ('', '.'):
765
parent = self.get_url('/'.join(segments[:-1]))
766
t = get_transport(parent)
768
t.mkdir(segments[-1])
769
except errors.FileExists:
771
return bzrlib.bzrdir.BzrDir.create(url)
772
except errors.UninitializableFormat:
773
raise TestSkipped("Format %s is not initializable.")
775
def make_repository(self, relpath, shared=False):
776
"""Create a repository on our default transport at relpath."""
777
made_control = self.make_bzrdir(relpath)
778
return made_control.create_repository(shared=shared)
780
def make_branch_and_tree(self, relpath):
781
"""Create a branch on the transport and a tree locally.
785
# TODO: always use the local disk path for the working tree,
786
# this obviously requires a format that supports branch references
787
# so check for that by checking bzrdir.BzrDirFormat.get_default_format()
789
b = self.make_branch(relpath)
791
return b.bzrdir.create_workingtree()
792
except errors.NotLocalUrl:
793
# new formats - catch No tree error and create
794
# a branch reference and a checkout.
795
# old formats at that point - raise TestSkipped.
797
return WorkingTreeFormat2().initialize(bzrdir.BzrDir.open(relpath))
799
def assertIsDirectory(self, relpath, transport):
800
"""Assert that relpath within transport is a directory.
802
This may not be possible on all transports; in that case it propagates
803
a TransportNotPossible.
806
mode = transport.stat(relpath).st_mode
807
except errors.NoSuchFile:
808
self.fail("path %s is not a directory; no such file"
810
if not stat.S_ISDIR(mode):
811
self.fail("path %s is not a directory; has mode %#o"
815
class ChrootedTestCase(TestCaseWithTransport):
816
"""A support class that provides readonly urls outside the local namespace.
818
This is done by checking if self.transport_server is a MemoryServer. if it
819
is then we are chrooted already, if it is not then an HttpServer is used
822
TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
823
be used without needed to redo it when a different
828
super(ChrootedTestCase, self).setUp()
829
if not self.transport_server == bzrlib.transport.memory.MemoryServer:
830
self.transport_readonly_server = bzrlib.transport.http.HttpServer
833
def filter_suite_by_re(suite, pattern):
835
filter_re = re.compile(pattern)
836
for test in iter_suite_tests(suite):
837
if filter_re.search(test.id()):
842
def run_suite(suite, name='test', verbose=False, pattern=".*",
843
stop_on_failure=False, keep_output=False,
845
TestCaseInTempDir._TEST_NAME = name
850
runner = TextTestRunner(stream=sys.stdout,
853
runner.stop_on_failure=stop_on_failure
855
suite = filter_suite_by_re(suite, pattern)
856
result = runner.run(suite)
857
# This is still a little bogus,
858
# but only a little. Folk not using our testrunner will
859
# have to delete their temp directories themselves.
860
if result.wasSuccessful() or not keep_output:
861
if TestCaseInTempDir.TEST_ROOT is not None:
862
shutil.rmtree(TestCaseInTempDir.TEST_ROOT)
864
print "Failed tests working directories are in '%s'\n" % TestCaseInTempDir.TEST_ROOT
865
return result.wasSuccessful()
868
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
871
"""Run the whole test suite under the enhanced runner"""
872
global default_transport
873
if transport is None:
874
transport = default_transport
875
old_transport = default_transport
876
default_transport = transport
879
return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
880
stop_on_failure=stop_on_failure, keep_output=keep_output,
883
default_transport = old_transport
888
"""Build and return TestSuite for the whole program."""
889
from doctest import DocTestSuite
891
global MODULES_TO_DOCTEST
894
'bzrlib.tests.test_ancestry',
895
'bzrlib.tests.test_annotate',
896
'bzrlib.tests.test_api',
897
'bzrlib.tests.test_bad_files',
898
'bzrlib.tests.test_basis_inventory',
899
'bzrlib.tests.test_branch',
900
'bzrlib.tests.test_bzrdir',
901
'bzrlib.tests.test_command',
902
'bzrlib.tests.test_commit',
903
'bzrlib.tests.test_commit_merge',
904
'bzrlib.tests.test_config',
905
'bzrlib.tests.test_conflicts',
906
'bzrlib.tests.test_decorators',
907
'bzrlib.tests.test_diff',
908
'bzrlib.tests.test_doc_generate',
909
'bzrlib.tests.test_errors',
910
'bzrlib.tests.test_fetch',
911
'bzrlib.tests.test_gpg',
912
'bzrlib.tests.test_graph',
913
'bzrlib.tests.test_hashcache',
914
'bzrlib.tests.test_http',
915
'bzrlib.tests.test_identitymap',
916
'bzrlib.tests.test_inv',
917
'bzrlib.tests.test_lockdir',
918
'bzrlib.tests.test_lockable_files',
919
'bzrlib.tests.test_log',
920
'bzrlib.tests.test_merge',
921
'bzrlib.tests.test_merge3',
922
'bzrlib.tests.test_merge_core',
923
'bzrlib.tests.test_missing',
924
'bzrlib.tests.test_msgeditor',
925
'bzrlib.tests.test_nonascii',
926
'bzrlib.tests.test_options',
927
'bzrlib.tests.test_osutils',
928
'bzrlib.tests.test_permissions',
929
'bzrlib.tests.test_plugins',
930
'bzrlib.tests.test_reconcile',
931
'bzrlib.tests.test_repository',
932
'bzrlib.tests.test_revision',
933
'bzrlib.tests.test_revisionnamespaces',
934
'bzrlib.tests.test_revprops',
935
'bzrlib.tests.test_reweave',
936
'bzrlib.tests.test_rio',
937
'bzrlib.tests.test_sampler',
938
'bzrlib.tests.test_selftest',
939
'bzrlib.tests.test_setup',
940
'bzrlib.tests.test_sftp_transport',
941
'bzrlib.tests.test_smart_add',
942
'bzrlib.tests.test_source',
943
'bzrlib.tests.test_store',
944
'bzrlib.tests.test_symbol_versioning',
945
'bzrlib.tests.test_testament',
946
'bzrlib.tests.test_trace',
947
'bzrlib.tests.test_transactions',
948
'bzrlib.tests.test_transform',
949
'bzrlib.tests.test_transport',
950
'bzrlib.tests.test_tsort',
951
'bzrlib.tests.test_ui',
952
'bzrlib.tests.test_uncommit',
953
'bzrlib.tests.test_upgrade',
954
'bzrlib.tests.test_weave',
955
'bzrlib.tests.test_whitebox',
956
'bzrlib.tests.test_workingtree',
957
'bzrlib.tests.test_xml',
959
test_transport_implementations = [
960
'bzrlib.tests.test_transport_implementations']
962
TestCase.BZRPATH = osutils.pathjoin(
963
osutils.realpath(osutils.dirname(bzrlib.__path__[0])), 'bzr')
964
print '%10s: %s' % ('bzr', osutils.realpath(sys.argv[0]))
965
print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
968
# python2.4's TestLoader.loadTestsFromNames gives very poor
969
# errors if it fails to load a named module - no indication of what's
970
# actually wrong, just "no such module". We should probably override that
971
# class, but for the moment just load them ourselves. (mbp 20051202)
972
loader = TestLoader()
973
from bzrlib.transport import TransportTestProviderAdapter
974
adapter = TransportTestProviderAdapter()
975
adapt_modules(test_transport_implementations, adapter, loader, suite)
976
for mod_name in testmod_names:
977
mod = _load_module_by_name(mod_name)
978
suite.addTest(loader.loadTestsFromModule(mod))
979
for package in packages_to_test():
980
suite.addTest(package.test_suite())
981
for m in MODULES_TO_TEST:
982
suite.addTest(loader.loadTestsFromModule(m))
983
for m in (MODULES_TO_DOCTEST):
984
suite.addTest(DocTestSuite(m))
985
for name, plugin in bzrlib.plugin.all_plugins().items():
986
if getattr(plugin, 'test_suite', None) is not None:
987
suite.addTest(plugin.test_suite())
991
def adapt_modules(mods_list, adapter, loader, suite):
992
"""Adapt the modules in mods_list using adapter and add to suite."""
993
for mod_name in mods_list:
994
mod = _load_module_by_name(mod_name)
995
for test in iter_suite_tests(loader.loadTestsFromModule(mod)):
996
suite.addTests(adapter.adapt(test))
999
def _load_module_by_name(mod_name):
1000
parts = mod_name.split('.')
1001
module = __import__(mod_name)
1003
# for historical reasons python returns the top-level module even though
1004
# it loads the submodule; we need to walk down to get the one we want.
1006
module = getattr(module, parts.pop(0))