~bzr-pqm/bzr/bzr.dev

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