/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
608 by Martin Pool
- Split selftests out into a new module and start changing them
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
609 by Martin Pool
- cleanup test code
17
1535 by Martin Pool
todo idea from John
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
1185.1.29 by Robert Collins
merge merge tweaks from aaron, which includes latest .dev
24
from cStringIO import StringIO
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
25
import difflib
26
import errno
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
27
import logging
28
import os
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
29
import re
30
import shutil
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
31
import sys
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
32
import tempfile
33
import unittest
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
34
import time
1185.52.1 by James Henstridge
Don't encode unicode messages to UTF-8 in mutter() (the stream writer does it).
35
import codecs
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
36
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
37
import bzrlib.branch
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
38
import bzrlib.commands
1514 by Robert Collins
Unbreak self.build_tree_shape in tests.
39
from bzrlib.errors import BzrError
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
40
import bzrlib.inventory
41
import bzrlib.merge3
42
import bzrlib.osutils
43
import bzrlib.osutils as osutils
44
import bzrlib.plugin
45
import bzrlib.store
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
46
import bzrlib.trace
1185.43.1 by Martin Pool
Remove direct logging calls from selftest
47
from bzrlib.trace import mutter
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
48
from bzrlib.tests.TestUtil import TestLoader, TestSuite
1514 by Robert Collins
Unbreak self.build_tree_shape in tests.
49
from bzrlib.tests.treeshape import build_tree_contents
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
50
855 by Martin Pool
- Patch from John to allow plugins to add their own tests.
51
MODULES_TO_TEST = []
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
52
MODULES_TO_DOCTEST = [
53
                      bzrlib.branch,
54
                      bzrlib.commands,
55
                      bzrlib.errors,
56
                      bzrlib.inventory,
57
                      bzrlib.merge3,
58
                      bzrlib.osutils,
59
                      bzrlib.store,
60
                      ]
61
def packages_to_test():
62
    import bzrlib.tests.blackbox
63
    return [
64
            bzrlib.tests.blackbox
65
            ]
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
66
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
67
68
class EarlyStoppingTestResultAdapter(object):
69
    """An adapter for TestResult to stop at the first first failure or error"""
70
71
    def __init__(self, result):
72
        self._result = result
73
74
    def addError(self, test, err):
75
        self._result.addError(test, err)
76
        self._result.stop()
77
78
    def addFailure(self, test, err):
79
        self._result.addFailure(test, err)
80
        self._result.stop()
81
82
    def __getattr__(self, name):
83
        return getattr(self._result, name)
84
85
    def __setattr__(self, name, value):
86
        if name == '_result':
87
            object.__setattr__(self, name, value)
88
        return setattr(self._result, name, value)
89
90
91
class _MyResult(unittest._TextTestResult):
1185.43.2 by Martin Pool
Nicer display of verbose test results and progress
92
    """Custom TestResult.
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
93
1185.33.54 by Martin Pool
[merge] test renames and other fixes (John)
94
    Shows output in a different format, including displaying runtime for tests.
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
95
    """
96
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
97
    def _elapsedTime(self):
1185.43.2 by Martin Pool
Nicer display of verbose test results and progress
98
        return "%5dms" % (1000 * (time.time() - self._start_time))
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
99
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
100
    def startTest(self, test):
101
        unittest.TestResult.startTest(self, test)
1185.31.17 by John Arbash Meinel
Shorten test names in verbose mode in a logical way. Removed bzrlib.selftest prefix
102
        # In a short description, the important words are in
103
        # the beginning, but in an id, the important words are
104
        # at the end
1185.33.54 by Martin Pool
[merge] test renames and other fixes (John)
105
        SHOW_DESCRIPTIONS = False
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
106
        if self.showAll:
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
107
            width = osutils.terminal_width()
108
            name_width = width - 15
109
            what = None
110
            if SHOW_DESCRIPTIONS:
111
                what = test.shortDescription()
112
                if what:
113
                    if len(what) > name_width:
114
                        what = what[:name_width-3] + '...'
115
            if what is None:
116
                what = test.id()
117
                if what.startswith('bzrlib.tests.'):
118
                    what = what[13:]
119
                if len(what) > name_width:
120
                    what = '...' + what[3-name_width:]
121
            what = what.ljust(name_width)
122
            self.stream.write(what)
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
123
        self.stream.flush()
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
124
        self._start_time = time.time()
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
125
126
    def addError(self, test, err):
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
127
        if isinstance(err[1], TestSkipped):
128
            return self.addSkipped(test, err)    
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
129
        unittest.TestResult.addError(self, test, err)
130
        if self.showAll:
131
            self.stream.writeln("ERROR %s" % self._elapsedTime())
