~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
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
30
import bzrlib.commands
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
31
import bzrlib.trace
974.1.27 by aaron.bentley at utoronto
Initial greedy fetch work
32
import bzrlib.fetch
1448 by Robert Collins
revert symlinks correctly
33
import bzrlib.osutils as osutils
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
34
from bzrlib.selftest import TestUtil
35
from bzrlib.selftest.TestUtil import TestLoader, TestSuite
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
36
from bzrlib.selftest.treeshape import build_tree_contents
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
37
855 by Martin Pool
- Patch from John to allow plugins to add their own tests.
38
MODULES_TO_TEST = []
39
MODULES_TO_DOCTEST = []
720 by Martin Pool
- start moving external tests into the testsuite framework
40
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
41
from logging import debug, warning, error
42
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
43
44
45
class EarlyStoppingTestResultAdapter(object):
46
    """An adapter for TestResult to stop at the first first failure or error"""
47
48
    def __init__(self, result):
49
        self._result = result
50
51
    def addError(self, test, err):
52
        self._result.addError(test, err)
53
        self._result.stop()
54
55
    def addFailure(self, test, err):
56
        self._result.addFailure(test, err)
57
        self._result.stop()
58
59
    def __getattr__(self, name):
60
        return getattr(self._result, name)
61
62
    def __setattr__(self, name, value):
63
        if name == '_result':
64
            object.__setattr__(self, name, value)
65
        return setattr(self._result, name, value)
66
67
68
class _MyResult(unittest._TextTestResult):
69
    """
70
    Custom TestResult.
71
72
    No special behaviour for now.
73
    """
74
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
75
    def _elapsedTime(self):
76
        return "(Took %.3fs)" % (time.time() - self._start_time)
77
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
78
    def startTest(self, test):
79
        unittest.TestResult.startTest(self, test)
80
        # TODO: Maybe show test.shortDescription somewhere?
81
        what = test.shortDescription() or test.id()        
82
        if self.showAll:
83
            self.stream.write('%-70.70s' % what)
84
        self.stream.flush()
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
85
        self._start_time = time.time()
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
86
87
    def addError(self, test, err):
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
88
        unittest.TestResult.addError(self, test, err)
89
        if self.showAll:
90
            self.stream.writeln("ERROR %s" % self._elapsedTime())
91
        elif self.dots:
92
            self.stream.write('E')
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
93
        self.stream.flush()
94
95
    def addFailure(self, test, err):
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
96
        unittest.TestResult.addFailure(self, test, err)
97
        if self.showAll:
98
            self.stream.writeln("FAIL %s" % self._elapsedTime())
99
        elif self.dots:
100
            self.stream.write('F')
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
101
        self.stream.flush()
102
103
    def addSuccess(self, test):
104
        if self.showAll:
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
105
            self.stream.writeln('OK %s' % self._elapsedTime())
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
106
        elif self.dots:
107
            self.stream.write('~')
108
        self.stream.flush()
109
        unittest.TestResult.addSuccess(self, test)
110
111
    def printErrorList(self, flavour, errors):
112
        for test, err in errors:
113
            self.stream.writeln(self.separator1)
114
            self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
115
            if hasattr(test, '_get_log'):
116
                self.stream.writeln()
117
                self.stream.writeln('log from this test:')
118
                print >>self.stream, test._get_log()
119
            self.stream.writeln(self.separator2)
120
            self.stream.writeln("%s" % err)
121
122
123
class TextTestRunner(unittest.TextTestRunner):
1185.16.58 by mbp at sourcefrog
- run all selftests by default
124
    stop_on_failure = False
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
125
126
    def _makeResult(self):
127
        result = _MyResult(self.stream, self.descriptions, self.verbosity)
1185.16.58 by mbp at sourcefrog
- run all selftests by default
128
        if self.stop_on_failure:
129
            result = EarlyStoppingTestResultAdapter(result)
130
        return result
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
131
132
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
133
def iter_suite_tests(suite):
134
    """Return all tests in a suite, recursing through nested suites"""
135
    for item in suite._tests:
136
        if isinstance(item, unittest.TestCase):
137
            yield item
138
        elif isinstance(item, unittest.TestSuite):
139
            for r in iter_suite_tests(item):
140
                yield r
141
        else:
142
            raise Exception('unknown object %r inside test suite %r'
143
                            % (item, suite))
