/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Robert Collins
  • Date: 2005-11-29 23:20:31 UTC
  • Revision ID: robertc@robertcollins.net-20051129232031-916cdaefe3a3c19b
    * bzrlib.plugin.all_plugins has been changed from an attribute to a 
      query method. (Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 by Canonical Ltd
 
2
 
 
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.
 
7
 
 
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.
 
12
 
 
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
 
16
 
 
17
 
 
18
from cStringIO import StringIO
 
19
import difflib
 
20
import errno
 
21
import logging
 
22
import os
 
23
import re
 
24
import shutil
 
25
import sys
 
26
import tempfile
 
27
import unittest
 
28
import time
 
29
 
 
30
import bzrlib.branch
 
31
import bzrlib.commands
 
32
from bzrlib.errors import BzrError
 
33
import bzrlib.inventory
 
34
import bzrlib.merge3
 
35
import bzrlib.osutils
 
36
import bzrlib.osutils as osutils
 
37
import bzrlib.plugin
 
38
import bzrlib.store
 
39
import bzrlib.trace
 
40
from bzrlib.trace import mutter
 
41
from bzrlib.tests.TestUtil import TestLoader, TestSuite
 
42
from bzrlib.tests.treeshape import build_tree_contents
 
43
 
 
44
MODULES_TO_TEST = []
 
45
MODULES_TO_DOCTEST = [
 
46
                      bzrlib.branch,
 
47
                      bzrlib.commands,
 
48
                      bzrlib.errors,
 
49
                      bzrlib.inventory,
 
50
                      bzrlib.merge3,
 
51
                      bzrlib.osutils,
 
52
                      bzrlib.store,
 
53
                      ]
 
54
def packages_to_test():
 
55
    import bzrlib.tests.blackbox
 
56
    return [
 
57
            bzrlib.tests.blackbox
 
58
            ]
 
59
 
 
60
 
 
61
class EarlyStoppingTestResultAdapter(object):
 
62
    """An adapter for TestResult to stop at the first first failure or error"""
 
63
 
 
64
    def __init__(self, result):
 
65
        self._result = result
 
66
 
 
67
    def addError(self, test, err):
 
68
        self._result.addError(test, err)
 
69
        self._result.stop()
 
70
 
 
71
    def addFailure(self, test, err):
 
72
        self._result.addFailure(test, err)
 
73
        self._result.stop()
 
74
 
 
75
    def __getattr__(self, name):
 
76
        return getattr(self._result, name)
 
77
 
 
78
    def __setattr__(self, name, value):
 
79
        if name == '_result':
 
80
            object.__setattr__(self, name, value)
 
81
        return setattr(self._result, name, value)
 
82
 
 
83
 
 
84
class _MyResult(unittest._TextTestResult):
 
85
    """Custom TestResult.
 
86
 
 
87
    Shows output in a different format, including displaying runtime for tests.
 
88
    """
 
89
 
 
90
    # assumes 80-column window, less 'ERROR 99999ms' = 13ch
 
91
    def _elapsedTime(self):
 
92
        return "%5dms" % (1000 * (time.time() - self._start_time))
 
93
 
 
94
    def startTest(self, test):
 
95
        unittest.TestResult.startTest(self, test)
 
96
        # In a short description, the important words are in
 
97
        # the beginning, but in an id, the important words are
 
98
        # at the end
 
99
        SHOW_DESCRIPTIONS = False
 
100
        what = SHOW_DESCRIPTIONS and test.shortDescription()
 
101
        if what:
 
102
            if len(what) > 65:
 
103
                what = what[:62] + '...'
 
104
        else:
 
105
            what = test.id()
 
106
            if what.startswith('bzrlib.tests.'):
 
107
                what = what[13:]
 
108
            if len(what) > 65:
 
109
                what = '...' + what[-62:]
 
110
        if self.showAll:
 
111
            self.stream.write('%-65.65s' % what)
 
112
        self.stream.flush()
 
113
        self._start_time = time.time()
 
114
 
 
115
    def addError(self, test, err):
 
116
        unittest.TestResult.addError(self, test, err)
 
117
        if self.showAll:
 
118
            self.stream.writeln("ERROR %s" % self._elapsedTime())
 
119
        elif self.dots:
 
120
            self.stream.write('E')
 
121
        self.stream.flush()
 
122
 
 
123
    def addFailure(self, test, err):
 
124
        unittest.TestResult.addFailure(self, test, err)
 
125
        if self.showAll:
 
126
            self.stream.writeln(" FAIL %s" % self._elapsedTime())
 
127
        elif self.dots:
 
128
            self.stream.write('F')
 
129
        self.stream.flush()
 
130
 
 
131
    def addSuccess(self, test):
 
132
        if self.showAll:
 
133
            self.stream.writeln('   OK %s' % self._elapsedTime())
 
134
        elif self.dots:
 
135
            self.stream.write('~')
 
136
        self.stream.flush()
 
137
        unittest.TestResult.addSuccess(self, test)
 
138
 
 
139
    def printErrorList(self, flavour, errors):
 
140
        for test, err in errors:
 
141
            self.stream.writeln(self.separator1)
 
142
            self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
 
143
            if hasattr(test, '_get_log'):
 
144
                self.stream.writeln()
 
145
                self.stream.writeln('log from this test:')
 
146
                print >>self.stream, test._get_log()
 
147
            self.stream.writeln(self.separator2)
 
148
            self.stream.writeln("%s" % err)
 
149
 
 
150
 
 
151
class TextTestRunner(unittest.TextTestRunner):
 
152
    stop_on_failure = False
 
153
 
 
154
    def _makeResult(self):
 
155
        result = _MyResult(self.stream, self.descriptions, self.verbosity)
 
156
        if self.stop_on_failure:
 
157
            result = EarlyStoppingTestResultAdapter(result)
 
158
        return result
 
159
 
 
160
 
 
161
def iter_suite_tests(suite):
 
162
    """Return all tests in a suite, recursing through nested suites"""
 
163
    for item in suite._tests:
 
164
        if isinstance(item, unittest.TestCase):
 
165
            yield item
 
166
        elif isinstance(item, unittest.TestSuite):
 
167
            for r in iter_suite_tests(item):
 
168
                yield r
 
169
        else:
 
170
            raise Exception('unknown object %r inside test suite %r'
 
171
                            % (item, suite))
 
172
 
 
173
 
 
174
class TestSkipped(Exception):
 
175
    """Indicates that a test was intentionally skipped, rather than failing."""
 
176
    # XXX: Not used yet
 
177
 
 
178
 
 
179
class CommandFailed(Exception):
 
180
    pass
 
181
 
 
182
class TestCase(unittest.TestCase):
 
183
    """Base class for bzr unit tests.
 
184
    
 
185
    Tests that need access to disk resources should subclass 
 
186
    TestCaseInTempDir not TestCase.
 
187
 
 
188
    Error and debug log messages are redirected from their usual
 
189
    location into a temporary file, the contents of which can be
 
190
    retrieved by _get_log().  We use a real OS file, not an in-memory object,
 
191
    so that it can also capture file IO.  When the test completes this file
 
192
    is read into memory and removed from disk.
 
193
       
 
194
    There are also convenience functions to invoke bzr's command-line
 
195
    routine, and to build and check bzr trees.
 
196
   
 
197
    In addition to the usual method of overriding tearDown(), this class also
 
198
    allows subclasses to register functions into the _cleanups list, which is
 
199
    run in order as the object is torn down.  It's less likely this will be
 
200
    accidentally overlooked.
 
201
    """
 
202
 
 
203
    BZRPATH = 'bzr'
 
204
    _log_file_name = None
 
205
    _log_contents = ''
 
206
 
 
207
    def setUp(self):
 
208
        unittest.TestCase.setUp(self)
 
209
        self._cleanups = []
 
210
        self._cleanEnvironment()
 
211
        bzrlib.trace.disable_default_logging()
 
212
        self._startLogFile()
 
213
 
 
214
    def _ndiff_strings(self, a, b):
 
215
        """Return ndiff between two strings containing lines.
 
216
        
 
217
        A trailing newline is added if missing to make the strings
 
218
        print properly."""
 
219
        if b and b[-1] != '\n':
 
220
            b += '\n'
 
221
        if a and a[-1] != '\n':
 
222
            a += '\n'
 
223
        difflines = difflib.ndiff(a.splitlines(True),
 
224
                                  b.splitlines(True),
 
225
                                  linejunk=lambda x: False,
 
226
                                  charjunk=lambda x: False)
 
227
        return ''.join(difflines)
 
228
 
 
229
    def assertEqualDiff(self, a, b):
 
230
        """Assert two texts are equal, if not raise an exception.
 
231
        
 
232
        This is intended for use with multi-line strings where it can 
 
233
        be hard to find the differences by eye.
 
234
        """
 
235
        # TODO: perhaps override assertEquals to call this for strings?
 
236
        if a == b:
 
237
            return
 
238
        raise AssertionError("texts not equal:\n" + 
 
239
                             self._ndiff_strings(a, b))      
 
240
 
 
241
    def assertContainsRe(self, haystack, needle_re):
 
242
        """Assert that a contains something matching a regular expression."""
 
243
        if not re.search(needle_re, haystack):
 
244
            raise AssertionError('pattern "%s" not found in "%s"'
 
245
                    % (needle_re, haystack))
 
246
 
 
247
    def _startLogFile(self):
 
248
        """Send bzr and test log messages to a temporary file.
 
249
 
 
250
        The file is removed as the test is torn down.
 
251
        """
 
252
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
 
253
        self._log_file = os.fdopen(fileno, 'w+')
 
254
        bzrlib.trace.enable_test_log(self._log_file)
 
255
        self._log_file_name = name
 
256
        self.addCleanup(self._finishLogFile)
 
257
 
 
258
    def _finishLogFile(self):
 
259
        """Finished with the log file.
 
260
 
 
261
        Read contents into memory, close, and delete.
 
262
        """
 
263
        bzrlib.trace.disable_test_log()
 
264
        self._log_file.seek(0)
 
265
        self._log_contents = self._log_file.read()
 
266
        self._log_file.close()
 
267
        os.remove(self._log_file_name)
 
268
        self._log_file = self._log_file_name = None
 
269
 
 
270
    def addCleanup(self, callable):
 
271
        """Arrange to run a callable when this case is torn down.
 
272
 
 
273
        Callables are run in the reverse of the order they are registered, 
 
274
        ie last-in first-out.
 
275
        """
 
276
        if callable in self._cleanups:
 
277
            raise ValueError("cleanup function %r already registered on %s" 
 
278
                    % (callable, self))
 
279
        self._cleanups.append(callable)
 
280
 
 
281
    def _cleanEnvironment(self):
 
282
        new_env = {
 
283
            'HOME': os.getcwd(),
 
284
            'APPDATA': os.getcwd(),
 
285
            'BZREMAIL': None,
 
286
            'EMAIL': None,
 
287
        }
 
288
        self.__old_env = {}
 
289
        self.addCleanup(self._restoreEnvironment)
 
290
        for name, value in new_env.iteritems():
 
291
            self._captureVar(name, value)
 
292
 
 
293
 
 
294
    def _captureVar(self, name, newvalue):
 
295
        """Set an environment variable, preparing it to be reset when finished."""
 
296
        self.__old_env[name] = os.environ.get(name, None)
 
297
        if newvalue is None:
 
298
            if name in os.environ:
 
299
                del os.environ[name]
 
300
        else:
 
301
            os.environ[name] = newvalue
 
302
 
 
303
    @staticmethod
 
304
    def _restoreVar(name, value):
 
305
        if value is None:
 
306
            if name in os.environ:
 
307
                del os.environ[name]
 
308
        else:
 
309
            os.environ[name] = value
 
310
 
 
311
    def _restoreEnvironment(self):
 
312
        for name, value in self.__old_env.iteritems():
 
313
            self._restoreVar(name, value)
 
314
 
 
315
    def tearDown(self):
 
316
        self._runCleanups()
 
317
        unittest.TestCase.tearDown(self)
 
318
 
 
319
    def _runCleanups(self):
 
320
        """Run registered cleanup functions. 
 
321
 
 
322
        This should only be called from TestCase.tearDown.
 
323
        """
 
324
        for callable in reversed(self._cleanups):
 
325
            callable()
 
326
 
 
327
    def log(self, *args):
 
328
        mutter(*args)
 
329
 
 
330
    def _get_log(self):
 
331
        """Return as a string the log for this test"""
 
332
        if self._log_file_name:
 
333
            return open(self._log_file_name).read()
 
334
        else:
 
335
            return self._log_contents
 
336
        # TODO: Delete the log after it's been read in
 
337
 
 
338
    def capture(self, cmd, retcode=0):
 
339
        """Shortcut that splits cmd into words, runs, and returns stdout"""
 
340
        return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
 
341
 
 
342
    def run_bzr_captured(self, argv, retcode=0):
 
343
        """Invoke bzr and return (stdout, stderr).
 
344
 
 
345
        Useful for code that wants to check the contents of the
 
346
        output, the way error messages are presented, etc.
 
347
 
 
348
        This should be the main method for tests that want to exercise the
 
349
        overall behavior of the bzr application (rather than a unit test
 
350
        or a functional test of the library.)
 
351
 
 
352
        Much of the old code runs bzr by forking a new copy of Python, but
 
353
        that is slower, harder to debug, and generally not necessary.
 
354
 
 
355
        This runs bzr through the interface that catches and reports
 
356
        errors, and with logging set to something approximating the
 
357
        default, so that error reporting can be checked.
 
358
 
 
359
        argv -- arguments to invoke bzr
 
360
        retcode -- expected return code, or None for don't-care.
 
361
        """
 
362
        stdout = StringIO()
 
363
        stderr = StringIO()
 
364
        self.log('run bzr: %s', ' '.join(argv))
 
365
        # FIXME: don't call into logging here
 
366
        handler = logging.StreamHandler(stderr)
 
367
        handler.setFormatter(bzrlib.trace.QuietFormatter())
 
368
        handler.setLevel(logging.INFO)
 
369
        logger = logging.getLogger('')
 
370
        logger.addHandler(handler)
 
371
        try:
 
372
            result = self.apply_redirected(None, stdout, stderr,
 
373
                                           bzrlib.commands.run_bzr_catch_errors,
 
374
                                           argv)
 
375
        finally:
 
376
            logger.removeHandler(handler)
 
377
        out = stdout.getvalue()
 
378
        err = stderr.getvalue()
 
379
        if out:
 
380
            self.log('output:\n%s', out)
 
381
        if err:
 
382
            self.log('errors:\n%s', err)
 
383
        if retcode is not None:
 
384
            self.assertEquals(result, retcode)
 
385
        return out, err
 
386
 
 
387
    def run_bzr(self, *args, **kwargs):
 
388
        """Invoke bzr, as if it were run from the command line.
 
389
 
 
390
        This should be the main method for tests that want to exercise the
 
391
        overall behavior of the bzr application (rather than a unit test
 
392
        or a functional test of the library.)
 
393
 
 
394
        This sends the stdout/stderr results into the test's log,
 
395
        where it may be useful for debugging.  See also run_captured.
 
396
        """
 
397
        retcode = kwargs.pop('retcode', 0)
 
398
        return self.run_bzr_captured(args, retcode)
 
399
 
 
400
    def check_inventory_shape(self, inv, shape):
 
401
        """Compare an inventory to a list of expected names.
 
402
 
 
403
        Fail if they are not precisely equal.
 
404
        """
 
405
        extras = []
 
406
        shape = list(shape)             # copy
 
407
        for path, ie in inv.entries():
 
408
            name = path.replace('\\', '/')
 
409
            if ie.kind == 'dir':
 
410
                name = name + '/'
 
411
            if name in shape:
 
412
                shape.remove(name)
 
413
            else:
 
414
                extras.append(name)
 
415
        if shape:
 
416
            self.fail("expected paths not found in inventory: %r" % shape)
 
417
        if extras:
 
418
            self.fail("unexpected paths found in inventory: %r" % extras)
 
419
 
 
420
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
 
421
                         a_callable=None, *args, **kwargs):
 