132
        elif self.dots:
133
            self.stream.write('E')
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
134
        self.stream.flush()
135
136
    def addFailure(self, test, err):
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
137
        unittest.TestResult.addFailure(self, test, err)
138
        if self.showAll:
1185.43.2 by Martin Pool
Nicer display of verbose test results and progress
139
            self.stream.writeln(" FAIL %s" % self._elapsedTime())
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
140
        elif self.dots:
141
            self.stream.write('F')
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
142
        self.stream.flush()
143
144
    def addSuccess(self, test):
145
        if self.showAll:
1185.43.2 by Martin Pool
Nicer display of verbose test results and progress
146
            self.stream.writeln('   OK %s' % self._elapsedTime())
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
147
        elif self.dots:
148
            self.stream.write('~')
149
        self.stream.flush()
150
        unittest.TestResult.addSuccess(self, test)
151
1185.33.96 by Martin Pool
Fix up display of reasons why tests were skipped.
152
    def addSkipped(self, test, skip_excinfo):
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
153
        if self.showAll:
1185.33.96 by Martin Pool
Fix up display of reasons why tests were skipped.
154
            print >>self.stream, ' SKIP %s' % self._elapsedTime()
155
            print >>self.stream, '     %s' % skip_excinfo[1]
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
156
        elif self.dots:
157
            self.stream.write('S')
158
        self.stream.flush()
159
        # seems best to treat this as success from point-of-view of unittest
160
        # -- it actually does nothing so it barely matters :)
161
        unittest.TestResult.addSuccess(self, test)
162
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
163
    def printErrorList(self, flavour, errors):
164
        for test, err in errors:
165
            self.stream.writeln(self.separator1)
166
            self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
167
            if hasattr(test, '_get_log'):
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
168
                print >>self.stream
169
                print >>self.stream, \
170
                        ('vvvv[log from %s]' % test).ljust(78,'-')
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
171
                print >>self.stream, test._get_log()
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
172
                print >>self.stream, \
173
                        ('^^^^[log from %s]' % test).ljust(78,'-')
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
174
            self.stream.writeln(self.separator2)
175
            self.stream.writeln("%s" % err)
176
177
178
class TextTestRunner(unittest.TextTestRunner):
1185.16.58 by mbp at sourcefrog
- run all selftests by default
179
    stop_on_failure = False
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
180
181
    def _makeResult(self):
182
        result = _MyResult(self.stream, self.descriptions, self.verbosity)
1185.16.58 by mbp at sourcefrog
- run all selftests by default
183
        if self.stop_on_failure:
184
            result = EarlyStoppingTestResultAdapter(result)
185
        return result
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
186
187
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
188
def iter_suite_tests(suite):
189
    """Return all tests in a suite, recursing through nested suites"""
190
    for item in suite._tests:
191
        if isinstance(item, unittest.TestCase):
192
            yield item
193
        elif isinstance(item, unittest.TestSuite):
194
            for r in iter_suite_tests(item):
195
                yield r
196
        else:
197
            raise Exception('unknown object %r inside test suite %r'
198
                            % (item, suite))
199
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
200
201
class TestSkipped(Exception):
202
    """Indicates that a test was intentionally skipped, rather than failing."""
203
    # XXX: Not used yet
204
205
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
206
class CommandFailed(Exception):
207
    pass
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
208
209
class TestCase(unittest.TestCase):
210
    """Base class for bzr unit tests.
211
    
212
    Tests that need access to disk resources should subclass 
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
213
    TestCaseInTempDir not TestCase.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
214
215
    Error and debug log messages are redirected from their usual
216
    location into a temporary file, the contents of which can be
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
217
    retrieved by _get_log().  We use a real OS file, not an in-memory object,
218
    so that it can also capture file IO.  When the test completes this file
219
    is read into memory and removed from disk.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
220
       
221
    There are also convenience functions to invoke bzr's command-line
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
222
    routine, and to build and check bzr trees.
223
   
224
    In addition to the usual method of overriding tearDown(), this class also
225
    allows subclasses to register functions into the _cleanups list, which is
226
    run in order as the object is torn down.  It's less likely this will be
227
    accidentally overlooked.
228
    """
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
229
230
    BZRPATH = 'bzr'
1185.16.14 by Martin Pool
- make TestCase._get_log work even if setup was aborted
231
    _log_file_name = None
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
232
    _log_contents = ''
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
233
234
    def setUp(self):
235
        unittest.TestCase.setUp(self)
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
236
        self._cleanups = []
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
237
        self._cleanEnvironment()
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
238
        bzrlib.trace.disable_default_logging()
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
239
        self._startLogFile()
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
240
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
241
    def _ndiff_strings(self, a, b):
