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
from cStringIO import StringIO
18
from testsweet import TestBase, run_suite, InTempDir
39
19
import bzrlib.commands
40
from bzrlib.errors import BzrError
41
import bzrlib.inventory
44
import bzrlib.osutils as osutils
48
from bzrlib.transport import urlescape
49
import bzrlib.transport
50
from bzrlib.transport.readonly import ReadonlyServer
51
from bzrlib.trace import mutter
52
from bzrlib.tests.TestUtil import TestLoader, TestSuite
53
from bzrlib.tests.treeshape import build_tree_contents
55
21
MODULES_TO_TEST = []
56
MODULES_TO_DOCTEST = [
65
def packages_to_test():
66
import bzrlib.tests.blackbox
72
class EarlyStoppingTestResultAdapter(object):
73
"""An adapter for TestResult to stop at the first first failure or error"""
75
def __init__(self, result):
78
def addError(self, test, err):
79
if (isinstance(err[1], TestSkipped) and
80
getattr(self, "addSkipped", None) is not None):
81
return self.addSkipped(test, err)
82
self._result.addError(test, err)
85
def addFailure(self, test, err):
86
self._result.addFailure(test, err)
89
def __getattr__(self, name):
90
return getattr(self._result, name)
92
def __setattr__(self, name, value):
94
object.__setattr__(self, name, value)
95
return setattr(self._result, name, value)
98
class _MyResult(unittest._TextTestResult):
101
Shows output in a different format, including displaying runtime for tests.
104
def _elapsedTime(self):
105
return "%5dms" % (1000 * (time.time() - self._start_time))
107
def startTest(self, test):
108
unittest.TestResult.startTest(self, test)
109
# In a short description, the important words are in
110
# the beginning, but in an id, the important words are
112
SHOW_DESCRIPTIONS = False
114
width = osutils.terminal_width()
115
name_width = width - 15
117
if SHOW_DESCRIPTIONS:
118
what = test.shortDescription()
120
if len(what) > name_width:
121
what = what[:name_width-3] + '...'
124
if what.startswith('bzrlib.tests.'):
126
if len(what) > name_width:
127
what = '...' + what[3-name_width:]
128
what = what.ljust(name_width)
129
self.stream.write(what)
131
self._start_time = time.time()
133
def addError(self, test, err):
134
if isinstance(err[1], TestSkipped):
135
return self.addSkipped(test, err)
136
unittest.TestResult.addError(self, test, err)
138
self.stream.writeln("ERROR %s" % self._elapsedTime())
140
self.stream.write('E')
143
def addFailure(self, test, err):
144
unittest.TestResult.addFailure(self, test, err)
146
self.stream.writeln(" FAIL %s" % self._elapsedTime())
148
self.stream.write('F')
151
def addSuccess(self, test):
153
self.stream.writeln(' OK %s' % self._elapsedTime())
155
self.stream.write('~')
157
unittest.TestResult.addSuccess(self, test)
159
def addSkipped(self, test, skip_excinfo):
161
print >>self.stream, ' SKIP %s' % self._elapsedTime()
162
print >>self.stream, ' %s' % skip_excinfo[1]
164
self.stream.write('S')
166
# seems best to treat this as success from point-of-view of unittest
167
# -- it actually does nothing so it barely matters :)
168
unittest.TestResult.addSuccess(self, test)
170
def printErrorList(self, flavour, errors):
171
for test, err in errors:
172
self.stream.writeln(self.separator1)
173
self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
174
if getattr(test, '_get_log', None) is not None:
176
print >>self.stream, \
177
('vvvv[log from %s]' % test.id()).ljust(78,'-')
178
print >>self.stream, test._get_log()
179
print >>self.stream, \
180
('^^^^[log from %s]' % test.id()).ljust(78,'-')
181
self.stream.writeln(self.separator2)
182
self.stream.writeln("%s" % err)
185
class TextTestRunner(unittest.TextTestRunner):
186
stop_on_failure = False
188
def _makeResult(self):
189
result = _MyResult(self.stream, self.descriptions, self.verbosity)
190
if self.stop_on_failure:
191
result = EarlyStoppingTestResultAdapter(result)
195
def iter_suite_tests(suite):
196
"""Return all tests in a suite, recursing through nested suites"""
197
for item in suite._tests:
198
if isinstance(item, unittest.TestCase):
200
elif isinstance(item, unittest.TestSuite):
201
for r in iter_suite_tests(item):
204
raise Exception('unknown object %r inside test suite %r'
208
class TestSkipped(Exception):
209
"""Indicates that a test was intentionally skipped, rather than failing."""
213
class CommandFailed(Exception):
216
class TestCase(unittest.TestCase):
217
"""Base class for bzr unit tests.
219
Tests that need access to disk resources should subclass
220
TestCaseInTempDir not TestCase.
222
Error and debug log messages are redirected from their usual
223
location into a temporary file, the contents of which can be
224
retrieved by _get_log(). We use a real OS file, not an in-memory object,
225
so that it can also capture file IO. When the test completes this file
226
is read into memory and removed from disk.
228
There are also convenience functions to invoke bzr's command-line
229
routine, and to build and check bzr trees.
231
In addition to the usual method of overriding tearDown(), this class also
232
allows subclasses to register functions into the _cleanups list, which is
233
run in order as the object is torn down. It's less likely this will be
234
accidentally overlooked.
238
_log_file_name = None
241
def __init__(self, methodName='testMethod'):
242
super(TestCase, self).__init__(methodName)
246
unittest.TestCase.setUp(self)
247
self._cleanEnvironment()
248
bzrlib.trace.disable_default_logging()
251
def _ndiff_strings(self, a, b):
252
"""Return ndiff between two strings containing lines.
254
A trailing newline is added if missing to make the strings
256
if b and b[-1] != '\n':
258
if a and a[-1] != '\n':
260
difflines = difflib.ndiff(a.splitlines(True),
262
linejunk=lambda x: False,
263
charjunk=lambda x: False)
264
return ''.join(difflines)
266
def assertEqualDiff(self, a, b):
267
"""Assert two texts are equal, if not raise an exception.
269
This is intended for use with multi-line strings where it can
270
be hard to find the differences by eye.
272
# TODO: perhaps override assertEquals to call this for strings?
275
raise AssertionError("texts not equal:\n" +
276
self._ndiff_strings(a, b))
278
def assertStartsWith(self, s, prefix):
279
if not s.startswith(prefix):
280
raise AssertionError('string %r does not start with %r' % (s, prefix))
282
def assertEndsWith(self, s, suffix):
283
if not s.endswith(prefix):
284
raise AssertionError('string %r does not end with %r' % (s, suffix))
286
def assertContainsRe(self, haystack, needle_re):
287
"""Assert that a contains something matching a regular expression."""
288
if not re.search(needle_re, haystack):
289
raise AssertionError('pattern "%s" not found in "%s"'
290
% (needle_re, haystack))
292
def AssertSubset(self, sublist, superlist):
293
"""Assert that every entry in sublist is present in superlist."""
295
for entry in sublist:
296
if entry not in superlist:
297
missing.append(entry)
299
raise AssertionError("value(s) %r not present in container %r" %
300
(missing, superlist))
302
def assertTransportMode(self, transport, path, mode):
303
"""Fail if a path does not have mode mode.
305
If modes are not supported on this platform, the test is skipped.
307
if sys.platform == 'win32':
309
path_stat = transport.stat(path)
310
actual_mode = stat.S_IMODE(path_stat.st_mode)
311
self.assertEqual(mode, actual_mode,
312
'mode of %r incorrect (%o != %o)' % (path, mode, actual_mode))
314
def _startLogFile(self):
315
"""Send bzr and test log messages to a temporary file.
317
The file is removed as the test is torn down.
319
fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
320
encoder, decoder, stream_reader, stream_writer = codecs.lookup('UTF-8')
321
self._log_file = stream_writer(os.fdopen(fileno, 'w+'))
322
bzrlib.trace.enable_test_log(self._log_file)
323
self._log_file_name = name
324
self.addCleanup(self._finishLogFile)
326
def _finishLogFile(self):
327
"""Finished with the log file.
329
Read contents into memory, close, and delete.
331
bzrlib.trace.disable_test_log()
332
self._log_file.seek(0)
333
self._log_contents = self._log_file.read()
334
self._log_file.close()
335
os.remove(self._log_file_name)
336
self._log_file = self._log_file_name = None
338
def addCleanup(self, callable):
339
"""Arrange to run a callable when this case is torn down.
341
Callables are run in the reverse of the order they are registered,
342
ie last-in first-out.
344
if callable in self._cleanups:
345
raise ValueError("cleanup function %r already registered on %s"
347
self._cleanups.append(callable)
349
def _cleanEnvironment(self):
352
'APPDATA': os.getcwd(),
357
self.addCleanup(self._restoreEnvironment)
358
for name, value in new_env.iteritems():
359
self._captureVar(name, value)
362
def _captureVar(self, name, newvalue):
363
"""Set an environment variable, preparing it to be reset when finished."""
364
self.__old_env[name] = os.environ.get(name, None)
366
if name in os.environ:
369
os.environ[name] = newvalue
372
def _restoreVar(name, value):
374
if name in os.environ:
377
os.environ[name] = value
379
def _restoreEnvironment(self):
380
for name, value in self.__old_env.iteritems():
381
self._restoreVar(name, value)
385
unittest.TestCase.tearDown(self)
387
def _runCleanups(self):
388
"""Run registered cleanup functions.
390
This should only be called from TestCase.tearDown.
392
# TODO: Perhaps this should keep running cleanups even if
394
for cleanup_fn in reversed(self._cleanups):
397
def log(self, *args):
401
"""Return as a string the log for this test"""
402
if self._log_file_name:
403
return open(self._log_file_name).read()
405
return self._log_contents
406
# TODO: Delete the log after it's been read in
408
def capture(self, cmd, retcode=0):
409
"""Shortcut that splits cmd into words, runs, and returns stdout"""
410
return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
412
def run_bzr_captured(self, argv, retcode=0):
413
"""Invoke bzr and return (stdout, stderr).
415
Useful for code that wants to check the contents of the
416
output, the way error messages are presented, etc.
418
This should be the main method for tests that want to exercise the
419
overall behavior of the bzr application (rather than a unit test
420
or a functional test of the library.)
422
Much of the old code runs bzr by forking a new copy of Python, but
423
that is slower, harder to debug, and generally not necessary.
425
This runs bzr through the interface that catches and reports
426
errors, and with logging set to something approximating the
427
default, so that error reporting can be checked.
429
argv -- arguments to invoke bzr
430
retcode -- expected return code, or None for don't-care.
434
self.log('run bzr: %s', ' '.join(argv))
435
# FIXME: don't call into logging here
436
handler = logging.StreamHandler(stderr)
437
handler.setFormatter(bzrlib.trace.QuietFormatter())
438
handler.setLevel(logging.INFO)
439
logger = logging.getLogger('')
440
logger.addHandler(handler)
442
result = self.apply_redirected(None, stdout, stderr,
443
bzrlib.commands.run_bzr_catch_errors,
446
logger.removeHandler(handler)
447
out = stdout.getvalue()
448
err = stderr.getvalue()
450
self.log('output:\n%s', out)
452
self.log('errors:\n%s', err)
453
if retcode is not None:
454
self.assertEquals(result, retcode)
22
MODULES_TO_DOCTEST = []
25
class BzrTestBase(InTempDir):
26
"""bzr-specific test base class"""
457
27
def run_bzr(self, *args, **kwargs):
458
"""Invoke bzr, as if it were run from the command line.
460
This should be the main method for tests that want to exercise the
461
overall behavior of the bzr application (rather than a unit test
462
or a functional test of the library.)
464
This sends the stdout/stderr results into the test's log,
465
where it may be useful for debugging. See also run_captured.
467
retcode = kwargs.pop('retcode', 0)
468
return self.run_bzr_captured(args, retcode)
470
def check_inventory_shape(self, inv, shape):
471
"""Compare an inventory to a list of expected names.
473
Fail if they are not precisely equal.
476
shape = list(shape) # copy
477
for path, ie in inv.entries():
478
name = path.replace('\\', '/')
486
self.fail("expected paths not found in inventory: %r" % shape)
488
self.fail("unexpected paths found in inventory: %r" % extras)
490
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
491
a_callable=None, *args, **kwargs):
492
"""Call callable with redirected std io pipes.
494
Returns the return code."""
495
if not callable(a_callable):
496
raise ValueError("a_callable must be callable.")
500
if getattr(self, "_log_file", None) is not None:
501
stdout = self._log_file
505
if getattr(self, "_log_file", None is not None):
506
stderr = self._log_file
509
real_stdin = sys.stdin
510
real_stdout = sys.stdout
511
real_stderr = sys.stderr
516
return a_callable(*args, **kwargs)
518
sys.stdout = real_stdout
519
sys.stderr = real_stderr
520
sys.stdin = real_stdin
523
BzrTestBase = TestCase
526
class TestCaseInTempDir(TestCase):
527
"""Derived class that runs a test within a temporary directory.
529
This is useful for tests that need to create a branch, etc.
531
The directory is created in a slightly complex way: for each
532
Python invocation, a new temporary top-level directory is created.
533
All test cases create their own directory within that. If the
534
tests complete successfully, the directory is removed.
536
InTempDir is an old alias for FunctionalTestCase.
541
OVERRIDE_PYTHON = 'python'
543
def check_file_contents(self, filename, expect):
544
self.log("check contents of file %s" % filename)
545
contents = file(filename, 'r').read()
546
if contents != expect:
547
self.log("expected: %r" % expect)
548
self.log("actually: %r" % contents)
549
self.fail("contents of %s not as expected" % filename)
551
def _make_test_root(self):
552
if TestCaseInTempDir.TEST_ROOT is not None:
556
root = u'test%04d.tmp' % i
560
if e.errno == errno.EEXIST:
565
# successfully created
566
TestCaseInTempDir.TEST_ROOT = osutils.abspath(root)
568
# make a fake bzr directory there to prevent any tests propagating
569
# up onto the source directory's real branch
570
os.mkdir(osutils.pathjoin(TestCaseInTempDir.TEST_ROOT, '.bzr'))
573
super(TestCaseInTempDir, self).setUp()
574
self._make_test_root()
575
_currentdir = os.getcwdu()
576
short_id = self.id().replace('bzrlib.tests.', '') \
577
.replace('__main__.', '')
578
self.test_dir = osutils.pathjoin(self.TEST_ROOT, short_id)
579
os.mkdir(self.test_dir)
580
os.chdir(self.test_dir)
581
os.environ['HOME'] = self.test_dir
582
os.environ['APPDATA'] = self.test_dir
583
def _leaveDirectory():
584
os.chdir(_currentdir)
585
self.addCleanup(_leaveDirectory)
587
def build_tree(self, shape, line_endings='native', transport=None):
588
"""Build a test tree according to a pattern.
590
shape is a sequence of file specifications. If the final
591
character is '/', a directory is created.
593
This doesn't add anything to a branch.
594
:param line_endings: Either 'binary' or 'native'
595
in binary mode, exact contents are written
596
in native mode, the line endings match the
597
default platform endings.
599
:param transport: A transport to write to, for building trees on
600
VFS's. If the transport is readonly or None,
601
"." is opened automatically.
603
# XXX: It's OK to just create them using forward slashes on windows?
604
if transport is None or transport.is_readonly():
605
transport = bzrlib.transport.get_transport(".")
607
self.assert_(isinstance(name, basestring))
609
transport.mkdir(urlescape(name[:-1]))
611
if line_endings == 'binary':
613
elif line_endings == 'native':
616
raise BzrError('Invalid line ending request %r' % (line_endings,))
617
content = "contents of %s%s" % (name, end)
618
transport.put(urlescape(name), StringIO(content))
620
def build_tree_contents(self, shape):
621
build_tree_contents(shape)
623
def failUnlessExists(self, path):
624
"""Fail unless path, which may be abs or relative, exists."""
625
self.failUnless(osutils.lexists(path))
627
def failIfExists(self, path):
628
"""Fail if path, which may be abs or relative, exists."""
629
self.failIf(osutils.lexists(path))
631
def assertFileEqual(self, content, path):
632
"""Fail if path does not contain 'content'."""
633
self.failUnless(osutils.lexists(path))
634
self.assertEqualDiff(content, open(path, 'r').read())
637
class TestCaseWithTransport(TestCaseInTempDir):
638
"""A test case that provides get_url and get_readonly_url facilities.
640
These back onto two transport servers, one for readonly access and one for
643
If no explicit class is provided for readonly access, a
644
ReadonlyTransportDecorator is used instead which allows the use of non disk
645
based read write transports.
647
If an explicit class is provided for readonly access, that server and the
648
readwrite one must both define get_url() as resolving to os.getcwd().
651
def __init__(self, methodName='testMethod'):
652
super(TestCaseWithTransport, self).__init__(methodName)
653
self.__readonly_server = None
655
self.transport_server = bzrlib.transport.local.LocalRelpathServer
656
self.transport_readonly_server = None
658
def get_readonly_url(self, relpath=None):
659
"""Get a URL for the readonly transport.
661
This will either be backed by '.' or a decorator to the transport
662
used by self.get_url()
663
relpath provides for clients to get a path relative to the base url.
664
These should only be downwards relative, not upwards.
666
if self.__readonly_server is None:
667
if self.transport_readonly_server is None:
668
# readonly decorator requested
669
# bring up the server
671
self.__readonly_server = ReadonlyServer()
672
self.__readonly_server.setUp(self.__server)
674
self.__readonly_server = self.transport_readonly_server()
675
self.__readonly_server.setUp()
676
self.addCleanup(self.__readonly_server.tearDown)
677
base = self.__readonly_server.get_url()
678
if relpath is not None:
679
if not base.endswith('/'):
681
base = base + relpath
684
def get_url(self, relpath=None):
685
"""Get a URL for the readwrite transport.
687
This will either be backed by '.' or to an equivalent non-file based
689
relpath provides for clients to get a path relative to the base url.
690
These should only be downwards relative, not upwards.
692
if self.__server is None:
693
self.__server = self.transport_server()
694
self.__server.setUp()
695
self.addCleanup(self.__server.tearDown)
696
base = self.__server.get_url()
697
if relpath is not None:
698
if not base.endswith('/'):
700
base = base + relpath
706
def filter_suite_by_re(suite, pattern):
708
filter_re = re.compile(pattern)
709
for test in iter_suite_tests(suite):
710
if filter_re.search(test.id()):
715
def run_suite(suite, name='test', verbose=False, pattern=".*",
716
stop_on_failure=False, keep_output=False):
717
TestCaseInTempDir._TEST_NAME = name
722
runner = TextTestRunner(stream=sys.stdout,
725
runner.stop_on_failure=stop_on_failure
727
suite = filter_suite_by_re(suite, pattern)
728
result = runner.run(suite)
729
# This is still a little bogus,
730
# but only a little. Folk not using our testrunner will
731
# have to delete their temp directories themselves.
732
if result.wasSuccessful() or not keep_output:
733
if TestCaseInTempDir.TEST_ROOT is not None:
734
shutil.rmtree(TestCaseInTempDir.TEST_ROOT)
736
print "Failed tests working directories are in '%s'\n" % TestCaseInTempDir.TEST_ROOT
737
return result.wasSuccessful()
740
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
742
"""Run the whole test suite under the enhanced runner"""
743
return run_suite(test_suite(), 'testbzr', verbose=verbose, pattern=pattern,
744
stop_on_failure=stop_on_failure, keep_output=keep_output)
748
"""Build and return TestSuite for the whole program."""
28
retcode = kwargs.get('retcode', 0)
29
self.assertEquals(bzrlib.commands.run_bzr(args), retcode)
32
def selftest(verbose=False):
33
from unittest import TestLoader, TestSuite
34
import bzrlib, bzrlib.store, bzrlib.inventory, bzrlib.branch
35
import bzrlib.osutils, bzrlib.commands, bzrlib.merge3, bzrlib.plugin
749
36
from doctest import DocTestSuite
751
global MODULES_TO_DOCTEST
754
'bzrlib.tests.test_ancestry',
755
'bzrlib.tests.test_annotate',
756
'bzrlib.tests.test_api',
757
'bzrlib.tests.test_bad_files',
758
'bzrlib.tests.test_basis_inventory',
759
'bzrlib.tests.test_branch',
760
'bzrlib.tests.test_command',
761
'bzrlib.tests.test_commit',
762
'bzrlib.tests.test_commit_merge',
763
'bzrlib.tests.test_config',
764
'bzrlib.tests.test_conflicts',
765
'bzrlib.tests.test_diff',
766
'bzrlib.tests.test_fetch',
767
'bzrlib.tests.test_gpg',
768
'bzrlib.tests.test_graph',
769
'bzrlib.tests.test_hashcache',
770
'bzrlib.tests.test_http',
771
'bzrlib.tests.test_identitymap',
772
'bzrlib.tests.test_inv',
773
'bzrlib.tests.test_log',
774
'bzrlib.tests.test_merge',
775
'bzrlib.tests.test_merge3',
776
'bzrlib.tests.test_merge_core',
777
'bzrlib.tests.test_missing',
778
'bzrlib.tests.test_msgeditor',
779
'bzrlib.tests.test_nonascii',
780
'bzrlib.tests.test_options',
781
'bzrlib.tests.test_osutils',
782
'bzrlib.tests.test_parent',
783
'bzrlib.tests.test_permissions',
784
'bzrlib.tests.test_plugins',
785
'bzrlib.tests.test_remove',
786
'bzrlib.tests.test_revision',
787
'bzrlib.tests.test_revisionnamespaces',
788
'bzrlib.tests.test_revprops',
789
'bzrlib.tests.test_reweave',
790
'bzrlib.tests.test_rio',
791
'bzrlib.tests.test_sampler',
792
'bzrlib.tests.test_selftest',
793
'bzrlib.tests.test_setup',
794
'bzrlib.tests.test_sftp_transport',
795
'bzrlib.tests.test_smart_add',
796
'bzrlib.tests.test_source',
797
'bzrlib.tests.test_status',
798
'bzrlib.tests.test_store',
799
'bzrlib.tests.test_symbol_versioning',
800
'bzrlib.tests.test_testament',
801
'bzrlib.tests.test_trace',
802
'bzrlib.tests.test_transactions',
803
'bzrlib.tests.test_transport',
804
'bzrlib.tests.test_tsort',
805
'bzrlib.tests.test_ui',
806
'bzrlib.tests.test_uncommit',
807
'bzrlib.tests.test_upgrade',
808
'bzrlib.tests.test_weave',
809
'bzrlib.tests.test_whitebox',
810
'bzrlib.tests.test_workingtree',
811
'bzrlib.tests.test_xml',
43
global MODULES_TO_TEST, MODULES_TO_DOCTEST
46
['bzrlib.selftest.whitebox',
47
'bzrlib.selftest.versioning',
48
'bzrlib.selftest.testinv',
49
'bzrlib.selftest.testmerge3',
50
'bzrlib.selftest.testhashcache',
51
'bzrlib.selftest.teststatus',
52
'bzrlib.selftest.testlog',
53
'bzrlib.selftest.blackbox',
54
'bzrlib.selftest.testrevisionnamespaces',
55
'bzrlib.selftest.testbranch',
56
'bzrlib.selftest.testrevision',
58
'bzrlib.selftest.testdiff',
813
test_branch_implementations = [
814
'bzrlib.tests.test_branch_implementations']
815
test_transport_implementations = [
816
'bzrlib.tests.test_transport_implementations']
818
TestCase.BZRPATH = osutils.pathjoin(
819
osutils.realpath(osutils.dirname(bzrlib.__path__[0])), 'bzr')
820
print '%10s: %s' % ('bzr', osutils.realpath(sys.argv[0]))
821
print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
61
# XXX: should also test bzrlib.merge_core, but they seem to be out
62
# of date with the code.
64
for m in (bzrlib.store, bzrlib.inventory, bzrlib.branch,
65
bzrlib.osutils, bzrlib.commands, bzrlib.merge3):
66
if m not in MODULES_TO_DOCTEST:
67
MODULES_TO_DOCTEST.append(m)
70
TestBase.BZRPATH = os.path.join(os.path.realpath(os.path.dirname(bzrlib.__path__[0])), 'bzr')
71
print '%-30s %s' % ('bzr binary', TestBase.BZRPATH)
823
75
suite = TestSuite()
824
# python2.4's TestLoader.loadTestsFromNames gives very poor
825
# errors if it fails to load a named module - no indication of what's
826
# actually wrong, just "no such module". We should probably override that
827
# class, but for the moment just load them ourselves. (mbp 20051202)
828
loader = TestLoader()
829
from bzrlib.transport import TransportTestProviderAdapter
830
adapter = TransportTestProviderAdapter()
831
for mod_name in test_transport_implementations:
832
mod = _load_module_by_name(mod_name)
833
for test in iter_suite_tests(loader.loadTestsFromModule(mod)):
834
suite.addTests(adapter.adapt(test))
835
from bzrlib.branch import BranchTestProviderAdapter
836
adapter = BranchTestProviderAdapter(
837
bzrlib.transport.local.LocalRelpathServer,
838
# None here will cause a readonly decorator to be created
839
# by the TestCaseWithTransport.get_readonly_transport method.
841
bzrlib.branch.BzrBranchFormat._formats.values())
842
for mod_name in test_branch_implementations:
843
mod = _load_module_by_name(mod_name)
844
for test in iter_suite_tests(loader.loadTestsFromModule(mod)):
845
suite.addTests(adapter.adapt(test))
846
for mod_name in testmod_names:
847
mod = _load_module_by_name(mod_name)
848
suite.addTest(loader.loadTestsFromModule(mod))
849
for package in packages_to_test():
850
suite.addTest(package.test_suite())
77
suite.addTest(TestLoader().loadTestsFromNames(testmod_names))
851
79
for m in MODULES_TO_TEST:
852
suite.addTest(loader.loadTestsFromModule(m))
80
suite.addTest(TestLoader().loadTestsFromModule(m))
853
82
for m in (MODULES_TO_DOCTEST):
854
83
suite.addTest(DocTestSuite(m))
855
for name, plugin in bzrlib.plugin.all_plugins().items():
856
if getattr(plugin, 'test_suite', None) is not None:
857
suite.addTest(plugin.test_suite())
861
def _load_module_by_name(mod_name):
862
parts = mod_name.split('.')
863
module = __import__(mod_name)
865
# for historical reasons python returns the top-level module even though
866
# it loads the submodule; we need to walk down to get the one we want.
868
module = getattr(module, parts.pop(0))
85
for p in bzrlib.plugin.all_plugins:
86
if hasattr(p, 'test_suite'):
87
suite.addTest(p.test_suite())
89
import bzrlib.merge_core
90
suite.addTest(unittest.makeSuite(bzrlib.merge_core.MergeTest, 'test_'))
92
return run_suite(suite, 'testbzr', verbose=verbose)