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