/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: 2006-05-16 05:16:22 UTC
  • mto: (1713.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 1714.
  • Revision ID: robertc@robertcollins.net-20060516051622-807a8bbda673f4ee
'bzr selftest --benchmark' will run a new benchmarking selftest.
(Robert Collins, Martin Pool).

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 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
# 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)
 
23
 
 
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.
 
28
 
 
29
import codecs
 
30
from cStringIO import StringIO
 
31
import difflib
 
32
import errno
 
33
import logging
 
34
import os
 
35
import re
 
36
import stat
 
37
import sys
 
38
import tempfile
 
39
import unittest
 
40
import time
 
41
 
 
42
 
 
43
import bzrlib.branch
 
44
import bzrlib.bzrdir as bzrdir
 
45
import bzrlib.commands
 
46
import bzrlib.errors as errors
 
47
import bzrlib.inventory
 
48
import bzrlib.iterablefile
 
49
import bzrlib.lockdir
 
50
from bzrlib.merge import merge_inner
 
51
import bzrlib.merge3
 
52
import bzrlib.osutils
 
53
import bzrlib.osutils as osutils
 
54
import bzrlib.plugin
 
55
import bzrlib.progress as progress
 
56
from bzrlib.revision import common_ancestor
 
57
import bzrlib.store
 
58
import bzrlib.trace
 
59
from bzrlib.transport import urlescape, get_transport
 
60
import bzrlib.transport
 
61
from bzrlib.transport.local import LocalRelpathServer
 
62
from bzrlib.transport.readonly import ReadonlyServer
 
63
from bzrlib.trace import mutter
 
64
from bzrlib.tests.TestUtil import TestLoader, TestSuite
 
65
from bzrlib.tests.treeshape import build_tree_contents
 
66
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
 
67
 
 
68
default_transport = LocalRelpathServer
 
69
 
 
70
MODULES_TO_TEST = []
 
71
MODULES_TO_DOCTEST = [
 
72
                      bzrlib.branch,
 
73
                      bzrlib.commands,
 
74
                      bzrlib.errors,
 
75
                      bzrlib.inventory,
 
76
                      bzrlib.iterablefile,
 
77
                      bzrlib.lockdir,
 
78
                      bzrlib.merge3,
 
79
                      bzrlib.option,
 
80
                      bzrlib.osutils,
 
81
                      bzrlib.store
 
82
                      ]
 
83
def packages_to_test():
 
84
    """Return a list of packages to test.
 
85
 
 
86
    The packages are not globally imported so that import failures are
 
87
    triggered when running selftest, not when importing the command.
 
88
    """
 
89
    import bzrlib.doc
 
90
    import bzrlib.tests.blackbox
 
91
    import bzrlib.tests.branch_implementations
 
92
    import bzrlib.tests.bzrdir_implementations
 
93
    import bzrlib.tests.interrepository_implementations
 
94
    import bzrlib.tests.interversionedfile_implementations
 
95
    import bzrlib.tests.repository_implementations
 
96
    import bzrlib.tests.revisionstore_implementations
 
97
    import bzrlib.tests.workingtree_implementations
 
98
    return [
 
99
            bzrlib.doc,
 
100
            bzrlib.tests.blackbox,
 
101
            bzrlib.tests.branch_implementations,
 
102
            bzrlib.tests.bzrdir_implementations,
 
103
            bzrlib.tests.interrepository_implementations,
 
104
            bzrlib.tests.interversionedfile_implementations,
 
105
            bzrlib.tests.repository_implementations,
 
106
            bzrlib.tests.revisionstore_implementations,
 
107
            bzrlib.tests.workingtree_implementations,
 
108
            ]
 
109
 
 
110
 
 
111
class _MyResult(unittest._TextTestResult):
 
112
    """Custom TestResult.
 
113
 
 
114
    Shows output in a different format, including displaying runtime for tests.
 
115
    """
 
116
    stop_early = False
 
117
    
 
118
    def __init__(self, stream, descriptions, verbosity, pb=None):
 
119
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
 
120
        self.pb = pb
 
121
 
 
122
    def _elapsedTime(self):
 
123
        return "%5dms" % (1000 * (time.time() - self._start_time))
 
124
 
 
125
    def _ellipsise_unimportant_words(self, a_string, final_width,
 
126
                                   keep_start=False):
 
127
        """Add ellipsese (sp?) for overly long strings.
 
128
        
 
129
        :param keep_start: If true preserve the start of a_string rather
 
130
                           than the end of it.
 
131
        """
 
132
        if keep_start:
 
133
            if len(a_string) > final_width:
 
134
                result = a_string[:final_width-3] + '...'
 
135
            else:
 
136
                result = a_string
 
137
        else:
 
138
            if len(a_string) > final_width:
 
139
                result = '...' + a_string[3-final_width:]
 
140
            else:
 
141
                result = a_string
 
142
        return result.ljust(final_width)
 
143
 
 
144
    def startTest(self, test):
 
145
        unittest.TestResult.startTest(self, test)
 
146
        # In a short description, the important words are in
 
147
        # the beginning, but in an id, the important words are
 
148
        # at the end
 
149
        SHOW_DESCRIPTIONS = False
 
150
 
 
151
        if not self.showAll and self.dots and self.pb is not None:
 
152
            final_width = 13
 
153
        else:
 
154
            final_width = osutils.terminal_width()
 
155
            final_width = final_width - 15
 
156
        what = None
 
157
        if SHOW_DESCRIPTIONS:
 
158
            what = test.shortDescription()
 
159
            if what:
 
160
                what = self._ellipsise_unimportant_words(what, final_width, keep_start=True)
 
161
        if what is None:
 
162
            what = test.id()
 
163
            if what.startswith('bzrlib.tests.'):
 
164
                what = what[13:]
 
165
            what = self._ellipsise_unimportant_words(what, final_width)
 
166
        if self.showAll:
 
167
            self.stream.write(what)
 
168
        elif self.dots and self.pb is not None:
 
169
            self.pb.update(what, self.testsRun - 1, None)
 
170
        self.stream.flush()
 
171
        self._start_time = time.time()
 
172
 
 
173
    def addError(self, test, err):
 
174
        if isinstance(err[1], TestSkipped):
 
175
            return self.addSkipped(test, err)    
 
176
        unittest.TestResult.addError(self, test, err)
 
177
        if self.showAll:
 
178
            self.stream.writeln("ERROR %s" % self._elapsedTime())
 
179
        elif self.dots and self.pb is None:
 
180
            self.stream.write('E')
 
181
        elif self.dots:
 
182
            self.pb.update(self._ellipsise_unimportant_words('ERROR', 13), self.testsRun, None)
 
183
        self.stream.flush()
 
184
        if self.stop_early:
 
185
            self.stop()
 
186
 
 
187
    def addFailure(self, test, err):
 
188
        unittest.TestResult.addFailure(self, test, err)
 
189
        if self.showAll:
 
190
            self.stream.writeln(" FAIL %s" % self._elapsedTime())
 
191
        elif self.dots and self.pb is None:
 
192
            self.stream.write('F')
 
193
        elif self.dots:
 
194
            self.pb.update(self._ellipsise_unimportant_words('FAIL', 13), self.testsRun, None)
 
195
        self.stream.flush()
 
196
        if self.stop_early:
 
197
            self.stop()
 
198
 
 
199
    def addSuccess(self, test):
 
200
        if self.showAll:
 
201
            self.stream.writeln('   OK %s' % self._elapsedTime())
 
202
        elif self.dots and self.pb is None:
 
203
            self.stream.write('~')
 
204
        elif self.dots:
 
205
            self.pb.update(self._ellipsise_unimportant_words('OK', 13), self.testsRun, None)
 
206
        self.stream.flush()
 
207
        unittest.TestResult.addSuccess(self, test)
 
208
 
 
209
    def addSkipped(self, test, skip_excinfo):
 
210
        if self.showAll:
 
211
            print >>self.stream, ' SKIP %s' % self._elapsedTime()
 
212
            print >>self.stream, '     %s' % skip_excinfo[1]
 
213
        elif self.dots and self.pb is None:
 
214
            self.stream.write('S')
 
215
        elif self.dots:
 
216
            self.pb.update(self._ellipsise_unimportant_words('SKIP', 13), self.testsRun, None)
 
217
        self.stream.flush()
 
218
        # seems best to treat this as success from point-of-view of unittest
 
219
        # -- it actually does nothing so it barely matters :)
 
220
        unittest.TestResult.addSuccess(self, test)
 
221
 
 
222
    def printErrorList(self, flavour, errors):
 
223
        for test, err in errors:
 
224
            self.stream.writeln(self.separator1)
 
225
            self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
 
226
            if getattr(test, '_get_log', None) is not None:
 
227
                print >>self.stream
 
228
                print >>self.stream, \
 
229
                        ('vvvv[log from %s]' % test.id()).ljust(78,'-')
 
230
                print >>self.stream, test._get_log()
 
231
                print >>self.stream, \
 
232
                        ('^^^^[log from %s]' % test.id()).ljust(78,'-')
 
233
            self.stream.writeln(self.separator2)
 
234
            self.stream.writeln("%s" % err)
 
235
 
 
236
 
 
237
class TextTestRunner(object):
 
238
    stop_on_failure = False
 
239
 
 
240
    def __init__(self,
 
241
                 stream=sys.stderr,
 
242
                 descriptions=0,
 
243
                 verbosity=1,
 
244
                 keep_output=False,
 
245
                 pb=None):
 
246
        self.stream = unittest._WritelnDecorator(stream)
 
247
        self.descriptions = descriptions
 
248
        self.verbosity = verbosity
 
249
        self.keep_output = keep_output
 
250
        self.pb = pb
 
251
 
 
252
    def _makeResult(self):
 
253
        result = _MyResult(self.stream,
 
254
                           self.descriptions,
 
255
                           self.verbosity,
 
256
                           pb=self.pb)
 
257
        result.stop_early = self.stop_on_failure
 
258
        return result
 
259
 
 
260
    def run(self, test):
 
261
        "Run the given test case or test suite."
 
262
        result = self._makeResult()
 
263
        startTime = time.time()
 
264
        if self.pb is not None:
 
265
            self.pb.update('Running tests', 0, test.countTestCases())
 
266
        test.run(result)
 
267
        stopTime = time.time()
 
268
        timeTaken = stopTime - startTime
 
269
        result.printErrors()
 
270
        self.stream.writeln(result.separator2)
 
271
        run = result.testsRun
 
272
        self.stream.writeln("Ran %d test%s in %.3fs" %
 
273
                            (run, run != 1 and "s" or "", timeTaken))
 
274
        self.stream.writeln()
 
275
        if not result.wasSuccessful():
 
276
            self.stream.write("FAILED (")
 
277
            failed, errored = map(len, (result.failures, result.errors))
 
278
            if failed:
 
279
                self.stream.write("failures=%d" % failed)
 
280
            if errored:
 
281
                if failed: self.stream.write(", ")
 
282
                self.stream.write("errors=%d" % errored)
 
283
            self.stream.writeln(")")
 
284
        else:
 
285
            self.stream.writeln("OK")
 
286
        if self.pb is not None:
 
287
            self.pb.update('Cleaning up', 0, 1)
 
288
        # This is still a little bogus, 
 
289
        # but only a little. Folk not using our testrunner will
 
290
        # have to delete their temp directories themselves.
 
291
        test_root = TestCaseInTempDir.TEST_ROOT
 
292
        if result.wasSuccessful() or not self.keep_output:
 
293
            if test_root is not None:
 
294
                    osutils.rmtree(test_root)
 
295
        else:
 
296
            if self.pb is not None:
 
297
                self.pb.note("Failed tests working directories are in '%s'\n",
 
298
                             test_root)
 
299
            else:
 
300
                self.stream.writeln(
 
301
                    "Failed tests working directories are in '%s'\n" %
 
302
                    test_root)
 
303
        TestCaseInTempDir.TEST_ROOT = None
 
304
        if self.pb is not None:
 
305
            self.pb.clear()
 
306
        return result
 
307
 
 
308
 
 
309
def iter_suite_tests(suite):
 
310
    """Return all tests in a suite, recursing through nested suites"""
 
311
    for item in suite._tests:
 
312
        if isinstance(item, unittest.TestCase):
 
313
            yield item
 
314
        elif isinstance(item, unittest.TestSuite):
 
315
            for r in iter_suite_tests(item):
 
316
                yield r
 
317
        else:
 
318
            raise Exception('unknown object %r inside test suite %r'
 
319
                            % (item, suite))
 
320
 
 
321
 
 
322
class TestSkipped(Exception):
 
323
    """Indicates that a test was intentionally skipped, rather than failing."""
 
324
    # XXX: Not used yet
 
325
 
 
326
 
 
327
class CommandFailed(Exception):
 
328
    pass
 
329
 
 
330
class TestCase(unittest.TestCase):
 
331
    """Base class for bzr unit tests.
 
332
    
 
333
    Tests that need access to disk resources should subclass 
 
334
    TestCaseInTempDir not TestCase.
 
335
 
 
336
    Error and debug log messages are redirected from their usual
 
337
    location into a temporary file, the contents of which can be
 
338
    retrieved by _get_log().  We use a real OS file, not an in-memory object,
 
339
    so that it can also capture file IO.  When the test completes this file
 
340
    is read into memory and removed from disk.
 
341
       
 
342
    There are also convenience functions to invoke bzr's command-line
 
343
    routine, and to build and check bzr trees.
 
344
   
 
345
    In addition to the usual method of overriding tearDown(), this class also
 
346
    allows subclasses to register functions into the _cleanups list, which is
 
347
    run in order as the object is torn down.  It's less likely this will be
 
348
    accidentally overlooked.
 
349
    """
 
350
 
 
351
    _log_file_name = None
 
352
    _log_contents = ''
 
353
 
 
354
    def __init__(self, methodName='testMethod'):
 
355
        super(TestCase, self).__init__(methodName)
 
356
        self._cleanups = []
 
357
 
 
358
    def setUp(self):
 
359
        unittest.TestCase.setUp(self)
 
360
        self._cleanEnvironment()
 
361
        bzrlib.trace.disable_default_logging()
 
362
        self._startLogFile()
 
363
 
 
364
    def _ndiff_strings(self, a, b):
 
365
        """Return ndiff between two strings containing lines.
 
366
        
 
367
        A trailing newline is added if missing to make the strings
 
368
        print properly."""
 
369
        if b and b[-1] != '\n':
 
370
            b += '\n'
 
371
        if a and a[-1] != '\n':
 
372
            a += '\n'
 
373
        difflines = difflib.ndiff(a.splitlines(True),
 
374
                                  b.splitlines(True),
 
375
                                  linejunk=lambda x: False,
 
376
                                  charjunk=lambda x: False)
 
377
        return ''.join(difflines)
 
378
 
 
379
    def assertEqualDiff(self, a, b, message=None):
 
380
        """Assert two texts are equal, if not raise an exception.
 
381
        
 
382
        This is intended for use with multi-line strings where it can 
 
383
        be hard to find the differences by eye.
 
384
        """
 
385
        # TODO: perhaps override assertEquals to call this for strings?
 
386
        if a == b:
 
387
            return
 
388
        if message is None:
 
389
            message = "texts not equal:\n"
 
390
        raise AssertionError(message + 
 
391
                             self._ndiff_strings(a, b))      
 
392
        
 
393
    def assertEqualMode(self, mode, mode_test):
 
394
        self.assertEqual(mode, mode_test,
 
395
                         'mode mismatch %o != %o' % (mode, mode_test))
 
396
 
 
397
    def assertStartsWith(self, s, prefix):
 
398
        if not s.startswith(prefix):
 
399
            raise AssertionError('string %r does not start with %r' % (s, prefix))
 
400
 
 
401
    def assertEndsWith(self, s, suffix):
 
402
        """Asserts that s ends with suffix."""
 
403
        if not s.endswith(suffix):
 
404
            raise AssertionError('string %r does not end with %r' % (s, suffix))
 
405
 
 
406
    def assertContainsRe(self, haystack, needle_re):
 
407
        """Assert that a contains something matching a regular expression."""
 
408
        if not re.search(needle_re, haystack):
 
409
            raise AssertionError('pattern "%s" not found in "%s"'
 
410
                    % (needle_re, haystack))
 
411
 
 
412
    def assertSubset(self, sublist, superlist):
 
413
        """Assert that every entry in sublist is present in superlist."""
 
414
        missing = []
 
415
        for entry in sublist:
 
416
            if entry not in superlist:
 
417
                missing.append(entry)
 
418
        if len(missing) > 0:
 
419
            raise AssertionError("value(s) %r not present in container %r" % 
 
420
                                 (missing, superlist))
 
421
 
 
422
    def assertIs(self, left, right):
 
423
        if not (left is right):
 
424
            raise AssertionError("%r is not %r." % (left, right))
 
425
 
 
426
    def assertTransportMode(self, transport, path, mode):
 
427
        """Fail if a path does not have mode mode.
 
428
        
 
429
        If modes are not supported on this transport, the assertion is ignored.
 
430
        """
 
431
        if not transport._can_roundtrip_unix_modebits():
 
432
            return
 
433
        path_stat = transport.stat(path)
 
434
        actual_mode = stat.S_IMODE(path_stat.st_mode)
 
435
        self.assertEqual(mode, actual_mode,
 
436
            'mode of %r incorrect (%o != %o)' % (path, mode, actual_mode))
 
437
 
 
438
    def assertIsInstance(self, obj, kls):
 
439
        """Fail if obj is not an instance of kls"""
 
440
        if not isinstance(obj, kls):
 
441
            self.fail("%r is an instance of %s rather than %s" % (
 
442
                obj, obj.__class__, kls))
 
443
 
 
444
    def _startLogFile(self):
 
445
        """Send bzr and test log messages to a temporary file.
 
446
 
 
447
        The file is removed as the test is torn down.
 
448
        """
 
449
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
 
450
        encoder, decoder, stream_reader, stream_writer = codecs.lookup('UTF-8')
 
451
        self._log_file = stream_writer(os.fdopen(fileno, 'w+'))
 
452
        self._log_nonce = bzrlib.trace.enable_test_log(self._log_file)
 
453
        self._log_file_name = name
 
454
        self.addCleanup(self._finishLogFile)
 
455
 
 
456
    def _finishLogFile(self):
 
457
        """Finished with the log file.
 
458
 
 
459
        Read contents into memory, close, and delete.
 
460
        """
 
461
        bzrlib.trace.disable_test_log(self._log_nonce)
 
462
        self._log_file.seek(0)
 
463
        self._log_contents = self._log_file.read()
 
464
        self._log_file.close()
 
465
        os.remove(self._log_file_name)
 
466
        self._log_file = self._log_file_name = None
 
467
 
 
468
    def addCleanup(self, callable):
 
469
        """Arrange to run a callable when this case is torn down.
 
470
 
 
471
        Callables are run in the reverse of the order they are registered, 
 
472
        ie last-in first-out.
 
473
        """
 
474
        if callable in self._cleanups:
 
475
            raise ValueError("cleanup function %r already registered on %s" 
 
476
                    % (callable, self))
 
477
        self._cleanups.append(callable)
 
478
 
 
479
    def _cleanEnvironment(self):
 
480
        new_env = {
 
481
            'HOME': os.getcwd(),
 
482
            'APPDATA': os.getcwd(),
 
483
            'BZREMAIL': None,
 
484
            'EMAIL': None,
 
485
        }
 
486
        self.__old_env = {}
 
487
        self.addCleanup(self._restoreEnvironment)
 
488
        for name, value in new_env.iteritems():
 
489
            self._captureVar(name, value)
 
490
 
 
491
 
 
492
    def _captureVar(self, name, newvalue):
 
493
        """Set an environment variable, preparing it to be reset when finished."""
 
494
        self.__old_env[name] = os.environ.get(name, None)
 
495
        if newvalue is None:
 
496
            if name in os.environ:
 
497
                del os.environ[name]
 
498
        else:
 
499
            os.environ[name] = newvalue
 
500
 
 
501
    @staticmethod
 
502
    def _restoreVar(name, value):
 
503
        if value is None:
 
504
            if name in os.environ:
 
505
                del os.environ[name]
 
506
        else:
 
507
            os.environ[name] = value
 
508
 
 
509
    def _restoreEnvironment(self):
 
510
        for name, value in self.__old_env.iteritems():
 
511
            self._restoreVar(name, value)
 
512
 
 
513
    def tearDown(self):
 
514
        self._runCleanups()
 
515
        unittest.TestCase.tearDown(self)
 
516
 
 
517
    def _runCleanups(self):
 
518
        """Run registered cleanup functions. 
 
519
 
 
520
        This should only be called from TestCase.tearDown.
 
521
        """
 
522
        # TODO: Perhaps this should keep running cleanups even if 
 
523
        # one of them fails?
 
524
        for cleanup_fn in reversed(self._cleanups):
 
525
            cleanup_fn()
 
526
 
 
527
    def log(self, *args):
 
528
        mutter(*args)
 
529
 
 
530
    def _get_log(self):
 
531
        """Return as a string the log for this test"""
 
532
        if self._log_file_name:
 
533
            return open(self._log_file_name).read()
 
534
        else:
 
535
            return self._log_contents
 
536
        # TODO: Delete the log after it's been read in
 
537
 
 
538
    def capture(self, cmd, retcode=0):
 
539
        """Shortcut that splits cmd into words, runs, and returns stdout"""
 
540
        return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
 
541
 
 
542
    def run_bzr_captured(self, argv, retcode=0, stdin=None):
 
543
        """Invoke bzr and return (stdout, stderr).
 
544
 
 
545
        Useful for code that wants to check the contents of the
 
546
        output, the way error messages are presented, etc.
 
547
 
 
548
        This should be the main method for tests that want to exercise the
 
549
        overall behavior of the bzr application (rather than a unit test
 
550
        or a functional test of the library.)
 
551
 
 
552
        Much of the old code runs bzr by forking a new copy of Python, but
 
553
        that is slower, harder to debug, and generally not necessary.
 
554
 
 
555
        This runs bzr through the interface that catches and reports
 
556
        errors, and with logging set to something approximating the
 
557
        default, so that error reporting can be checked.
 
558
 
 
559
        argv -- arguments to invoke bzr
 
560
        retcode -- expected return code, or None for don't-care.
 
561
        :param stdin: A string to be used as stdin for the command.
 
562
        """
 
563
        if stdin is not None:
 
564
            stdin = StringIO(stdin)
 
565
        stdout = StringIO()
 
566
        stderr = StringIO()
 
567
        self.log('run bzr: %s', ' '.join(argv))
 
568
        # FIXME: don't call into logging here
 
569
        handler = logging.StreamHandler(stderr)
 
570
        handler.setFormatter(bzrlib.trace.QuietFormatter())
 
571
        handler.setLevel(logging.INFO)
 
572
        logger = logging.getLogger('')
 
573
        logger.addHandler(handler)
 
574
        old_ui_factory = bzrlib.ui.ui_factory
 
575
        bzrlib.ui.ui_factory = bzrlib.tests.blackbox.TestUIFactory(
 
576
            stdout=stdout,
 
577
            stderr=stderr)
 
578
        bzrlib.ui.ui_factory.stdin = stdin
 
579
        try:
 
580
            result = self.apply_redirected(stdin, stdout, stderr,
 
581
                                           bzrlib.commands.run_bzr_catch_errors,
 
582
                                           argv)
 
583
        finally:
 
584
            logger.removeHandler(handler)
 
585
            bzrlib.ui.ui_factory = old_ui_factory
 
586
        out = stdout.getvalue()
 
587
        err = stderr.getvalue()
 
588
        if out:
 
589
            self.log('output:\n%s', out)
 
590
        if err:
 
591
            self.log('errors:\n%s', err)
 
592
        if retcode is not None:
 
593
            self.assertEquals(result, retcode)
 
594
        return out, err
 
595
 
 
596
    def run_bzr(self, *args, **kwargs):
 
597
        """Invoke bzr, as if it were run from the command line.
 
598
 
 
599
        This should be the main method for tests that want to exercise the
 
600
        overall behavior of the bzr application (rather than a unit test
 
601
        or a functional test of the library.)
 
602
 
 
603
        This sends the stdout/stderr results into the test's log,
 
604
        where it may be useful for debugging.  See also run_captured.
 
605
 
 
606
        :param stdin: A string to be used as stdin for the command.
 
607
        """
 
608
        retcode = kwargs.pop('retcode', 0)
 
609
        stdin = kwargs.pop('stdin', None)
 
610
        return self.run_bzr_captured(args, retcode, stdin)
 
611
 
 
612
    def check_inventory_shape(self, inv, shape):
 
613
        """Compare an inventory to a list of expected names.
 
614
 
 
615
        Fail if they are not precisely equal.
 
616
        """
 
617
        extras = []
 
618
        shape = list(shape)             # copy
 
619
        for path, ie in inv.entries():
 
620
            name = path.replace('\\', '/')
 
621
            if ie.kind == 'dir':
 
622
                name = name + '/'
 
623
            if name in shape:
 
624
                shape.remove(name)
 
625
            else:
 
626
                extras.append(name)
 
627
        if shape:
 
628
            self.fail("expected paths not found in inventory: %r" % shape)
 
629
        if extras:
 
630
            self.fail("unexpected paths found in inventory: %r" % extras)
 
631
 
 
632
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
 
633
                         a_callable=None, *args, **kwargs):
 