1185.16.67 by Martin Pool
- assertEqualDiff handles strings without trailing newline
242
        """Return ndiff between two strings containing lines.
243
        
244
        A trailing newline is added if missing to make the strings
245
        print properly."""
246
        if b and b[-1] != '\n':
247
            b += '\n'
248
        if a and a[-1] != '\n':
249
            a += '\n'
1185.16.21 by Martin Pool
- tweak diff shown by assertEqualDiff
250
        difflines = difflib.ndiff(a.splitlines(True),
251
                                  b.splitlines(True),
252
                                  linejunk=lambda x: False,
253
                                  charjunk=lambda x: False)
254
        return ''.join(difflines)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
255
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
256
    def assertEqualDiff(self, a, b):
257
        """Assert two texts are equal, if not raise an exception.
258
        
259
        This is intended for use with multi-line strings where it can 
260
        be hard to find the differences by eye.
261
        """
262
        # TODO: perhaps override assertEquals to call this for strings?
263
        if a == b:
264
            return
265
        raise AssertionError("texts not equal:\n" + 
266
                             self._ndiff_strings(a, b))      
1185.31.40 by John Arbash Meinel
Added osutils.mkdtemp()
267
        
268
    def assertStartsWith(self, s, prefix):
269
        if not s.startswith(prefix):
270
            raise AssertionError('string %r does not start with %r' % (s, prefix))
271
272
    def assertEndsWith(self, s, suffix):
273
        if not s.endswith(prefix):
274
            raise AssertionError('string %r does not end with %r' % (s, suffix))
1185.16.42 by Martin Pool
- Add assertContainsRe
275
276
    def assertContainsRe(self, haystack, needle_re):
277
        """Assert that a contains something matching a regular expression."""
278
        if not re.search(needle_re, haystack):
279
            raise AssertionError('pattern "%s" not found in "%s"'
280
                    % (needle_re, haystack))
1442.1.70 by Robert Collins
Add assertFileEqual to TestCaseInTempDir.
281
1185.46.8 by Aaron Bentley
bzr add reports ignored patterns.
282
    def AssertSubset(self, sublist, superlist):
283
        """Assert that every entry in sublist is present in superlist."""
284
        missing = []
285
        for entry in sublist:
286
            if entry not in superlist:
287
                missing.append(entry)
288
        if len(missing) > 0:
289
            raise AssertionError("value(s) %r not present in container %r" % 
290
                                 (missing, superlist))
291
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
292
    def _startLogFile(self):
293
        """Send bzr and test log messages to a temporary file.
294
295
        The file is removed as the test is torn down.
296
        """
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
297
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
1185.52.1 by James Henstridge
Don't encode unicode messages to UTF-8 in mutter() (the stream writer does it).
298
        encoder, decoder, stream_reader, stream_writer = codecs.lookup('UTF-8')
299
        self._log_file = stream_writer(os.fdopen(fileno, 'w+'))
1185.33.13 by Martin Pool
Hide more stuff in bzrlib.trace
300
        bzrlib.trace.enable_test_log(self._log_file)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
301
        self._log_file_name = name
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
302
        self.addCleanup(self._finishLogFile)
303
304
    def _finishLogFile(self):
305
        """Finished with the log file.
306
307
        Read contents into memory, close, and delete.
308
        """
1185.33.13 by Martin Pool
Hide more stuff in bzrlib.trace
309
        bzrlib.trace.disable_test_log()
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
310
        self._log_file.seek(0)
311
        self._log_contents = self._log_file.read()
1185.16.122 by Martin Pool
[patch] Close test log file before deleting, needed on Windows
312
        self._log_file.close()
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
313
        os.remove(self._log_file_name)
314
        self._log_file = self._log_file_name = None
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
315
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
316
    def addCleanup(self, callable):
317
        """Arrange to run a callable when this case is torn down.
318
319
        Callables are run in the reverse of the order they are registered, 
320
        ie last-in first-out.
321
        """
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
322
        if callable in self._cleanups:
323
            raise ValueError("cleanup function %r already registered on %s" 
324
                    % (callable, self))
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
325
        self._cleanups.append(callable)
326
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
327
    def _cleanEnvironment(self):
1185.38.3 by John Arbash Meinel
Refactored environment cleaning code
328
        new_env = {
329
            'HOME': os.getcwd(),
330
            'APPDATA': os.getcwd(),
331
            'BZREMAIL': None,
332
            'EMAIL': None,
333
        }
1185.38.4 by John Arbash Meinel
Making old_env a private member
334
        self.__old_env = {}
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
335
        self.addCleanup(self._restoreEnvironment)
