~bzr-pqm/bzr/bzr.dev

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
1185.1.29 by Robert Collins
merge merge tweaks from aaron, which includes latest .dev
18
from cStringIO import StringIO
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
19
import difflib
20
import errno
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
21
import logging
22
import os
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
23
import re
24
import shutil
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
25
import sys
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
26
import tempfile
27
import unittest
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
28
import time
1185.52.1 by James Henstridge
Don't encode unicode messages to UTF-8 in mutter() (the stream writer does it).
29
import codecs
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
30
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
31
import bzrlib.branch
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
32
import bzrlib.commands
1514 by Robert Collins
Unbreak self.build_tree_shape in tests.
33
from bzrlib.errors import BzrError
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
34
import bzrlib.inventory
35
import bzrlib.merge3
36
import bzrlib.osutils
37
import bzrlib.osutils as osutils
38
import bzrlib.plugin
39
import bzrlib.store
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
40
import bzrlib.trace
1185.82.7 by John Arbash Meinel
Adding patches.py into bzrlib, including the tests into the test suite.
41
import bzrlib.changeset.serializer
1185.43.1 by Martin Pool
Remove direct logging calls from selftest
42
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
43
from bzrlib.tests.TestUtil import TestLoader, TestSuite
1514 by Robert Collins
Unbreak self.build_tree_shape in tests.
44
from bzrlib.tests.treeshape import build_tree_contents
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
45
855 by Martin Pool
- Patch from John to allow plugins to add their own tests.
46
MODULES_TO_TEST = []
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
47
MODULES_TO_DOCTEST = [
48
                      bzrlib.branch,
1185.82.7 by John Arbash Meinel
Adding patches.py into bzrlib, including the tests into the test suite.
49
                      bzrlib.changeset.serializer,
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
50
                      bzrlib.commands,
51
                      bzrlib.errors,
52
                      bzrlib.inventory,
53
                      bzrlib.merge3,
54
                      bzrlib.osutils,
55
                      bzrlib.store,
56
                      ]
1185.82.7 by John Arbash Meinel
Adding patches.py into bzrlib, including the tests into the test suite.
57
58
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
59
def packages_to_test():
60
    import bzrlib.tests.blackbox
