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