1185.38.3 by John Arbash Meinel
Refactored environment cleaning code
336
        for name, value in new_env.iteritems():
337
            self._captureVar(name, value)
338
339
340
    def _captureVar(self, name, newvalue):
341
        """Set an environment variable, preparing it to be reset when finished."""
1185.38.4 by John Arbash Meinel
Making old_env a private member
342
        self.__old_env[name] = os.environ.get(name, None)
1185.38.3 by John Arbash Meinel
Refactored environment cleaning code
343
        if newvalue is None:
344
            if name in os.environ:
345
                del os.environ[name]
346
        else:
347
            os.environ[name] = newvalue
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
348
1185.38.2 by John Arbash Meinel
[patch] Aaron Bentley's HOME fix.
349
    @staticmethod
350
    def _restoreVar(name, value):
351
        if value is None:
1185.38.3 by John Arbash Meinel
Refactored environment cleaning code
352
            if name in os.environ:
353
                del os.environ[name]
1185.38.2 by John Arbash Meinel
[patch] Aaron Bentley's HOME fix.
354
        else:
355
            os.environ[name] = value
356
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
357
    def _restoreEnvironment(self):
1185.38.4 by John Arbash Meinel
Making old_env a private member
358
        for name, value in self.__old_env.iteritems():
1185.38.3 by John Arbash Meinel
Refactored environment cleaning code
359
            self._restoreVar(name, value)
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
360
361
    def tearDown(self):
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
362
        self._runCleanups()
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
363
        unittest.TestCase.tearDown(self)
364
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
365
    def _runCleanups(self):
366
        """Run registered cleanup functions. 
367
368
        This should only be called from TestCase.tearDown.
369
        """
1541 by Martin Pool
doc
370
        # TODO: Perhaps this should keep running cleanups even if 
371
        # one of them fails?
1185.33.74 by Martin Pool
pychecker cleanups
372
        for cleanup_fn in reversed(self._cleanups):
373
            cleanup_fn()
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
374
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
375
    def log(self, *args):
1185.43.1 by Martin Pool
Remove direct logging calls from selftest
376
        mutter(*args)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
377
378
    def _get_log(self):
379
        """Return as a string the log for this test"""
1185.16.14 by Martin Pool
- make TestCase._get_log work even if setup was aborted
380
        if self._log_file_name:
381
            return open(self._log_file_name).read()
382
        else:
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
383
            return self._log_contents
1185.43.1 by Martin Pool
Remove direct logging calls from selftest
384
        # TODO: Delete the log after it's been read in
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
385
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
386
    def capture(self, cmd, retcode=0):
1185.3.26 by Martin Pool
- remove remaining external executions of bzr
387
        """Shortcut that splits cmd into words, runs, and returns stdout"""
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
388
        return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
1185.3.26 by Martin Pool
- remove remaining external executions of bzr
389
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
390
    def run_bzr_captured(self, argv, retcode=0):
1185.22.7 by Michael Ellerman
Fix error in run_bzr_captured() doco
391
        """Invoke bzr and return (stdout, stderr).
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
392
393
        Useful for code that wants to check the contents of the
394
        output, the way error messages are presented, etc.
395
396
        This should be the main method for tests that want to exercise the
397
        overall behavior of the bzr application (rather than a unit test
398
        or a functional test of the library.)
399
400
        Much of the old code runs bzr by forking a new copy of Python, but
401
        that is slower, harder to debug, and generally not necessary.
402
1185.3.20 by Martin Pool
- run_bzr_captured also includes logged errors in
403
        This runs bzr through the interface that catches and reports
404
        errors, and with logging set to something approximating the
405
        default, so that error reporting can be checked.
406
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
407
        argv -- arguments to invoke bzr
408
        retcode -- expected return code, or None for don't-care.
409
        """
410
        stdout = StringIO()
411
        stderr = StringIO()
412
        self.log('run bzr: %s', ' '.join(argv))
1185.43.5 by Martin Pool
Update log message quoting
413
        # FIXME: don't call into logging here
1185.3.20 by Martin Pool
- run_bzr_captured also includes logged errors in
414
        handler = logging.StreamHandler(stderr)
415
        handler.setFormatter(bzrlib.trace.QuietFormatter())
416
        handler.setLevel(logging.INFO)
417
        logger = logging.getLogger('')
418
        logger.addHandler(handler)
419
        try:
420
            result = self.apply_redirected(None, stdout, stderr,
421
                                           bzrlib.commands.run_bzr_catch_errors,
422
                                           argv)
423
        finally:
424
            logger.removeHandler(handler)
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
425
        out = stdout.getvalue()
426
        err = stderr.getvalue()