1185.82.7 by John Arbash Meinel
Adding patches.py into bzrlib, including the tests into the test suite.
61
    import bzrlib.tests.changeset
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
62
    return [
1185.82.7 by John Arbash Meinel
Adding patches.py into bzrlib, including the tests into the test suite.
63
            bzrlib.tests.blackbox,
64
            bzrlib.tests.changeset
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
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
        """
1185.33.74 by Martin Pool
pychecker cleanups
370
        for cleanup_fn in reversed(self._cleanups):
371
            cleanup_fn()
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
372
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
373
    def log(self, *args):
1185.43.1 by Martin Pool
Remove direct logging calls from selftest
374
        mutter(*args)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
375
376
    def _get_log(self):
377
        """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
378
        if self._log_file_name:
379
            return open(self._log_file_name).read()
380
        else:
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
381
            return self._log_contents
1185.43.1 by Martin Pool
Remove direct logging calls from selftest
382
        # TODO: Delete the log after it's been read in
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
383
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
384
    def capture(self, cmd, retcode=0):
1185.3.26 by Martin Pool
- remove remaining external executions of bzr
385
        """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.
386
        return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
1185.3.26 by Martin Pool
- remove remaining external executions of bzr
387
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
388
    def run_bzr_captured(self, argv, retcode=0):
1185.22.7 by Michael Ellerman
Fix error in run_bzr_captured() doco
389
        """Invoke bzr and return (stdout, stderr).
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
390
391
        Useful for code that wants to check the contents of the
392
        output, the way error messages are presented, etc.
393
394
        This should be the main method for tests that want to exercise the
395
        overall behavior of the bzr application (rather than a unit test
396
        or a functional test of the library.)
397
398
        Much of the old code runs bzr by forking a new copy of Python, but
399
        that is slower, harder to debug, and generally not necessary.
400
1185.3.20 by Martin Pool
- run_bzr_captured also includes logged errors in
401
        This runs bzr through the interface that catches and reports
402
        errors, and with logging set to something approximating the
403
        default, so that error reporting can be checked.
404
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
405
        argv -- arguments to invoke bzr
406
        retcode -- expected return code, or None for don't-care.
407
        """
408
        stdout = StringIO()
409
        stderr = StringIO()
410
        self.log('run bzr: %s', ' '.join(argv))
1185.43.5 by Martin Pool
Update log message quoting
411
        # FIXME: don't call into logging here
1185.3.20 by Martin Pool
- run_bzr_captured also includes logged errors in
412
        handler = logging.StreamHandler(stderr)
413
        handler.setFormatter(bzrlib.trace.QuietFormatter())
414
        handler.setLevel(logging.INFO)
415
        logger = logging.getLogger('')
416
        logger.addHandler(handler)
417
        try:
418
            result = self.apply_redirected(None, stdout, stderr,
419
                                           bzrlib.commands.run_bzr_catch_errors,
420
                                           argv)
421
        finally:
422
            logger.removeHandler(handler)
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
423
        out = stdout.getvalue()
424
        err = stderr.getvalue()
425
        if out:
426
            self.log('output:\n%s', out)
427
        if err:
428
            self.log('errors:\n%s', err)
429
        if retcode is not None:
430
            self.assertEquals(result, retcode)
431
        return out, err
432
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
433
    def run_bzr(self, *args, **kwargs):
1119 by Martin Pool
doc
434
        """Invoke bzr, as if it were run from the command line.
435
436
        This should be the main method for tests that want to exercise the
437
        overall behavior of the bzr application (rather than a unit test
438
        or a functional test of the library.)
439
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
440
        This sends the stdout/stderr results into the test's log,
441
        where it may be useful for debugging.  See also run_captured.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
442
        """
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
443
        retcode = kwargs.pop('retcode', 0)
1185.3.21 by Martin Pool
TestBase.run_bzr doesn't need to be deprecated
444
        return self.run_bzr_captured(args, retcode)
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
445
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
446
    def check_inventory_shape(self, inv, shape):
1291 by Martin Pool
- add test for moving files between directories
447
        """Compare an inventory to a list of expected names.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
448
449
        Fail if they are not precisely equal.
450
        """
451
        extras = []
452
        shape = list(shape)             # copy
453
        for path, ie in inv.entries():
454
            name = path.replace('\\', '/')
455
            if ie.kind == 'dir':
456
                name = name + '/'
457
            if name in shape:
458
                shape.remove(name)
459
            else:
460
                extras.append(name)
461
        if shape:
462
            self.fail("expected paths not found in inventory: %r" % shape)
463
        if extras:
464
            self.fail("unexpected paths found in inventory: %r" % extras)
465
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
466
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
467
                         a_callable=None, *args, **kwargs):
468
        """Call callable with redirected std io pipes.
469
470
        Returns the return code."""
471
        if not callable(a_callable):
472
            raise ValueError("a_callable must be callable.")
473
        if stdin is None:
474
            stdin = StringIO("")
475
        if stdout is None:
974.1.70 by Aaron Bentley
Fixed selftest spewage (Brian M. Carlson)
476
            if hasattr(self, "_log_file"):
477
                stdout = self._log_file
478
            else:
479
                stdout = StringIO()
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
480
        if stderr is None:
974.1.70 by Aaron Bentley
Fixed selftest spewage (Brian M. Carlson)
481
            if hasattr(self, "_log_file"):
482
                stderr = self._log_file
483
            else:
484
                stderr = StringIO()
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
485
        real_stdin = sys.stdin
486
        real_stdout = sys.stdout
487
        real_stderr = sys.stderr
488
        try:
489
            sys.stdout = stdout
490
            sys.stderr = stderr
491
            sys.stdin = stdin
1160 by Martin Pool
- tiny refactoring
492
            return a_callable(*args, **kwargs)
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
493
        finally:
494
            sys.stdout = real_stdout
495
            sys.stderr = real_stderr
496
            sys.stdin = real_stdin
497
498
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
499
BzrTestBase = TestCase
500
501
     
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
502
class TestCaseInTempDir(TestCase):
503
    """Derived class that runs a test within a temporary directory.
504
505
    This is useful for tests that need to create a branch, etc.
506
507
    The directory is created in a slightly complex way: for each
508
    Python invocation, a new temporary top-level directory is created.
509
    All test cases create their own directory within that.  If the
510
    tests complete successfully, the directory is removed.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
511
512
    InTempDir is an old alias for FunctionalTestCase.
513
    """
514
515
    TEST_ROOT = None
516
    _TEST_NAME = 'test'
517
    OVERRIDE_PYTHON = 'python'
518
519
    def check_file_contents(self, filename, expect):
520
        self.log("check contents of file %s" % filename)
521
        contents = file(filename, 'r').read()
522
        if contents != expect:
523
            self.log("expected: %r" % expect)
524
            self.log("actually: %r" % contents)
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
525
            self.fail("contents of %s not as expected" % filename)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
526
527
    def _make_test_root(self):
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
528
        if TestCaseInTempDir.TEST_ROOT is not None:
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
529
            return
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
530
        i = 0
531
        while True:
1185.16.147 by Martin Pool
[patch] Test base directory must be unicode (from Alexander)
532
            root = u'test%04d.tmp' % i
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
533
            try:
534
                os.mkdir(root)
535
            except OSError, e:
536
                if e.errno == errno.EEXIST:
537
                    i += 1
538
                    continue
539
                else:
540
                    raise
541
            # successfully created
1185.31.37 by John Arbash Meinel
Switched os.path.abspath and os.path.realpath to osutils.* (still passes on cygwin)
542
            TestCaseInTempDir.TEST_ROOT = osutils.abspath(root)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
543
            break
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
544
        # make a fake bzr directory there to prevent any tests propagating
545
        # up onto the source directory's real branch
1185.31.33 by John Arbash Meinel
A couple more path.join statements needed changing.
546
        os.mkdir(osutils.pathjoin(TestCaseInTempDir.TEST_ROOT, '.bzr'))
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
547
548
    def setUp(self):
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
549
        super(TestCaseInTempDir, self).setUp()
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
550
        self._make_test_root()
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
551
        _currentdir = os.getcwdu()
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
552
        short_id = self.id().replace('bzrlib.tests.', '') \
1218 by Martin Pool
- fix up import
553
                   .replace('__main__.', '')
1185.31.33 by John Arbash Meinel
A couple more path.join statements needed changing.
554
        self.test_dir = osutils.pathjoin(self.TEST_ROOT, short_id)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
555
        os.mkdir(self.test_dir)
556
        os.chdir(self.test_dir)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
557
        os.environ['HOME'] = self.test_dir
1185.31.39 by John Arbash Meinel
Replacing os.getcwdu() with osutils.getcwd(),
558
        os.environ['APPDATA'] = self.test_dir
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
559
        def _leaveDirectory():
560
            os.chdir(_currentdir)
561
        self.addCleanup(_leaveDirectory)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
562
        
1185.38.7 by John Arbash Meinel
Updated build_tree to use fixed line-endings for tests which read the file contents and compare
563
    def build_tree(self, shape, line_endings='native'):
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
564
        """Build a test tree according to a pattern.
565
566
        shape is a sequence of file specifications.  If the final
567
        character is '/', a directory is created.
568
569
        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
570
        :param line_endings: Either 'binary' or 'native'
571
                             in binary mode, exact contents are written
572
                             in native mode, the line endings match the
573
                             default platform endings.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
574
        """
575
        # XXX: It's OK to just create them using forward slashes on windows?
576
        for name in shape:
1185.16.145 by Martin Pool
Remove all assert statements from test cases.
577
            self.assert_(isinstance(name, basestring))
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
578
            if name[-1] == '/':
579
                os.mkdir(name[:-1])
580
            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
581
                if line_endings == 'binary':
582
                    f = file(name, 'wb')
583
                elif line_endings == 'native':
584
                    f = file(name, 'wt')
585
                else:
586
                    raise BzrError('Invalid line ending request %r' % (line_endings,))
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
587
                print >>f, "contents of", name
588
                f.close()
589
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
590
    def build_tree_contents(self, shape):
1514 by Robert Collins
Unbreak self.build_tree_shape in tests.
591
        build_tree_contents(shape)
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
592
1405 by Robert Collins
remove some of the upgrade code that was duplicated with inventory_entry, and give all inventory entries a weave
593
    def failUnlessExists(self, path):
594
        """Fail unless path, which may be abs or relative, exists."""
1448 by Robert Collins
revert symlinks correctly
595
        self.failUnless(osutils.lexists(path))
1185.31.40 by John Arbash Meinel
Added osutils.mkdtemp()
596
597
    def failIfExists(self, path):
598
        """Fail if path, which may be abs or relative, exists."""
599
        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
600
        
1442.1.70 by Robert Collins
Add assertFileEqual to TestCaseInTempDir.
601
    def assertFileEqual(self, content, path):
602
        """Fail if path does not contain 'content'."""
603
        self.failUnless(osutils.lexists(path))
604
        self.assertEqualDiff(content, open(path, 'r').read())
1185.31.40 by John Arbash Meinel
Added osutils.mkdtemp()
605
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
606
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
607
def filter_suite_by_re(suite, pattern):
1185.33.74 by Martin Pool
pychecker cleanups
608
    result = TestSuite()
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
609
    filter_re = re.compile(pattern)
610
    for test in iter_suite_tests(suite):
1185.1.57 by Robert Collins
nuke --pattern to selftest, replace with regexp.search calls.
611
        if filter_re.search(test.id()):
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
612
            result.addTest(test)
613
    return result
614
615
1185.16.58 by mbp at sourcefrog
- run all selftests by default
616
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
617
              stop_on_failure=False, keep_output=False):
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
618
    TestCaseInTempDir._TEST_NAME = name
619
    if verbose:
620
        verbosity = 2
621
    else:
622
        verbosity = 1
623
    runner = TextTestRunner(stream=sys.stdout,
624
                            descriptions=0,
625
                            verbosity=verbosity)
1185.16.58 by mbp at sourcefrog
- run all selftests by default
626
    runner.stop_on_failure=stop_on_failure
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
627
    if pattern != '.*':
628
        suite = filter_suite_by_re(suite, pattern)
629
    result = runner.run(suite)
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
630
    # This is still a little bogus, 
631
    # but only a little. Folk not using our testrunner will
632
    # have to delete their temp directories themselves.
1185.35.20 by Aaron Bentley
Only keep test failure directories if --keep-output is specified
633
    if result.wasSuccessful() or not keep_output:
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
634
        if TestCaseInTempDir.TEST_ROOT is not None:
635
            shutil.rmtree(TestCaseInTempDir.TEST_ROOT) 
636
    else:
637
        print "Failed tests working directories are in '%s'\n" % TestCaseInTempDir.TEST_ROOT
638
    return result.wasSuccessful()
639
640
1185.35.20 by Aaron Bentley
Only keep test failure directories if --keep-output is specified
641
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
642
             keep_output=False):
1204 by Martin Pool
doc
643
    """Run the whole test suite under the enhanced runner"""
1185.16.58 by mbp at sourcefrog
- run all selftests by default
644
    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
645
                     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
646
647
648
def test_suite():
1204 by Martin Pool
doc
649
    """Build and return TestSuite for the whole program."""
721 by Martin Pool
- framework for running external commands from unittest suite
650
    from doctest import DocTestSuite
651
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
652
    global MODULES_TO_DOCTEST
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
653
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
654
    testmod_names = [ \
1518 by Robert Collins
Merge from mbp.
655
                   'bzrlib.tests.test_ancestry',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
656
                   '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
657
                   'bzrlib.tests.test_api',
1518 by Robert Collins
Merge from mbp.
658
                   'bzrlib.tests.test_bad_files',
1185.50.21 by John Arbash Meinel
Added a test for basis-inventory, which should have happened before.
659
                   'bzrlib.tests.test_basis_inventory',
1518 by Robert Collins
Merge from mbp.
660
                   'bzrlib.tests.test_branch',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
661
                   '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
662
                   'bzrlib.tests.test_commit',
663
                   'bzrlib.tests.test_commit_merge',
664
                   'bzrlib.tests.test_config',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
665
                   'bzrlib.tests.test_conflicts',
666
                   'bzrlib.tests.test_diff',
667
                   'bzrlib.tests.test_fetch',
1518 by Robert Collins
Merge from mbp.
668
                   'bzrlib.tests.test_gpg',
669
                   'bzrlib.tests.test_graph',
670
                   'bzrlib.tests.test_hashcache',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
671
                   'bzrlib.tests.test_http',
1518 by Robert Collins
Merge from mbp.
672
                   'bzrlib.tests.test_identitymap',
673
                   'bzrlib.tests.test_inv',
674
                   'bzrlib.tests.test_log',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
675
                   '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
676
                   'bzrlib.tests.test_merge3',
1518 by Robert Collins
Merge from mbp.
677
                   'bzrlib.tests.test_merge_core',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
678
                   'bzrlib.tests.test_missing',
1518 by Robert Collins
Merge from mbp.
679
                   '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
680
                   'bzrlib.tests.test_nonascii',
1518 by Robert Collins
Merge from mbp.
681
                   '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.
682
                   'bzrlib.tests.test_osutils',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
683
                   'bzrlib.tests.test_parent',
1185.58.1 by John Arbash Meinel
Added new permissions test (currently don't pass)
684
                   'bzrlib.tests.test_permissions',
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
685
                   'bzrlib.tests.test_plugins',
1185.33.92 by Martin Pool
[patch] fix for 'bzr rm -v' (Wouter van Heyst)
686
                   '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
687
                   'bzrlib.tests.test_revision',
688
                   'bzrlib.tests.test_revision_info',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
689
                   'bzrlib.tests.test_revisionnamespaces',
1518 by Robert Collins
Merge from mbp.
690
                   '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
691
                   'bzrlib.tests.test_reweave',
1185.47.1 by Martin Pool
[broken] start converting basic_io to more rfc822-like format
692
                   'bzrlib.tests.test_rio',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
693
                   'bzrlib.tests.test_sampler',
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
694
                   'bzrlib.tests.test_selftest',
1185.33.89 by Martin Pool
[patch] add a selftest test that the setup build script works (Alexander Belchenko)
695
                   '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.
696
                   '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
697
                   'bzrlib.tests.test_smart_add',
1522 by Robert Collins
Test for the number of uses of self.working_tree() in branch.py
698
                   'bzrlib.tests.test_source',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
699
                   '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
700
                   'bzrlib.tests.test_store',
1518 by Robert Collins
Merge from mbp.
701
                   'bzrlib.tests.test_testament',
702
                   '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
703
                   'bzrlib.tests.test_transactions',
704
                   'bzrlib.tests.test_transport',
705
                   'bzrlib.tests.test_tsort',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
706
                   'bzrlib.tests.test_ui',
707
                   'bzrlib.tests.test_uncommit',
708
                   'bzrlib.tests.test_upgrade',
709
                   'bzrlib.tests.test_weave',
710
                   '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
711
                   'bzrlib.tests.test_workingtree',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
712
                   'bzrlib.tests.test_xml',
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
713
                   ]
714
1185.31.33 by John Arbash Meinel
A couple more path.join statements needed changing.
715
    TestCase.BZRPATH = osutils.pathjoin(
716
            osutils.realpath(osutils.dirname(bzrlib.__path__[0])), 'bzr')
1185.31.57 by John Arbash Meinel
[merge] bzr.dev
717
    print '%10s: %s' % ('bzr', osutils.realpath(sys.argv[0]))
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
718
    print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
744 by Martin Pool
- show nicer descriptions while running tests
719
    print
721 by Martin Pool
- framework for running external commands from unittest suite
720
    suite = TestSuite()
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
721
    # python2.4's TestLoader.loadTestsFromNames gives very poor 
722
    # errors if it fails to load a named module - no indication of what's
723
    # actually wrong, just "no such module".  We should probably override that
724
    # class, but for the moment just load them ourselves. (mbp 20051202)
725
    loader = TestLoader()
726
    for mod_name in testmod_names:
727
        mod = _load_module_by_name(mod_name)
728
        suite.addTest(loader.loadTestsFromModule(mod))
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
729
    for package in packages_to_test():
730
        suite.addTest(package.test_suite())
855 by Martin Pool
- Patch from John to allow plugins to add their own tests.
731
    for m in MODULES_TO_TEST:
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
732
        suite.addTest(loader.loadTestsFromModule(m))
855 by Martin Pool
- Patch from John to allow plugins to add their own tests.
733
    for m in (MODULES_TO_DOCTEST):
721 by Martin Pool
- framework for running external commands from unittest suite
734
        suite.addTest(DocTestSuite(m))
1516 by Robert Collins
* bzrlib.plugin.all_plugins has been changed from an attribute to a
735
    for name, plugin in bzrlib.plugin.all_plugins().items():
736
        if hasattr(plugin, 'test_suite'):
737
            suite.addTest(plugin.test_suite())
1092.1.17 by Robert Collins
remove TEST_CLASSES dead code and provide a bzrlib.test_suite() convenience method
738
    return suite
764 by Martin Pool
- log messages from a particular test are printed if that test fails
739
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
740
741
def _load_module_by_name(mod_name):
742
    parts = mod_name.split('.')
743
    module = __import__(mod_name)
744
    del parts[0]
745
    # for historical reasons python returns the top-level module even though
746
    # it loads the submodule; we need to walk down to get the one we want.
747
    while parts:
748
        module = getattr(module, parts.pop(0))
749
    return module