144
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
145
146
class TestSkipped(Exception):
147
    """Indicates that a test was intentionally skipped, rather than failing."""
148
    # XXX: Not used yet
149
150
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
151
class CommandFailed(Exception):
152
    pass
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
153
154
class TestCase(unittest.TestCase):
155
    """Base class for bzr unit tests.
156
    
157
    Tests that need access to disk resources should subclass 
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
158
    TestCaseInTempDir not TestCase.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
159
160
    Error and debug log messages are redirected from their usual
161
    location into a temporary file, the contents of which can be
162
    retrieved by _get_log().
163
       
164
    There are also convenience functions to invoke bzr's command-line
165
    routine, and to build and check bzr trees."""
166
167
    BZRPATH = 'bzr'
1185.16.14 by Martin Pool
- make TestCase._get_log work even if setup was aborted
168
    _log_file_name = None
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
169
170
    def setUp(self):
171
        unittest.TestCase.setUp(self)
1442.1.55 by Robert Collins
move environment preservation up to the root test case, making it available to all tests
172
        self.oldenv = os.environ.get('HOME', None)
173
        os.environ['HOME'] = os.getcwd()
174
        self.bzr_email = os.environ.get('BZREMAIL')
175
        if self.bzr_email is not None:
176
            del os.environ['BZREMAIL']
177
        self.email = os.environ.get('EMAIL')
178
        if self.email is not None:
179
            del os.environ['EMAIL']
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
180
        bzrlib.trace.disable_default_logging()
181
        self._enable_file_logging()
182
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
183
    def _ndiff_strings(self, a, b):
184
        """Return ndiff between two strings containing lines."""
1185.16.21 by Martin Pool
- tweak diff shown by assertEqualDiff
185
        difflines = difflib.ndiff(a.splitlines(True),
186
                                  b.splitlines(True),
187
                                  linejunk=lambda x: False,
188
                                  charjunk=lambda x: False)
189
        return ''.join(difflines)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
190
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
191
    def assertEqualDiff(self, a, b):
192
        """Assert two texts are equal, if not raise an exception.
193
        
194
        This is intended for use with multi-line strings where it can 
195
        be hard to find the differences by eye.
196
        """
197
        # TODO: perhaps override assertEquals to call this for strings?
198
        if a == b:
199
            return
200
        raise AssertionError("texts not equal:\n" + 
201
                             self._ndiff_strings(a, b))      
1185.16.42 by Martin Pool
- Add assertContainsRe
202
203
    def assertContainsRe(self, haystack, needle_re):
204
        """Assert that a contains something matching a regular expression."""
205
        if not re.search(needle_re, haystack):
206
            raise AssertionError('pattern "%s" not found in "%s"'
207
                    % (needle_re, haystack))
1442.1.70 by Robert Collins
Add assertFileEqual to TestCaseInTempDir.
208
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
209
    def _enable_file_logging(self):
210
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
211
212
        self._log_file = os.fdopen(fileno, 'w+')
213
214
        hdlr = logging.StreamHandler(self._log_file)
215
        hdlr.setLevel(logging.DEBUG)
1215 by Martin Pool
- change trace format for test logs
216
        hdlr.setFormatter(logging.Formatter('%(levelname)8s  %(message)s'))
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
217
        logging.getLogger('').addHandler(hdlr)
218
        logging.getLogger('').setLevel(logging.DEBUG)
219
        self._log_hdlr = hdlr
220
        debug('opened log file %s', name)
221
        
222
        self._log_file_name = name
223
224
    def tearDown(self):
1442.1.55 by Robert Collins
move environment preservation up to the root test case, making it available to all tests
225
        os.environ['HOME'] = self.oldenv
226
        if os.environ.get('BZREMAIL') is not None:
227
            del os.environ['BZREMAIL']
228
        if self.bzr_email is not None:
229
            os.environ['BZREMAIL'] = self.bzr_email
230
        if os.environ.get('EMAIL') is not None:
231
            del os.environ['EMAIL']
232
        if self.email is not None:
233
            os.environ['EMAIL'] = self.email
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
234
        logging.getLogger('').removeHandler(self._log_hdlr)
235
        bzrlib.trace.enable_default_logging()
236
        logging.debug('%s teardown', self.id())
237
        self._log_file.close()
238
        unittest.TestCase.tearDown(self)
239
240
    def log(self, *args):
241
        logging.debug(*args)
242
243
    def _get_log(self):