427
        if out:
428
            self.log('output:\n%s', out)
429
        if err:
430
            self.log('errors:\n%s', err)
431
        if retcode is not None:
432
            self.assertEquals(result, retcode)
433
        return out, err
434
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
435
    def run_bzr(self, *args, **kwargs):
1119 by Martin Pool
doc
436
        """Invoke bzr, as if it were run from the command line.
437
438
        This should be the main method for tests that want to exercise the
439
        overall behavior of the bzr application (rather than a unit test
440
        or a functional test of the library.)
441
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
442
        This sends the stdout/stderr results into the test's log,
443
        where it may be useful for debugging.  See also run_captured.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
444
        """
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
445
        retcode = kwargs.pop('retcode', 0)
1185.3.21 by Martin Pool
TestBase.run_bzr doesn't need to be deprecated
446
        return self.run_bzr_captured(args, retcode)
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
447
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
448
    def check_inventory_shape(self, inv, shape):
1291 by Martin Pool
- add test for moving files between directories
449
        """Compare an inventory to a list of expected names.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
450
451
        Fail if they are not precisely equal.
452
        """
453
        extras = []
454
        shape = list(shape)             # copy
455
        for path, ie in inv.entries():
456
            name = path.replace('\\', '/')
457
            if ie.kind == 'dir':
458
                name = name + '/'
459
            if name in shape:
460
                shape.remove(name)
461
            else:
462
                extras.append(name)
463
        if shape:
464
            self.fail("expected paths not found in inventory: %r" % shape)
465
        if extras:
466
            self.fail("unexpected paths found in inventory: %r" % extras)
467
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
468
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
469
                         a_callable=None, *args, **kwargs):
470
        """Call callable with redirected std io pipes.
471
472
        Returns the return code."""
473
        if not callable(a_callable):
474
            raise ValueError("a_callable must be callable.")
475
        if stdin is None:
476
            stdin = StringIO("")
477
        if stdout is None:
974.1.70 by Aaron Bentley
Fixed selftest spewage (Brian M. Carlson)
478
            if hasattr(self, "_log_file"):
479
                stdout = self._log_file
480
            else:
481
                stdout = StringIO()
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
482
        if stderr is None:
974.1.70 by Aaron Bentley
Fixed selftest spewage (Brian M. Carlson)
483
            if hasattr(self, "_log_file"):
484
                stderr = self._log_file
485
            else:
486
                stderr = StringIO()
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
487
        real_stdin = sys.stdin
488
        real_stdout = sys.stdout
489
        real_stderr = sys.stderr
490
        try:
491
            sys.stdout = stdout
492
            sys.stderr = stderr
493
            sys.stdin = stdin
1160 by Martin Pool
- tiny refactoring
494
            return a_callable(*args, **kwargs)
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
495
        finally:
496
            sys.stdout = real_stdout
497
            sys.stderr = real_stderr
498
            sys.stdin = real_stdin
499
500
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
501
BzrTestBase = TestCase
502
503
     
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
504
class TestCaseInTempDir(TestCase):
505
    """Derived class that runs a test within a temporary directory.
506
507
    This is useful for tests that need to create a branch, etc.
508
509
    The directory is created in a slightly complex way: for each
510
    Python invocation, a new temporary top-level directory is created.
511
    All test cases create their own directory within that.  If the
512
    tests complete successfully, the directory is removed.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
513
514
    InTempDir is an old alias for FunctionalTestCase.
515
    """
516
517
    TEST_ROOT = None
518
    _TEST_NAME = 'test'
519
    OVERRIDE_PYTHON = 'python'
520
521
    def check_file_contents(self, filename, expect):
522
        self.log("check contents of file %s" % filename)
523
        contents = file(filename, 'r').read()
524
        if contents != expect:
525
            self.log("expected: %r" % expect)
526
            self.log("actually: %r" % contents)
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
527
            self.fail("contents of %s not as expected" % filename)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
528
529
    def _make_test_root(self):
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
530
        if TestCaseInTempDir.TEST_ROOT is not None:
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
531
            return
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
532
        i = 0
533
        while True:
1185.16.147 by Martin Pool
[patch] Test base directory must be unicode (from Alexander)
534
            root = u'test%04d.tmp' % i
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
535
            try:
536
                os.mkdir(root)
537
            except OSError, e:
538
                if e.errno == errno.EEXIST:
539
                    i += 1
540
                    continue
541
                else:
542
                    raise
543
            # successfully created
1185.31.37 by John Arbash Meinel
Switched os.path.abspath and os.path.realpath to osutils.* (still passes on cygwin)
544
            TestCaseInTempDir.TEST_ROOT = osutils.abspath(root)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