634
        """Call callable with redirected std io pipes.
 
635
 
 
636
        Returns the return code."""
 
637
        if not callable(a_callable):
 
638
            raise ValueError("a_callable must be callable.")
 
639
        if stdin is None:
 
640
            stdin = StringIO("")
 
641
        if stdout is None:
 
642
            if getattr(self, "_log_file", None) is not None:
 
643
                stdout = self._log_file
 
644
            else:
 
645
                stdout = StringIO()
 
646
        if stderr is None:
 
647
            if getattr(self, "_log_file", None is not None):
 
648
                stderr = self._log_file
 
649
            else:
 
650
                stderr = StringIO()
 
651
        real_stdin = sys.stdin
 
652
        real_stdout = sys.stdout
 
653
        real_stderr = sys.stderr
 
654
        try:
 
655
            sys.stdout = stdout
 
656
            sys.stderr = stderr
 
657
            sys.stdin = stdin
 
658
            return a_callable(*args, **kwargs)
 
659
        finally:
 
660
            sys.stdout = real_stdout
 
661
            sys.stderr = real_stderr
 
662
            sys.stdin = real_stdin
 
663
 
 
664
    def merge(self, branch_from, wt_to):
 
665
        """A helper for tests to do a ui-less merge.
 
666
 
 
667
        This should move to the main library when someone has time to integrate
 
668
        it in.
 
669
        """
 