422
        """Call callable with redirected std io pipes.
 
423
 
 
424
        Returns the return code."""
 
425
        if not callable(a_callable):
 
426
            raise ValueError("a_callable must be callable.")
 
427
        if stdin is None:
 
428
            stdin = StringIO("")
 
429
        if stdout is None:
 
430
            if hasattr(self, "_log_file"):
 
431
                stdout = self._log_file
 
432
            else:
 
433
                stdout = StringIO()
 
434
        if stderr is None:
 
435
            if hasattr(self, "_log_file"):
 
436
                stderr = self._log_file
 
437
            else:
 
438
                stderr = StringIO()
 
439
        real_stdin = sys.stdin
 
440
        real_stdout = sys.stdout
 
441
        real_stderr = sys.stderr
 
442
        try:
 
443
            sys.stdout = stdout
 
444
            sys.stderr = stderr
 
445
            sys.stdin = stdin
 
446
            return a_callable(*args, **kwargs)
 
447
        finally:
 
448
            sys.stdout = real_stdout
 
449
            sys.stderr = real_stderr
 
450
            sys.stdin = real_stdin
 
451
 
 
452
 
 
453
BzrTestBase = TestCase
 
454
 
 
455
     
 
456
class TestCaseInTempDir(TestCase):
 
457
    """Derived class that runs a test within a temporary directory.
 
458
 
 
459
    This is useful for tests that need to create a branch, etc.
 
460
 
 
461
    The directory is created in a slightly complex way: for each
 
462
    Python invocation, a new temporary top-level directory is created.
 
463
    All test cases create their own directory within that.  If the
 
464
    tests complete successfully, the directory is removed.
 
465
 
 
466
    InTempDir is an old alias for FunctionalTestCase.
 
467
    """
 