244
        """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
245
        if self._log_file_name:
246
            return open(self._log_file_name).read()
247
        else:
248
            return ''
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
249
1185.3.26 by Martin Pool
- remove remaining external executions of bzr
250
    def capture(self, cmd):
251
        """Shortcut that splits cmd into words, runs, and returns stdout"""
252
        return self.run_bzr_captured(cmd.split())[0]
253
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
254
    def run_bzr_captured(self, argv, retcode=0):
255
        """Invoke bzr and return (result, stdout, stderr).
256
257
        Useful for code that wants to check the contents of the
258
        output, the way error messages are presented, etc.
259
260
        This should be the main method for tests that want to exercise the
261
        overall behavior of the bzr application (rather than a unit test
262
        or a functional test of the library.)
263
264
        Much of the old code runs bzr by forking a new copy of Python, but
265
        that is slower, harder to debug, and generally not necessary.
266
1185.3.20 by Martin Pool
- run_bzr_captured also includes logged errors in
267
        This runs bzr through the interface that catches and reports
268
        errors, and with logging set to something approximating the
269
        default, so that error reporting can be checked.
270
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
271
        argv -- arguments to invoke bzr
272
        retcode -- expected return code, or None for don't-care.
273
        """
274
        stdout = StringIO()
275
        stderr = StringIO()
276
        self.log('run bzr: %s', ' '.join(argv))
1185.3.20 by Martin Pool
- run_bzr_captured also includes logged errors in
277
        handler = logging.StreamHandler(stderr)
278
        handler.setFormatter(bzrlib.trace.QuietFormatter())
279
        handler.setLevel(logging.INFO)
280
        logger = logging.getLogger('')
281
        logger.addHandler(handler)
282
        try:
283
            result = self.apply_redirected(None, stdout, stderr,
284
                                           bzrlib.commands.run_bzr_catch_errors,
285
                                           argv)
286
        finally:
287
            logger.removeHandler(handler)
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
288
        out = stdout.getvalue()
289
        err = stderr.getvalue()
290
        if out:
291
            self.log('output:\n%s', out)
292
        if err:
293
            self.log('errors:\n%s', err)
294
        if retcode is not None:
295
            self.assertEquals(result, retcode)
296
        return out, err
297
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
298
    def run_bzr(self, *args, **kwargs):
1119 by Martin Pool
doc
299
        """Invoke bzr, as if it were run from the command line.
300
301
        This should be the main method for tests that want to exercise the
302
        overall behavior of the bzr application (rather than a unit test
303
        or a functional test of the library.)
304
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
305
        This sends the stdout/stderr results into the test's log,
306
        where it may be useful for debugging.  See also run_captured.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
307
        """
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
308
        retcode = kwargs.pop('retcode', 0)
1185.3.21 by Martin Pool
TestBase.run_bzr doesn't need to be deprecated
309
        return self.run_bzr_captured(args, retcode)
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
310
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
311
    def check_inventory_shape(self, inv, shape):
1291 by Martin Pool
- add test for moving files between directories
312
        """Compare an inventory to a list of expected names.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
313
314
        Fail if they are not precisely equal.
315
        """
316
        extras = []
317
        shape = list(shape)             # copy
318
        for path, ie in inv.entries():
319
            name = path.replace('\\', '/')
320
            if ie.kind == 'dir':
321
                name = name + '/'
322
            if name in shape:
323
                shape.remove(name)
324
            else:
325
                extras.append(name)
326
        if shape:
327
            self.fail("expected paths not found in inventory: %r" % shape)
328
        if extras:
329
            self.fail("unexpected paths found in inventory: %r" % extras)
330
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
331
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
332
                         a_callable=None, *args, **kwargs):
333
        """Call callable with redirected std io pipes.
334
335
        Returns the return code."""
336
        if not callable(a_callable):
337
            raise ValueError("a_callable must be callable.")
338
        if stdin is None:
339
            stdin = StringIO("")
340
        if stdout is None:
974.1.70 by Aaron Bentley
Fixed selftest spewage (Brian M. Carlson)
341
            if hasattr(self, "_log_file"):
342
                stdout = self._log_file
343
            else:
344
                stdout = StringIO()
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
345
        if stderr is None:
974.1.70 by Aaron Bentley
Fixed selftest spewage (Brian M. Carlson)
346
            if hasattr(self, "_log_file"):
347
                stderr = self._log_file
348
            else:
349
                stderr = StringIO()
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
350
        real_stdin = sys.stdin
351
        real_stdout = sys.stdout
352
        real_stderr = sys.stderr
353
        try:
354
            sys.stdout = stdout
355
            sys.stderr = stderr
356
            sys.stdin = stdin
1160 by Martin Pool
- tiny refactoring
357
            return a_callable(*args, **kwargs)
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
358
        finally:
359
            sys.stdout = real_stdout
360
            sys.stderr = real_stderr
361
            sys.stdin = real_stdin
362
363
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
364
BzrTestBase = TestCase
365
366
     
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
367
class TestCaseInTempDir(TestCase):
368
    """Derived class that runs a test within a temporary directory.