670
        # minimal ui-less merge.
 
671
        wt_to.branch.fetch(branch_from)
 
672
        base_rev = common_ancestor(branch_from.last_revision(),
 
673
                                   wt_to.branch.last_revision(),
 
674
                                   wt_to.branch.repository)
 
675
        merge_inner(wt_to.branch, branch_from.basis_tree(), 
 
676
                    wt_to.branch.repository.revision_tree(base_rev),
 
677
                    this_tree=wt_to)
 
678
        wt_to.add_pending_merge(branch_from.last_revision())
 
679
 
 
680
 
 
681
BzrTestBase = TestCase
 
682
 
 
683
     
 
684
class TestCaseInTempDir(TestCase):
 
685
    """Derived class that runs a test within a temporary directory.
 
686
 
 
687
    This is useful for tests that need to create a branch, etc.
 
688
 
 
689
    The directory is created in a slightly complex way: for each
 
690
    Python invocation, a new temporary top-level directory is created.
 
691
    All test cases create their own directory within that.  If the
 
692
    tests complete successfully, the directory is removed.
 
693
 
 
694
    InTempDir is an old alias for FunctionalTestCase.
 
695
    """
 
696
 
 
697
    TEST_ROOT = None
 
698
    _TEST_NAME = 'test'
 
699
    OVERRIDE_PYTHON = 'python'
 