468
 
 
469
    TEST_ROOT = None
 
470
    _TEST_NAME = 'test'
 
471
    OVERRIDE_PYTHON = 'python'
 
472
 
 
473
    def check_file_contents(self, filename, expect):
 
474
        self.log("check contents of file %s" % filename)
 
475
        contents = file(filename, 'r').read()
 
476
        if contents != expect:
 
477
            self.log("expected: %r" % expect)
 
478
            self.log("actually: %r" % contents)
 
479
            self.fail("contents of %s not as expected" % filename)
 
480
 
 
481
    def _make_test_root(self):
 
482
        if TestCaseInTempDir.TEST_ROOT is not None:
 
483
            return
 
484
        i = 0
 
485
        while True:
 
486
            root = u'test%04d.tmp' % i
 
487
            try:
 
488
                os.mkdir(root)
 
489
            except OSError, e:
 
490
                if e.errno == errno.EEXIST:
 
491
                    i += 1
 
492
                    continue
 
493
                else:
 
494
                    raise
 
495
            # successfully created
 
496
            TestCaseInTempDir.TEST_ROOT = os.path.abspath(root)
 
497
            break
 
498
        # make a fake bzr directory there to prevent any tests propagating
 
499
        # up onto the source directory's real branch
 
500
        os.mkdir(os.path.join(TestCaseInTempDir.TEST_ROOT, '.bzr'))
 
