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