700
 
 
701
    def check_file_contents(self, filename, expect):
 
702
        self.log("check contents of file %s" % filename)
 
703
        contents = file(filename, 'r').read()
 
704
        if contents != expect:
 
705
            self.log("expected: %r" % expect)
 
706
            self.log("actually: %r" % contents)
 
707
            self.fail("contents of %s not as expected" % filename)
 
708
 
 
709
    def _make_test_root(self):
 
710
        if TestCaseInTempDir.TEST_ROOT is not None:
 
711
            return
 
712
        i = 0
 
713
        while True:
 
714
            root = u'test%04d.tmp' % i
 
715
            try:
 
716
                os.mkdir(root)
 
717
            except OSError, e:
 
718
                if e.errno == errno.EEXIST:
 
719
                    i += 1
 
720
                    continue
 
721
                else:
 
722
                    raise
 
723
            # successfully created
 
724
            TestCaseInTempDir.TEST_ROOT = osutils.abspath(root)
 
725
            break
 
726
        # make a fake bzr directory there to prevent any tests propagating
 
727
        # up onto the source directory's real branch
 
728
        bzrdir.BzrDir.create_standalone_workingtree(TestCaseInTempDir.TEST_ROOT)
 
729
 
 
730
    def setUp(self):
 
731
        super(TestCaseInTempDir, self).setUp()
 