369
370
    This is useful for tests that need to create a branch, etc.
371
372
    The directory is created in a slightly complex way: for each
373
    Python invocation, a new temporary top-level directory is created.
374
    All test cases create their own directory within that.  If the
375
    tests complete successfully, the directory is removed.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
376
377
    InTempDir is an old alias for FunctionalTestCase.
378
    """
379
380
    TEST_ROOT = None
381
    _TEST_NAME = 'test'
382
    OVERRIDE_PYTHON = 'python'
383
384
    def check_file_contents(self, filename, expect):
385
        self.log("check contents of file %s" % filename)
386
        contents = file(filename, 'r').read()
387
        if contents != expect:
388
            self.log("expected: %r" % expect)
389
            self.log("actually: %r" % contents)
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
390
            self.fail("contents of %s not as expected" % filename)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
391
392
    def _make_test_root(self):
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
393
        if TestCaseInTempDir.TEST_ROOT is not None:
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
394
            return
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
395
        i = 0
396
        while True:
397
            root = 'test%04d.tmp' % i
398
            try:
399
                os.mkdir(root)
400
            except OSError, e:
401
                if e.errno == errno.EEXIST:
402
                    i += 1
403
                    continue
404
                else:
405
                    raise
406
            # successfully created
407
            TestCaseInTempDir.TEST_ROOT = os.path.abspath(root)
408
            break
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
409
        # make a fake bzr directory there to prevent any tests propagating
410
        # up onto the source directory's real branch
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
411
        os.mkdir(os.path.join(TestCaseInTempDir.TEST_ROOT, '.bzr'))
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
412
413
    def setUp(self):
414
        self._make_test_root()
415
        self._currentdir = os.getcwdu()
1218 by Martin Pool
- fix up import
416
        short_id = self.id().replace('bzrlib.selftest.', '') \
417
                   .replace('__main__.', '')
1212 by Martin Pool
- use shorter test directory names
418
        self.test_dir = os.path.join(self.TEST_ROOT, short_id)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
419
        os.mkdir(self.test_dir)
420
        os.chdir(self.test_dir)
1442.1.55 by Robert Collins
move environment preservation up to the root test case, making it available to all tests
421
        super(TestCaseInTempDir, self).setUp()
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
422
        
423
    def tearDown(self):
424
        os.chdir(self._currentdir)
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
425
        super(TestCaseInTempDir, self).tearDown()
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
426
427
    def build_tree(self, shape):
428
        """Build a test tree according to a pattern.
429
430
        shape is a sequence of file specifications.  If the final
431
        character is '/', a directory is created.
432
433
        This doesn't add anything to a branch.