501
 
 
502
    def setUp(self):
 
503
        super(TestCaseInTempDir, self).setUp()
 
504
        self._make_test_root()
 
505
        _currentdir = os.getcwdu()
 
506
        short_id = self.id().replace('bzrlib.tests.', '') \
 
507
                   .replace('__main__.', '')
 
508
        self.test_dir = os.path.join(self.TEST_ROOT, short_id)
 
509
        os.mkdir(self.test_dir)
 
510
        os.chdir(self.test_dir)
 
511
        os.environ['HOME'] = self.test_dir
 
512
        def _leaveDirectory():
 
513
            os.chdir(_currentdir)
 
514
        self.addCleanup(_leaveDirectory)
 
515
        
 
516
    def build_tree(self, shape, line_endings='native'):
 
517
        """Build a test tree according to a pattern.
 
518
 
 
519
        shape is a sequence of file specifications.  If the final
 
520
        character is '/', a directory is created.
 
521
 
 
522
        This doesn't add anything to a branch.
 
523
        :param line_endings: Either 'binary' or 'native'
 
524
                             in binary mode, exact contents are written
 
525
                             in native mode, the line endings match the
 
526
                             default platform endings.
 
527
        """
 
528
        # XXX: It's OK to just create them using forward slashes on windows?
 