732
        self._make_test_root()
 
733
        _currentdir = os.getcwdu()
 
734
        # shorten the name, to avoid test failures due to path length
 
735
        short_id = self.id().replace('bzrlib.tests.', '') \
 
736
                   .replace('__main__.', '')[-100:]
 
737
        # it's possible the same test class is run several times for
 
738
        # parameterized tests, so make sure the names don't collide.  
 
739
        i = 0
 
740
        while True:
 
741
            if i > 0:
 
742
                candidate_dir = '%s/%s.%d' % (self.TEST_ROOT, short_id, i)
 
743
            else:
 
744
                candidate_dir = '%s/%s' % (self.TEST_ROOT, short_id)
 
745
            if os.path.exists(candidate_dir):
 
746
                i = i + 1
 
747
                continue
 
748
            else:
 
749
                self.test_dir = candidate_dir
 
750
                os.mkdir(self.test_dir)
 
751
                os.chdir(self.test_dir)
 
752
                break
 
753
        os.environ['HOME'] = self.test_dir
 
754
        os.environ['APPDATA'] = self.test_dir
 
755
        def _leaveDirectory():
 
756
            os.chdir(_currentdir)
 
757
        self.addCleanup(_leaveDirectory)
 
758
        
 
759
    def build_tree(self, shape, line_endings='native', transport=None):
 