545
            break
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
546
        # make a fake bzr directory there to prevent any tests propagating
547
        # up onto the source directory's real branch
1185.31.33 by John Arbash Meinel
A couple more path.join statements needed changing.
548
        os.mkdir(osutils.pathjoin(TestCaseInTempDir.TEST_ROOT, '.bzr'))
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
549
550
    def setUp(self):
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
551
        super(TestCaseInTempDir, self).setUp()
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
552
        self._make_test_root()
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
553
        _currentdir = os.getcwdu()
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
554
        short_id = self.id().replace('bzrlib.tests.', '') \
1218 by Martin Pool
- fix up import
555
                   .replace('__main__.', '')
1185.31.33 by John Arbash Meinel
A couple more path.join statements needed changing.
556
        self.test_dir = osutils.pathjoin(self.TEST_ROOT, short_id)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
557
        os.mkdir(self.test_dir)
558
        os.chdir(self.test_dir)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
559
        os.environ['HOME'] = self.test_dir
1185.31.39 by John Arbash Meinel
Replacing os.getcwdu() with osutils.getcwd(),
560
        os.environ['APPDATA'] = self.test_dir
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
561
        def _leaveDirectory():
562
            os.chdir(_currentdir)
563
        self.addCleanup(_leaveDirectory)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
564
        
1185.38.7 by John Arbash Meinel
Updated build_tree to use fixed line-endings for tests which read the file contents and compare
565
    def build_tree(self, shape, line_endings='native'):
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
566
        """Build a test tree according to a pattern.
567
568
        shape is a sequence of file specifications.  If the final
569
        character is '/', a directory is created.
570
571
        This doesn't add anything to a branch.
1185.38.7 by John Arbash Meinel
Updated build_tree to use fixed line-endings for tests which read the file contents and compare
572
        :param line_endings: Either 'binary' or 'native'
573
                             in binary mode, exact contents are written
574
                             in native mode, the line endings match the
575
                             default platform endings.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
576
        """
577
        # XXX: It's OK to just create them using forward slashes on windows?
578
        for name in shape:
1185.16.145 by Martin Pool
Remove all assert statements from test cases.
579
            self.assert_(isinstance(name, basestring))
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
580
            if name[-1] == '/':
581
                os.mkdir(name[:-1])
582
            else:
1185.38.7 by John Arbash Meinel
Updated build_tree to use fixed line-endings for tests which read the file contents and compare
583
                if line_endings == 'binary':
584
                    f = file(name, 'wb')
585
                elif line_endings == 'native':
586
                    f = file(name, 'wt')
587
                else:
588
                    raise BzrError('Invalid line ending request %r' % (line_endings,))
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
589
                print >>f, "contents of", name
590
                f.close()
591
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
592
    def build_tree_contents(self, shape):
1514 by Robert Collins
Unbreak self.build_tree_shape in tests.
593
        build_tree_contents(shape)
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
594
1405 by Robert Collins
remove some of the upgrade code that was duplicated with inventory_entry, and give all inventory entries a weave
595
    def failUnlessExists(self, path):
596
        """Fail unless path, which may be abs or relative, exists."""
1448 by Robert Collins
revert symlinks correctly
597
        self.failUnless(osutils.lexists(path))
1185.31.40 by John Arbash Meinel
Added osutils.mkdtemp()
598
599
    def failIfExists(self, path):
600
        """Fail if path, which may be abs or relative, exists."""
601
        self.failIf(osutils.lexists(path))
1405 by Robert Collins
remove some of the upgrade code that was duplicated with inventory_entry, and give all inventory entries a weave
602
        
1442.1.70 by Robert Collins
Add assertFileEqual to TestCaseInTempDir.
603
    def assertFileEqual(self, content, path):
604
        """Fail if path does not contain 'content'."""
605
        self.failUnless(osutils.lexists(path))
606
        self.assertEqualDiff(content, open(path, 'r').read())
1185.31.40 by John Arbash Meinel
Added osutils.mkdtemp()
607
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
608
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
609
def filter_suite_by_re(suite, pattern):
1185.33.74 by Martin Pool
pychecker cleanups
610
    result = TestSuite()
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
611
    filter_re = re.compile(pattern)
612
    for test in iter_suite_tests(suite):
1185.1.57 by Robert Collins
nuke --pattern to selftest, replace with regexp.search calls.
613
        if filter_re.search(test.id()):
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
614
            result.addTest(test)
615
    return result
616
617
1185.16.58 by mbp at sourcefrog
- run all selftests by default
618
def run_suite(suite, name='test', verbose=False, pattern=".*",
1185.35.20 by Aaron Bentley
Only keep test failure directories if --keep-output is specified
619
              stop_on_failure=False, keep_output=False):
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
620
    TestCaseInTempDir._TEST_NAME = name