529
        for name in shape:
 
530
            self.assert_(isinstance(name, basestring))
 
531
            if name[-1] == '/':
 
532
                os.mkdir(name[:-1])
 
533
            else:
 
534
                if line_endings == 'binary':
 
535
                    f = file(name, 'wb')
 
536
                elif line_endings == 'native':
 
537
                    f = file(name, 'wt')
 
538
                else:
 
539
                    raise BzrError('Invalid line ending request %r' % (line_endings,))
 
540
                print >>f, "contents of", name
 
541
                f.close()
 
542
 
 
543
    def build_tree_contents(self, shape):
 
544
        build_tree_contents(shape)
 
545
 
 
546
    def failUnlessExists(self, path):
 
547
        """Fail unless path, which may be abs or relative, exists."""
 
548
        self.failUnless(osutils.lexists(path))
 
549
        
 
550
    def assertFileEqual(self, content, path):
 
551
        """Fail if path does not contain 'content'."""
 
552
        self.failUnless(osutils.lexists(path))
 
553
        self.assertEqualDiff(content, open(path, 'r').read())
 
554
        
 
555
 
 
556
class MetaTestLog(TestCase):
 
557
    def test_logging(self):
 
558
        """Test logs are captured when a test fails."""
 
559
        self.log('a test message')
 