760
        """Build a test tree according to a pattern.
 
761
 
 
762
        shape is a sequence of file specifications.  If the final
 
763
        character is '/', a directory is created.
 
764
 
 
765
        This doesn't add anything to a branch.
 
766
        :param line_endings: Either 'binary' or 'native'
 
767
                             in binary mode, exact contents are written
 
768
                             in native mode, the line endings match the
 
769
                             default platform endings.
 
770
 
 
771
        :param transport: A transport to write to, for building trees on 
 
772
                          VFS's. If the transport is readonly or None,
 
773
                          "." is opened automatically.
 
774
        """
 
775
        # XXX: It's OK to just create them using forward slashes on windows?
 
776
        if transport is None or transport.is_readonly():
 
777
            transport = get_transport(".")
 
778
        for name in shape:
 
779
            self.assert_(isinstance(name, basestring))
 
780
            if name[-1] == '/':
 
781
                transport.mkdir(urlescape(name[:-1]))
 
782
            else:
 
783
                if line_endings == 'binary':
 
784
                    end = '\n'
 
785
                elif line_endings == 'native':
 
786
                    end = os.linesep
 
787
                else:
 
788
                    raise errors.BzrError('Invalid line ending request %r' % (line_endings,))
 
789
                content = "contents of %s%s" % (name, end)
 
790
                transport.put(urlescape(name), StringIO(content))
 
791
 
 
792
    def build_tree_contents(self, shape):
 
793
        build_tree_contents(shape)
 
794
 
 
795
    def failUnlessExists(self, path):
 
796
        """Fail unless path, which may be abs or relative, exists."""
 
797
        self.failUnless(osutils.lexists(path))
 
798
 
 
799
    def failIfExists(self, path):
 
800
        """Fail if path, which may be abs or relative, exists."""
 
801
        self.failIf(osutils.lexists(path))
 
802
        
 
803
    def assertFileEqual(self, content, path):
 
804
        """Fail if path does not contain 'content'."""
 
805
        self.failUnless(osutils.lexists(path))
 
806
        self.assertEqualDiff(content, open(path, 'r').read())
 
807
 
 
808
 
 
809
class TestCaseWithTransport(TestCaseInTempDir):
 
810
    """A test case that provides get_url and get_readonly_url facilities.
 
811
 
 
812
    These back onto two transport servers, one for readonly access and one for
 
813
    read write access.
 
814
 
 
815
    If no explicit class is provided for readonly access, a
 
816
    ReadonlyTransportDecorator is used instead which allows the use of non disk
 
817
    based read write transports.
 
818
 
 
819
    If an explicit class is provided for readonly access, that server and the 
 
820
    readwrite one must both define get_url() as resolving to os.getcwd().
 
821
    """
 
822
 
 
823
    def __init__(self, methodName='testMethod'):
 
824
        super(TestCaseWithTransport, self).__init__(methodName)
 
825
        self.__readonly_server = None
 
826
        self.__server = None
 
827
        self.transport_server = default_transport
 
828
        self.transport_readonly_server = None
 
829
 
 
830
    def get_readonly_url(self, relpath=None):
 
831
        """Get a URL for the readonly transport.
 
832
 
 
833
        This will either be backed by '.' or a decorator to the transport 
 
834
        used by self.get_url()
 
835
        relpath provides for clients to get a path relative to the base url.
 
836
        These should only be downwards relative, not upwards.
 
837
        """
 
838
        base = self.get_readonly_server().get_url()
 
839
        if relpath is not None:
 
840
            if not base.endswith('/'):
 
841
                base = base + '/'
 
842
            base = base + relpath
 
843
        return base
 
844
 
 
845
    def get_readonly_server(self):
 
846
        """Get the server instance for the readonly transport
 
847
 
 
848
        This is useful for some tests with specific servers to do diagnostics.
 
849
        """
 
850
        if self.__readonly_server is None:
 
851
            if self.transport_readonly_server is None:
 
852
                # readonly decorator requested
 
853
                # bring up the server
 
854
                self.get_url()
 
855
                self.__readonly_server = ReadonlyServer()
 
856
                self.__readonly_server.setUp(self.__server)
 
857
            else:
 
858
                self.__readonly_server = self.transport_readonly_server()
 
859
                self.__readonly_server.setUp()
 
860
            self.addCleanup(self.__readonly_server.tearDown)
 
861
        return self.__readonly_server
 
862
 
 
863
    def get_server(self):
 
864
        """Get the read/write server instance.
 
865
 
 
866
        This is useful for some tests with specific servers that need
 
867
        diagnostics.
 
868
        """
 
869
        if self.__server is None:
 
870
            self.__server = self.transport_server()
 
871
            self.__server.setUp()
 
872
            self.addCleanup(self.__server.tearDown)
 
873
        return self.__server
 
874
 
 
875
    def get_url(self, relpath=None):
 
876
        """Get a URL for the readwrite transport.
 
877
 
 
878
        This will either be backed by '.' or to an equivalent non-file based
 
879
        facility.
 
880
        relpath provides for clients to get a path relative to the base url.
 
881
        These should only be downwards relative, not upwards.
 
882
        """
 
883
        base = self.get_server().get_url()
 
884
        if relpath is not None and relpath != '.':
 
885
            if not base.endswith('/'):
 
886
                base = base + '/'
 
887
            base = base + relpath
 
888
        return base
 
889
 
 
890
    def get_transport(self):
 
891
        """Return a writeable transport for the test scratch space"""
 
892
        t = get_transport(self.get_url())
 
893
        self.assertFalse(t.is_readonly())
 
894
        return t
 
895
 
 
896
    def get_readonly_transport(self):
 
897
        """Return a readonly transport for the test scratch space
 
898
        
 
899
        This can be used to test that operations which should only need
 
900
        readonly access in fact do not try to write.
 
901
        """
 
902
        t = get_transport(self.get_readonly_url())
 
903
        self.assertTrue(t.is_readonly())
 
904
        return t
 
905
 
 
906
    def make_branch(self, relpath, format=None):
 
907
        """Create a branch on the transport at relpath."""
 
908
        repo = self.make_repository(relpath, format=format)
 
909
        return repo.bzrdir.create_branch()
 