621
    if verbose:
622
        verbosity = 2
623
    else:
624
        verbosity = 1
625
    runner = TextTestRunner(stream=sys.stdout,
626
                            descriptions=0,
627
                            verbosity=verbosity)
1185.16.58 by mbp at sourcefrog
- run all selftests by default
628
    runner.stop_on_failure=stop_on_failure
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
629
    if pattern != '.*':
630
        suite = filter_suite_by_re(suite, pattern)
631
    result = runner.run(suite)
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
632
    # This is still a little bogus, 
633
    # but only a little. Folk not using our testrunner will
634
    # have to delete their temp directories themselves.
1185.35.20 by Aaron Bentley
Only keep test failure directories if --keep-output is specified
635
    if result.wasSuccessful() or not keep_output:
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
636
        if TestCaseInTempDir.TEST_ROOT is not None:
637
            shutil.rmtree(TestCaseInTempDir.TEST_ROOT) 
638
    else:
639
        print "Failed tests working directories are in '%s'\n" % TestCaseInTempDir.TEST_ROOT
640
    return result.wasSuccessful()
641
642
1185.35.20 by Aaron Bentley
Only keep test failure directories if --keep-output is specified
643
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
644
             keep_output=False):
1204 by Martin Pool
doc
645
    """Run the whole test suite under the enhanced runner"""
1185.16.58 by mbp at sourcefrog
- run all selftests by default
646
    return run_suite(test_suite(), 'testbzr', verbose=verbose, pattern=pattern,
1185.35.20 by Aaron Bentley
Only keep test failure directories if --keep-output is specified
647
                     stop_on_failure=stop_on_failure, keep_output=keep_output)
1092.1.17 by Robert Collins
remove TEST_CLASSES dead code and provide a bzrlib.test_suite() convenience method
648
649
650
def test_suite():
1204 by Martin Pool
doc
651
    """Build and return TestSuite for the whole program."""
721 by Martin Pool
- framework for running external commands from unittest suite
652
    from doctest import DocTestSuite