434
        """
435
        # XXX: It's OK to just create them using forward slashes on windows?
436
        for name in shape:
437
            assert isinstance(name, basestring)
438
            if name[-1] == '/':
439
                os.mkdir(name[:-1])
440
            else:
441
                f = file(name, 'wt')
442
                print >>f, "contents of", name
443
                f.close()
444
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
445
    def build_tree_contents(self, shape):
446
        bzrlib.selftest.build_tree_contents(shape)
447
1405 by Robert Collins
remove some of the upgrade code that was duplicated with inventory_entry, and give all inventory entries a weave
448
    def failUnlessExists(self, path):
449
        """Fail unless path, which may be abs or relative, exists."""
1448 by Robert Collins
revert symlinks correctly
450
        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
451
        
1442.1.70 by Robert Collins
Add assertFileEqual to TestCaseInTempDir.
452
    def assertFileEqual(self, content, path):
453
        """Fail if path does not contain 'content'."""
454
        self.failUnless(osutils.lexists(path))
455
        self.assertEqualDiff(content, open(path, 'r').read())
456
        
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
457
458
class MetaTestLog(TestCase):
459
    def test_logging(self):
460
        """Test logs are captured when a test fails."""
461
        logging.info('an info message')
462
        warning('something looks dodgy...')
463
        logging.debug('hello, test is running')
1185.16.59 by mbp at sourcefrog
- store revprops in testaments
464
        ## assert 0
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
465
466
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
467
def filter_suite_by_re(suite, pattern):
468
    result = TestUtil.TestSuite()
469
    filter_re = re.compile(pattern)
470
    for test in iter_suite_tests(suite):
1185.1.57 by Robert Collins
nuke --pattern to selftest, replace with regexp.search calls.
471
        if filter_re.search(test.id()):
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
472
            result.addTest(test)
473
    return result
474
475
1185.16.58 by mbp at sourcefrog
- run all selftests by default
476
def run_suite(suite, name='test', verbose=False, pattern=".*",
477
              stop_on_failure=False):
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
478
    TestCaseInTempDir._TEST_NAME = name
479
    if verbose:
480
        verbosity = 2
481
    else:
482
        verbosity = 1
483
    runner = TextTestRunner(stream=sys.stdout,
484
                            descriptions=0,
485
                            verbosity=verbosity)
1185.16.58 by mbp at sourcefrog
- run all selftests by default
486
    runner.stop_on_failure=stop_on_failure
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
487
    if pattern != '.*':
488
        suite = filter_suite_by_re(suite, pattern)
489
    result = runner.run(suite)
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
490
    # This is still a little bogus, 
491
    # but only a little. Folk not using our testrunner will
492
    # have to delete their temp directories themselves.
493
    if result.wasSuccessful():
494
        if TestCaseInTempDir.TEST_ROOT is not None:
495
            shutil.rmtree(TestCaseInTempDir.TEST_ROOT) 
496
    else:
497
        print "Failed tests working directories are in '%s'\n" % TestCaseInTempDir.TEST_ROOT
498
    return result.wasSuccessful()
499
500
1185.16.58 by mbp at sourcefrog
- run all selftests by default
501
def selftest(verbose=False, pattern=".*", stop_on_failure=True):
1204 by Martin Pool
doc
502
    """Run the whole test suite under the enhanced runner"""
1185.16.58 by mbp at sourcefrog
- run all selftests by default
503
    return run_suite(test_suite(), 'testbzr', verbose=verbose, pattern=pattern,
504
                     stop_on_failure=stop_on_failure)
1092.1.17 by Robert Collins
remove TEST_CLASSES dead code and provide a bzrlib.test_suite() convenience method
505
506
507
def test_suite():
1204 by Martin Pool
doc
508
    """Build and return TestSuite for the whole program."""
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
509
    import bzrlib.store, bzrlib.inventory, bzrlib.branch
510
    import bzrlib.osutils, bzrlib.merge3, bzrlib.plugin
721 by Martin Pool
- framework for running external commands from unittest suite
511
    from doctest import DocTestSuite
512
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
513
    global MODULES_TO_TEST, MODULES_TO_DOCTEST
514
515
    testmod_names = \
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
516
                  ['bzrlib.selftest.MetaTestLog',
1442.1.55 by Robert Collins
move environment preservation up to the root test case, making it available to all tests
517
                   'bzrlib.selftest.testgpg',
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
518
                   'bzrlib.selftest.testidentitymap',
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
519
                   'bzrlib.selftest.testinv',
1390 by Robert Collins
pair programming worx... merge integration and weave
520
                   'bzrlib.selftest.test_ancestry',
1251 by Martin Pool
- fix up commit in directory with some deleted files
521
                   'bzrlib.selftest.test_commit',
1342 by Martin Pool
- start some tests for commit of merge revisions
522
                   'bzrlib.selftest.test_commit_merge',
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
523
                   'bzrlib.selftest.testconfig',
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
524
                   'bzrlib.selftest.versioning',
525
                   'bzrlib.selftest.testmerge3',
974.1.80 by Aaron Bentley
Improved merge error handling and testing
526
                   'bzrlib.selftest.testmerge',
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
527
                   'bzrlib.selftest.testhashcache',
528
                   'bzrlib.selftest.teststatus',
529
                   'bzrlib.selftest.testlog',
530
                   'bzrlib.selftest.testrevisionnamespaces',
531
                   'bzrlib.selftest.testbranch',
1270 by Martin Pool
- fix recording of merged ancestry lines
532
                   'bzrlib.selftest.testrevision',
1185.5.4 by John Arbash Meinel
Updated bzr revision-info, created tests.
533
                   'bzrlib.selftest.test_revision_info',
1277 by Martin Pool
- turn on merge_core tests again
534
                   'bzrlib.selftest.test_merge_core',
1092.1.26 by Robert Collins
start writing star-topology test, realise we need smart-add change
535
                   'bzrlib.selftest.test_smart_add',
1185.3.29 by John Arbash Meinel
Added test cases for handling bogus files.
536
                   'bzrlib.selftest.test_bad_files',
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
537
                   'bzrlib.selftest.testdiff',
1273 by Martin Pool
- fix up copy_branch, etc
538
                   'bzrlib.selftest.test_parent',
1181 by Martin Pool
- add test for deserialization from a canned XML inventory
539
                   'bzrlib.selftest.test_xml',
1234 by Martin Pool
- run weave tests from bzr selftest
540
                   'bzrlib.selftest.test_weave',
1274 by Martin Pool
- stub out obsolete fetch tests
541
                   'bzrlib.selftest.testfetch',
1281 by Martin Pool
- reenable whitebox tests
542
                   'bzrlib.selftest.whitebox',
974.1.44 by aaron.bentley at utoronto
Added test of double-add in ImmutableStore
543
                   'bzrlib.selftest.teststore',
1288 by Martin Pool
- reenable blackbox tests - everything passes!
544
                   'bzrlib.selftest.blackbox',
1417.1.2 by Robert Collins
add sample test
545
                   'bzrlib.selftest.testsampler',
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
546
                   'bzrlib.selftest.testtransactions',
1185.11.1 by John Arbash Meinel
(broken) Transport work is merged in. Tests do not pass yet.
547
                   'bzrlib.selftest.testtransport',
974.1.57 by aaron.bentley at utoronto
Started work on djkstra longest-path algorithm
548
                   'bzrlib.selftest.testgraph',
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
549
                   'bzrlib.selftest.testworkingtree',
1393.1.31 by Martin Pool
- add simple test for upgrade
550
                   'bzrlib.selftest.test_upgrade',
1185.14.8 by Aaron Bentley
Added test_commit.py
551
                   'bzrlib.selftest.test_conflicts',
1185.16.12 by Martin Pool
- basic testament class
552
                   'bzrlib.selftest.testtestament',
1185.16.32 by Martin Pool
- add a basic annotate built-in command
553
                   'bzrlib.selftest.testannotate',
1185.16.35 by Martin Pool
- stub for revision properties
554
                   'bzrlib.selftest.testrevprops',
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
555
                   'bzrlib.selftest.testoptions',
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
556
                   ]
557
855 by Martin Pool
- Patch from John to allow plugins to add their own tests.
558
    for m in (bzrlib.store, bzrlib.inventory, bzrlib.branch,
559
              bzrlib.osutils, bzrlib.commands, bzrlib.merge3):
560
        if m not in MODULES_TO_DOCTEST:
561
            MODULES_TO_DOCTEST.append(m)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
562
1102 by Martin Pool
- merge test refactoring from robertc
563
    TestCase.BZRPATH = os.path.join(os.path.realpath(os.path.dirname(bzrlib.__path__[0])), 'bzr')
564
    print '%-30s %s' % ('bzr binary', TestCase.BZRPATH)
744 by Martin Pool
- show nicer descriptions while running tests
565
    print
721 by Martin Pool
- framework for running external commands from unittest suite
566
    suite = TestSuite()
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
567
    suite.addTest(TestLoader().loadTestsFromNames(testmod_names))
855 by Martin Pool
- Patch from John to allow plugins to add their own tests.
568
    for m in MODULES_TO_TEST:
569
         suite.addTest(TestLoader().loadTestsFromModule(m))
570
    for m in (MODULES_TO_DOCTEST):
721 by Martin Pool
- framework for running external commands from unittest suite
571
        suite.addTest(DocTestSuite(m))
908 by Martin Pool
- merge john's plugins-have-test_suite.patch:
572
    for p in bzrlib.plugin.all_plugins:
573
        if hasattr(p, 'test_suite'):
574
            suite.addTest(p.test_suite())
1092.1.17 by Robert Collins
remove TEST_CLASSES dead code and provide a bzrlib.test_suite() convenience method
575
    return suite
764 by Martin Pool
- log messages from a particular test are printed if that test fails
576