910
 
 
911
    def make_bzrdir(self, relpath, format=None):
 
912
        try:
 
913
            url = self.get_url(relpath)
 
914
            segments = relpath.split('/')
 
915
            if segments and segments[-1] not in ('', '.'):
 
916
                parent = self.get_url('/'.join(segments[:-1]))
 
917
                t = get_transport(parent)
 
918
                try:
 
919
                    t.mkdir(segments[-1])
 
920
                except errors.FileExists:
 
921
                    pass
 
922
            if format is None:
 
923
                format=bzrlib.bzrdir.BzrDirFormat.get_default_format()
 
924
            # FIXME: make this use a single transport someday. RBC 20060418
 
925
            return format.initialize_on_transport(get_transport(relpath))
 
926
        except errors.UninitializableFormat:
 
927
            raise TestSkipped("Format %s is not initializable." % format)
 
928
 
 
929
    def make_repository(self, relpath, shared=False, format=None):
 
930
        """Create a repository on our default transport at relpath."""
 
931
        made_control = self.make_bzrdir(relpath, format=format)
 
932
        return made_control.create_repository(shared=shared)
 
933
 
 
934
    def make_branch_and_tree(self, relpath, format=None):
 
935
        """Create a branch on the transport and a tree locally.
 
936
 
 
937
        Returns the tree.
 
938
        """
 
939
        # TODO: always use the local disk path for the working tree,
 
940
        # this obviously requires a format that supports branch references
 
941
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
 
942
        # RBC 20060208
 
943
        b = self.make_branch(relpath, format=format)
 
944
        try:
 
945
            return b.bzrdir.create_workingtree()
 
946
        except errors.NotLocalUrl:
 
947
            # new formats - catch No tree error and create
 
948
            # a branch reference and a checkout.
 
949
            # old formats at that point - raise TestSkipped.
 
950
            # TODO: rbc 20060208
 
951
            return WorkingTreeFormat2().initialize(bzrdir.BzrDir.open(relpath))
 
952
 
 
953
    def assertIsDirectory(self, relpath, transport):
 
954
        """Assert that relpath within transport is a directory.
 
955
 
 
956
        This may not be possible on all transports; in that case it propagates
 
957
        a TransportNotPossible.
 
958
        """
 
959
        try:
 
960
            mode = transport.stat(relpath).st_mode
 
961
        except errors.NoSuchFile:
 
962
            self.fail("path %s is not a directory; no such file"
 
963
                      % (relpath))
 
964
        if not stat.S_ISDIR(mode):
 
965
            self.fail("path %s is not a directory; has mode %#o"
 
966
                      % (relpath, mode))
 
967
 
 
968
 
 
969
class ChrootedTestCase(TestCaseWithTransport):
 
970
    """A support class that provides readonly urls outside the local namespace.
 
971
 
 
972
    This is done by checking if self.transport_server is a MemoryServer. if it
 
973
    is then we are chrooted already, if it is not then an HttpServer is used
 
974
    for readonly urls.
 
975
 
 
976
    TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
 
977
                       be used without needed to redo it when a different 
 
978
                       subclass is in use ?
 
979
    """
 
980
 
 
981
    def setUp(self):
 
982
        super(ChrootedTestCase, self).setUp()
 
983
        if not self.transport_server == bzrlib.transport.memory.MemoryServer:
 
984
            self.transport_readonly_server = bzrlib.transport.http.HttpServer
 
985
 
 
986
 
 
987
def filter_suite_by_re(suite, pattern):
 
988
    result = TestSuite()
 
989
    filter_re = re.compile(pattern)
 
990
    for test in iter_suite_tests(suite):
 
991
        if filter_re.search(test.id()):
 
992
            result.addTest(test)
 
993
    return result
 
994
 
 
995
 
 
996
def run_suite(suite, name='test', verbose=False, pattern=".*",
 
997
              stop_on_failure=False, keep_output=False,
 
998
              transport=None):
 
999
    TestCaseInTempDir._TEST_NAME = name
 
1000
    if verbose:
 
1001
        verbosity = 2
 
1002
        pb = None
 
1003
    else:
 
1004
        verbosity = 1
 
1005
        pb = progress.ProgressBar()
 
1006
    runner = TextTestRunner(stream=sys.stdout,
 
1007
                            descriptions=0,
 
1008
                            verbosity=verbosity,
 
1009
                            keep_output=keep_output,
 
1010
                            pb=pb)
 
1011
    runner.stop_on_failure=stop_on_failure
 
1012
    if pattern != '.*':
 
1013
        suite = filter_suite_by_re(suite, pattern)
 
1014
    result = runner.run(suite)
 
1015
    return result.wasSuccessful()
 
1016
 
 
1017
 
 
1018
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
 
1019
             keep_output=False,
 
1020
             transport=None,
 
1021
             test_suite_factory=None):
 
1022
    """Run the whole test suite under the enhanced runner"""
 
1023
    global default_transport
 
1024
    if transport is None:
 
1025
        transport = default_transport
 
1026
    old_transport = default_transport
 
1027
    default_transport = transport
 
1028
    try:
 
1029
        if test_suite_factory is None:
 
1030
            suite = test_suite()
 
1031
        else:
 
1032
            suite = test_suite_factory()
 
1033
        return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
 
1034
                     stop_on_failure=stop_on_failure, keep_output=keep_output,
 
1035
                     transport=transport)
 
1036
    finally:
 
1037
        default_transport = old_transport
 
1038
 
 
1039
 
 
1040
def benchmark_suite():
 
1041
    """Build and return a TestSuite which contains benchmark tests only."""
 
1042
    return TestSuite()
 
1043
 
 
1044
 
 
1045
def test_suite():
 
1046
    """Build and return TestSuite for the whole of bzrlib.
 
1047
    
 
1048
    This function can be replaced if you need to change the default test
 
1049
    suite on a global basis, but it is not encouraged.
 
1050
    """
 
1051
    from doctest import DocTestSuite
 
1052
 
 
1053
    global MODULES_TO_DOCTEST
 