560
        self._log_file.flush()
 
561
        self.assertContainsRe(self._get_log(), 'a test message\n')
 
562
 
 
563
 
 
564
def filter_suite_by_re(suite, pattern):
 
565
    result = TestUtil.TestSuite()
 
566
    filter_re = re.compile(pattern)
 
567
    for test in iter_suite_tests(suite):
 
568
        if filter_re.search(test.id()):
 
569
            result.addTest(test)
 
570
    return result
 
571
 
 
572
 
 
573
def run_suite(suite, name='test', verbose=False, pattern=".*",
 
574
              stop_on_failure=False, keep_output=False):
 
575
    TestCaseInTempDir._TEST_NAME = name
 
576
    if verbose:
 
577
        verbosity = 2
 
578
    else:
 
579
        verbosity = 1
 
580
    runner = TextTestRunner(stream=sys.stdout,
 
581
                            descriptions=0,
 
582
                            verbosity=verbosity)
 
583
    runner.stop_on_failure=stop_on_failure
 
584
    if pattern != '.*':
 
585
        suite = filter_suite_by_re(suite, pattern)
 
586
    result = runner.run(suite)
 
587
    # This is still a little bogus, 
 
588
    # but only a little. Folk not using our testrunner will
 
589
    # have to delete their temp directories themselves.
 
590
    if result.wasSuccessful() or not keep_output:
 
591
        if TestCaseInTempDir.TEST_ROOT is not None:
 
592
            shutil.rmtree(TestCaseInTempDir.TEST_ROOT) 
 
593
    else:
 
594
        print "Failed tests working directories are in '%s'\n" % TestCaseInTempDir.TEST_ROOT
 
595
    return result.wasSuccessful()
 
596
 
 
597
 
 
598
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
 
599
             keep_output=False):
 
600
    """Run the whole test suite under the enhanced runner"""
 
601
    return run_suite(test_suite(), 'testbzr', verbose=verbose, pattern=pattern,
 
602
                     stop_on_failure=stop_on_failure, keep_output=keep_output)
 
603
 
 
604
 
 
605
def test_suite():
 
606
    """Build and return TestSuite for the whole program."""
 
607
    from doctest import DocTestSuite
 
608
 
 
609
    global MODULES_TO_DOCTEST
 