653
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
654
    global MODULES_TO_DOCTEST
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
655
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
656
    testmod_names = [ \
1518 by Robert Collins
Merge from mbp.
657
                   'bzrlib.tests.test_ancestry',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
658
                   'bzrlib.tests.test_annotate',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
659
                   'bzrlib.tests.test_api',
1518 by Robert Collins
Merge from mbp.
660
                   'bzrlib.tests.test_bad_files',
1185.50.21 by John Arbash Meinel
Added a test for basis-inventory, which should have happened before.
661
                   'bzrlib.tests.test_basis_inventory',
1518 by Robert Collins
Merge from mbp.
662
                   'bzrlib.tests.test_branch',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
663
                   'bzrlib.tests.test_command',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
664
                   'bzrlib.tests.test_commit',
665
                   'bzrlib.tests.test_commit_merge',
666
                   'bzrlib.tests.test_config',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
667
                   'bzrlib.tests.test_conflicts',
668
                   'bzrlib.tests.test_diff',
669
                   'bzrlib.tests.test_fetch',
1518 by Robert Collins
Merge from mbp.
670
                   'bzrlib.tests.test_gpg',
671
                   'bzrlib.tests.test_graph',
672
                   'bzrlib.tests.test_hashcache',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
673
                   'bzrlib.tests.test_http',
1518 by Robert Collins
Merge from mbp.
674
                   'bzrlib.tests.test_identitymap',
675
                   'bzrlib.tests.test_inv',
676
                   'bzrlib.tests.test_log',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
677
                   'bzrlib.tests.test_merge',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
678
                   'bzrlib.tests.test_merge3',
1518 by Robert Collins
Merge from mbp.
679
                   'bzrlib.tests.test_merge_core',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
680
                   'bzrlib.tests.test_missing',
1518 by Robert Collins
Merge from mbp.
681
                   'bzrlib.tests.test_msgeditor',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
682
                   'bzrlib.tests.test_nonascii',
1518 by Robert Collins
Merge from mbp.
683
                   'bzrlib.tests.test_options',
1185.50.20 by John Arbash Meinel
merge permissions branch, also fixup tests so they are lined up with bzr.dev to help prevent conflicts.
684
                   'bzrlib.tests.test_osutils',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
685
                   'bzrlib.tests.test_parent',
1185.58.1 by John Arbash Meinel
Added new permissions test (currently don't pass)
686
                   'bzrlib.tests.test_permissions',
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
687
                   'bzrlib.tests.test_plugins',
1185.33.92 by Martin Pool
[patch] fix for 'bzr rm -v' (Wouter van Heyst)
688
                   'bzrlib.tests.test_remove',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
689
                   'bzrlib.tests.test_revision',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
690
                   'bzrlib.tests.test_revisionnamespaces',
1518 by Robert Collins
Merge from mbp.
691
                   'bzrlib.tests.test_revprops',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
692
                   'bzrlib.tests.test_reweave',
1185.47.1 by Martin Pool
[broken] start converting basic_io to more rfc822-like format
693
                   'bzrlib.tests.test_rio',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
694
                   'bzrlib.tests.test_sampler',
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
695
                   'bzrlib.tests.test_selftest',
1185.33.89 by Martin Pool
[patch] add a selftest test that the setup build script works (Alexander Belchenko)
696
                   'bzrlib.tests.test_setup',
1185.50.20 by John Arbash Meinel
merge permissions branch, also fixup tests so they are lined up with bzr.dev to help prevent conflicts.
697
                   'bzrlib.tests.test_sftp_transport',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
698
                   'bzrlib.tests.test_smart_add',
1522 by Robert Collins
Test for the number of uses of self.working_tree() in branch.py
699
                   'bzrlib.tests.test_source',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
700
                   'bzrlib.tests.test_status',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
701
                   'bzrlib.tests.test_store',
1534.2.1 by Robert Collins
Implement deprecated_method
702
                   'bzrlib.tests.test_symbol_versioning',
1518 by Robert Collins
Merge from mbp.
703
                   'bzrlib.tests.test_testament',
704
                   'bzrlib.tests.test_trace',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
705
                   'bzrlib.tests.test_transactions',
706
                   'bzrlib.tests.test_transport',
707
                   'bzrlib.tests.test_tsort',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
708
                   'bzrlib.tests.test_ui',
709
                   'bzrlib.tests.test_uncommit',
710
                   'bzrlib.tests.test_upgrade',
711
                   'bzrlib.tests.test_weave',
712
                   'bzrlib.tests.test_whitebox',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
713
                   'bzrlib.tests.test_workingtree',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
714
                   'bzrlib.tests.test_xml',
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
715
                   ]
716
1185.31.33 by John Arbash Meinel
A couple more path.join statements needed changing.
717
    TestCase.BZRPATH = osutils.pathjoin(
718
            osutils.realpath(osutils.dirname(bzrlib.__path__[0])), 'bzr')
1185.31.57 by John Arbash Meinel
[merge] bzr.dev
719
    print '%10s: %s' % ('bzr', osutils.realpath(sys.argv[0]))
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
720
    print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
744 by Martin Pool
- show nicer descriptions while running tests
721
    print
721 by Martin Pool
- framework for running external commands from unittest suite
722
    suite = TestSuite()
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
723
    # python2.4's TestLoader.loadTestsFromNames gives very poor 
724
    # errors if it fails to load a named module - no indication of what's
725
    # actually wrong, just "no such module".  We should probably override that
726
    # class, but for the moment just load them ourselves. (mbp 20051202)
727
    loader = TestLoader()
728
    for mod_name in testmod_names:
729
        mod = _load_module_by_name(mod_name)
730
        suite.addTest(loader.loadTestsFromModule(mod))
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
731
    for package in packages_to_test():
732
        suite.addTest(package.test_suite())
855 by Martin Pool
- Patch from John to allow plugins to add their own tests.
733
    for m in MODULES_TO_TEST:
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
734
        suite.addTest(loader.loadTestsFromModule(m))
855 by Martin Pool
- Patch from John to allow plugins to add their own tests.
735
    for m in (MODULES_TO_DOCTEST):
721 by Martin Pool
- framework for running external commands from unittest suite
736
        suite.addTest(DocTestSuite(m))
1516 by Robert Collins
* bzrlib.plugin.all_plugins has been changed from an attribute to a
737
    for name, plugin in bzrlib.plugin.all_plugins().items():
738
        if hasattr(plugin, 'test_suite'):
739
            suite.addTest(plugin.test_suite())
1092.1.17 by Robert Collins
remove TEST_CLASSES dead code and provide a bzrlib.test_suite() convenience method
740
    return suite
764 by Martin Pool
- log messages from a particular test are printed if that test fails
741
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
742
743
def _load_module_by_name(mod_name):
744
    parts = mod_name.split('.')
745
    module = __import__(mod_name)
746
    del parts[0]
747
    # for historical reasons python returns the top-level module even though
748
    # it loads the submodule; we need to walk down to get the one we want.
749
    while parts:
750
        module = getattr(module, parts.pop(0))
751
    return module