1054
 
 
1055
    testmod_names = [ \
 
1056
                   'bzrlib.tests.test_ancestry',
 
1057
                   'bzrlib.tests.test_api',
 
1058
                   'bzrlib.tests.test_bad_files',
 
1059
                   'bzrlib.tests.test_branch',
 
1060
                   'bzrlib.tests.test_bzrdir',
 
1061
                   'bzrlib.tests.test_command',
 
1062
                   'bzrlib.tests.test_commit',
 
1063
                   'bzrlib.tests.test_commit_merge',
 
1064
                   'bzrlib.tests.test_config',
 
1065
                   'bzrlib.tests.test_conflicts',
 
1066
                   'bzrlib.tests.test_decorators',
 
1067
                   'bzrlib.tests.test_diff',
 
1068
                   'bzrlib.tests.test_doc_generate',
 
1069
                   'bzrlib.tests.test_errors',
 
1070
                   'bzrlib.tests.test_escaped_store',
 
1071
                   'bzrlib.tests.test_fetch',
 
1072
                   'bzrlib.tests.test_gpg',
 
1073
                   'bzrlib.tests.test_graph',
 
1074
                   'bzrlib.tests.test_hashcache',
 
1075
                   'bzrlib.tests.test_http',
 
1076
                   'bzrlib.tests.test_identitymap',
 
1077
                   'bzrlib.tests.test_inv',
 
1078
                   'bzrlib.tests.test_knit',
 
1079
                   'bzrlib.tests.test_lockdir',
 
1080
                   'bzrlib.tests.test_lockable_files',
 
1081
                   'bzrlib.tests.test_log',
 
1082
                   'bzrlib.tests.test_merge',
 
1083
                   'bzrlib.tests.test_merge3',
 
1084
                   'bzrlib.tests.test_merge_core',
 
1085
                   'bzrlib.tests.test_missing',
 
1086
                   'bzrlib.tests.test_msgeditor',
 
1087
                   'bzrlib.tests.test_nonascii',
 
1088
                   'bzrlib.tests.test_options',
 
1089
                   'bzrlib.tests.test_osutils',
 
1090
                   'bzrlib.tests.test_patch',
 
1091
                   'bzrlib.tests.test_permissions',
 
1092
                   'bzrlib.tests.test_plugins',
 
1093
                   'bzrlib.tests.test_progress',
 
1094
                   'bzrlib.tests.test_reconcile',
 
1095
                   'bzrlib.tests.test_repository',
 
1096
                   'bzrlib.tests.test_revision',
 
1097
                   'bzrlib.tests.test_revisionnamespaces',
 
1098
                   'bzrlib.tests.test_revprops',
 
1099
                   'bzrlib.tests.test_rio',
 
1100
                   'bzrlib.tests.test_sampler',
 
1101
                   'bzrlib.tests.test_selftest',
 
1102
                   'bzrlib.tests.test_setup',
 
1103
                   'bzrlib.tests.test_sftp_transport',
 
1104
                   'bzrlib.tests.test_smart_add',
 
1105
                   'bzrlib.tests.test_source',
 
1106
                   'bzrlib.tests.test_store',
 
1107
                   'bzrlib.tests.test_symbol_versioning',
 
1108
                   'bzrlib.tests.test_testament',
 
1109
                   'bzrlib.tests.test_textfile',
 
1110
                   'bzrlib.tests.test_textmerge',
 
1111
                   'bzrlib.tests.test_trace',
 
1112
                   'bzrlib.tests.test_transactions',
 
1113
                   'bzrlib.tests.test_transform',
 
1114
                   'bzrlib.tests.test_transport',
 
1115
                   'bzrlib.tests.test_tsort',
 
1116
                   'bzrlib.tests.test_tuned_gzip',
 
1117
                   'bzrlib.tests.test_ui',
 
1118
                   'bzrlib.tests.test_upgrade',
 
1119
                   'bzrlib.tests.test_versionedfile',
 
1120
                   'bzrlib.tests.test_weave',
 
1121
                   'bzrlib.tests.test_whitebox',
 
1122
                   'bzrlib.tests.test_workingtree',
 
1123
                   'bzrlib.tests.test_xml',
 
1124
                   ]
 
1125
    test_transport_implementations = [
 
1126
        'bzrlib.tests.test_transport_implementations']
 
1127
 
 
1128
    suite = TestSuite()
 
1129
    # python2.4's TestLoader.loadTestsFromNames gives very poor 
 
1130
    # errors if it fails to load a named module - no indication of what's
 
1131
    # actually wrong, just "no such module".  We should probably override that
 
1132
    # class, but for the moment just load them ourselves. (mbp 20051202)
 
1133
    loader = TestLoader()
 
1134
    from bzrlib.transport import TransportTestProviderAdapter
 
1135
    adapter = TransportTestProviderAdapter()
 
1136
    adapt_modules(test_transport_implementations, adapter, loader, suite)
 
1137
    for mod_name in testmod_names:
 
1138
        mod = _load_module_by_name(mod_name)
 
1139
        suite.addTest(loader.loadTestsFromModule(mod))
 
1140
    for package in packages_to_test():
 
1141
        suite.addTest(package.test_suite())
 
1142
    for m in MODULES_TO_TEST:
 
1143
        suite.addTest(loader.loadTestsFromModule(m))
 
1144
    for m in (MODULES_TO_DOCTEST):
 
1145
        suite.addTest(DocTestSuite(m))
 
1146
    for name, plugin in bzrlib.plugin.all_plugins().items():
 
1147
        if getattr(plugin, 'test_suite', None) is not None:
 
1148
            suite.addTest(plugin.test_suite())
 
1149
    return suite
 
1150
 
 
1151
 
 
1152
def adapt_modules(mods_list, adapter, loader, suite):
 
1153
    """Adapt the modules in mods_list using adapter and add to suite."""
 
1154
    for mod_name in mods_list:
 
1155
        mod = _load_module_by_name(mod_name)
 
1156
        for test in iter_suite_tests(loader.loadTestsFromModule(mod)):
 
1157
            suite.addTests(adapter.adapt(test))
 
1158
 
 
1159
 
 
1160
def _load_module_by_name(mod_name):
 
1161
    parts = mod_name.split('.')
 
1162
    module = __import__(mod_name)
 
1163
    del parts[0]
 
1164
    # for historical reasons python returns the top-level module even though
 
1165
    # it loads the submodule; we need to walk down to get the one we want.
 
1166
    while parts:
 
1167
        module = getattr(module, parts.pop(0))
 
1168
    return module