610
 
 
611
    # FIXME: If these fail to load, e.g. because of a syntax error, the
 
612
    # exception is hidden by unittest.  Sucks.  Should either fix that or
 
613
    # perhaps import them and pass them to unittest as modules.
 
614
    testmod_names = \
 
615
                  ['bzrlib.tests.MetaTestLog',
 
616
                   'bzrlib.tests.test_api',
 
617
                   'bzrlib.tests.test_basicio',
 
618
                   'bzrlib.tests.test_gpg',
 
619
                   'bzrlib.tests.test_identitymap',
 
620
                   'bzrlib.tests.test_inv',
 
621
                   'bzrlib.tests.test_ancestry',
 
622
                   'bzrlib.tests.test_commit',
 
623
                   'bzrlib.tests.test_command',
 
624
                   'bzrlib.tests.test_commit_merge',
 
625
                   'bzrlib.tests.test_config',
 
626
                   'bzrlib.tests.test_merge3',
 
627
                   'bzrlib.tests.test_merge',
 
628
                   'bzrlib.tests.test_hashcache',
 
629
                   'bzrlib.tests.test_status',
 
630
                   'bzrlib.tests.test_log',
 
631
                   'bzrlib.tests.test_revisionnamespaces',
 
632
                   'bzrlib.tests.test_branch',
 
633
                   'bzrlib.tests.test_revision',
 
634
                   'bzrlib.tests.test_revision_info',
 
635
                   'bzrlib.tests.test_merge_core',
 
636
                   'bzrlib.tests.test_smart_add',
 
637
                   'bzrlib.tests.test_bad_files',
 
638
                   'bzrlib.tests.test_diff',
 
639
                   'bzrlib.tests.test_parent',
 
640
                   'bzrlib.tests.test_xml',
 
641
                   'bzrlib.tests.test_weave',
 
642
                   'bzrlib.tests.test_fetch',
 
643
                   'bzrlib.tests.test_whitebox',
 
644
                   'bzrlib.tests.test_store',
 
645
                   'bzrlib.tests.test_sampler',
 
646
                   'bzrlib.tests.test_transactions',
 
647
                   'bzrlib.tests.test_transport',
 
648
                   'bzrlib.tests.test_sftp',
 
649
                   'bzrlib.tests.test_graph',
 
650
                   'bzrlib.tests.test_workingtree',
 
651
                   'bzrlib.tests.test_upgrade',
 
652
                   'bzrlib.tests.test_uncommit',
 
653
                   'bzrlib.tests.test_conflicts',
 
654
                   'bzrlib.tests.test_testament',
 
655
                   'bzrlib.tests.test_annotate',
 
656
                   'bzrlib.tests.test_revprops',
 
657
                   'bzrlib.tests.test_options',
 
658
                   'bzrlib.tests.test_http',
 
659
                   'bzrlib.tests.test_nonascii',
 
660
                   'bzrlib.tests.test_plugins',
 
661
                   'bzrlib.tests.test_reweave',
 
662
                   'bzrlib.tests.test_tsort',
 
663
                   'bzrlib.tests.test_trace',
 
664
                   ]
 
665
 
 
666
    TestCase.BZRPATH = os.path.join(os.path.realpath(os.path.dirname(bzrlib.__path__[0])), 'bzr')
 
667
    print '%-30s %s' % ('bzr binary', TestCase.BZRPATH)
 
668
    print
 
669
    suite = TestSuite()
 
670
    suite.addTest(TestLoader().loadTestsFromNames(testmod_names))
 
671
    for package in packages_to_test():
 
672
        suite.addTest(package.test_suite())
 
673
    for m in MODULES_TO_TEST:
 
674
        suite.addTest(TestLoader().loadTestsFromModule(m))
 
675
    for m in (MODULES_TO_DOCTEST):
 
676
        suite.addTest(DocTestSuite(m))
 
677
    for name, plugin in bzrlib.plugin.all_plugins().items():
 
678
        if hasattr(plugin, 'test_suite'):
 
679
            suite.addTest(plugin.test_suite())
 
680
    return suite
 
681