~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/selftest/__init__.py

  • Committer: Robert Collins
  • Date: 2005-10-08 00:32:39 UTC
  • mfrom: (1185.13.4)
  • mto: This revision was merged to the branch mainline in revision 1422.
  • Revision ID: robertc@robertcollins.net-20051008003239-b4e2f1ad62bbe3f6
merge in reweave support

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
 
18
from cStringIO import StringIO
18
19
import logging
19
20
import unittest
20
21
import tempfile
23
24
import errno
24
25
import subprocess
25
26
import shutil
 
27
import re
26
28
 
27
 
import testsweet
28
29
import bzrlib.commands
29
 
 
30
30
import bzrlib.trace
31
31
import bzrlib.fetch
 
32
from bzrlib.selftest import TestUtil
 
33
from bzrlib.selftest.TestUtil import TestLoader, TestSuite
32
34
 
33
35
 
34
36
MODULES_TO_TEST = []
36
38
 
37
39
from logging import debug, warning, error
38
40
 
 
41
 
 
42
 
 
43
class EarlyStoppingTestResultAdapter(object):
 
44
    """An adapter for TestResult to stop at the first first failure or error"""
 
45
 
 
46
    def __init__(self, result):
 
47
        self._result = result
 
48
 
 
49
    def addError(self, test, err):
 
50
        self._result.addError(test, err)
 
51
        self._result.stop()
 
52
 
 
53
    def addFailure(self, test, err):
 
54
        self._result.addFailure(test, err)
 
55
        self._result.stop()
 
56
 
 
57
    def __getattr__(self, name):
 
58
        return getattr(self._result, name)
 
59
 
 
60
    def __setattr__(self, name, value):
 
61
        if name == '_result':
 
62
            object.__setattr__(self, name, value)
 
63
        return setattr(self._result, name, value)
 
64
 
 
65
 
 
66
class _MyResult(unittest._TextTestResult):
 
67
    """
 
68
    Custom TestResult.
 
69
 
 
70
    No special behaviour for now.
 
71
    """
 
72
 
 
73
    def startTest(self, test):
 
74
        unittest.TestResult.startTest(self, test)
 
75
        # TODO: Maybe show test.shortDescription somewhere?
 
76
        what = test.shortDescription() or test.id()        
 
77
        if self.showAll:
 
78
            self.stream.write('%-70.70s' % what)
 
79
        self.stream.flush()
 
80
 
 
81
    def addError(self, test, err):
 
82
        super(_MyResult, self).addError(test, err)
 
83
        self.stream.flush()
 
84
 
 
85
    def addFailure(self, test, err):
 
86
        super(_MyResult, self).addFailure(test, err)
 
87
        self.stream.flush()
 
88
 
 
89
    def addSuccess(self, test):
 
90
        if self.showAll:
 
91
            self.stream.writeln('OK')
 
92
        elif self.dots:
 
93
            self.stream.write('~')
 
94
        self.stream.flush()
 
95
        unittest.TestResult.addSuccess(self, test)
 
96
 
 
97
    def printErrorList(self, flavour, errors):
 
98
        for test, err in errors:
 
99
            self.stream.writeln(self.separator1)
 
100
            self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
 
101
            if hasattr(test, '_get_log'):
 
102
                self.stream.writeln()
 
103
                self.stream.writeln('log from this test:')
 
104
                print >>self.stream, test._get_log()
 
105
            self.stream.writeln(self.separator2)
 
106
            self.stream.writeln("%s" % err)
 
107
 
 
108
 
 
109
class TextTestRunner(unittest.TextTestRunner):
 
110
 
 
111
    def _makeResult(self):
 
112
        result = _MyResult(self.stream, self.descriptions, self.verbosity)
 
113
        return EarlyStoppingTestResultAdapter(result)
 
114
 
 
115
 
 
116
def iter_suite_tests(suite):
 
117
    """Return all tests in a suite, recursing through nested suites"""
 
118
    for item in suite._tests:
 
119
        if isinstance(item, unittest.TestCase):
 
120
            yield item
 
121
        elif isinstance(item, unittest.TestSuite):
 
122
            for r in iter_suite_tests(item):
 
123
                yield r
 
124
        else:
 
125
            raise Exception('unknown object %r inside test suite %r'
 
126
                            % (item, suite))
 
127
 
 
128
 
 
129
class TestSkipped(Exception):
 
130
    """Indicates that a test was intentionally skipped, rather than failing."""
 
131
    # XXX: Not used yet
 
132
 
 
133
 
39
134
class CommandFailed(Exception):
40
135
    pass
41
136
 
55
150
    BZRPATH = 'bzr'
56
151
 
57
152
    def setUp(self):
58
 
        # this replaces the default testsweet.TestCase; we don't want logging changed
59
153
        unittest.TestCase.setUp(self)
60
154
        bzrlib.trace.disable_default_logging()
61
155
        self._enable_file_logging()
76
170
        
77
171
        self._log_file_name = name
78
172
 
79
 
        
80
173
    def tearDown(self):
81
174
        logging.getLogger('').removeHandler(self._log_hdlr)
82
175
        bzrlib.trace.enable_default_logging()
84
177
        self._log_file.close()
85
178
        unittest.TestCase.tearDown(self)
86
179
 
87
 
 
88
180
    def log(self, *args):
89
181
        logging.debug(*args)
90
182
 
92
184
        """Return as a string the log for this test"""
93
185
        return open(self._log_file_name).read()
94
186
 
 
187
 
 
188
    def capture(self, cmd):
 
189
        """Shortcut that splits cmd into words, runs, and returns stdout"""
 
190
        return self.run_bzr_captured(cmd.split())[0]
 
191
 
 
192
    def run_bzr_captured(self, argv, retcode=0):
 
193
        """Invoke bzr and return (result, stdout, stderr).
 
194
 
 
195
        Useful for code that wants to check the contents of the
 
196
        output, the way error messages are presented, etc.
 
197
 
 
198
        This should be the main method for tests that want to exercise the
 
199
        overall behavior of the bzr application (rather than a unit test
 
200
        or a functional test of the library.)
 
201
 
 
202
        Much of the old code runs bzr by forking a new copy of Python, but
 
203
        that is slower, harder to debug, and generally not necessary.
 
204
 
 
205
        This runs bzr through the interface that catches and reports
 
206
        errors, and with logging set to something approximating the
 
207
        default, so that error reporting can be checked.
 
208
 
 
209
        argv -- arguments to invoke bzr
 
210
        retcode -- expected return code, or None for don't-care.
 
211
        """
 
212
        stdout = StringIO()
 
213
        stderr = StringIO()
 
214
        self.log('run bzr: %s', ' '.join(argv))
 
215
        handler = logging.StreamHandler(stderr)
 
216
        handler.setFormatter(bzrlib.trace.QuietFormatter())
 
217
        handler.setLevel(logging.INFO)
 
218
        logger = logging.getLogger('')
 
219
        logger.addHandler(handler)
 
220
        try:
 
221
            result = self.apply_redirected(None, stdout, stderr,
 
222
                                           bzrlib.commands.run_bzr_catch_errors,
 
223
                                           argv)
 
224
        finally:
 
225
            logger.removeHandler(handler)
 
226
        out = stdout.getvalue()
 
227
        err = stderr.getvalue()
 
228
        if out:
 
229
            self.log('output:\n%s', out)
 
230
        if err:
 
231
            self.log('errors:\n%s', err)
 
232
        if retcode is not None:
 
233
            self.assertEquals(result, retcode)
 
234
        return out, err
 
235
 
95
236
    def run_bzr(self, *args, **kwargs):
96
237
        """Invoke bzr, as if it were run from the command line.
97
238
 
99
240
        overall behavior of the bzr application (rather than a unit test
100
241
        or a functional test of the library.)
101
242
 
102
 
        Much of the old code runs bzr by forking a new copy of Python, but
103
 
        that is slower, harder to debug, and generally not necessary.
 
243
        This sends the stdout/stderr results into the test's log,
 
244
        where it may be useful for debugging.  See also run_captured.
104
245
        """
105
 
        retcode = kwargs.get('retcode', 0)
106
 
        result = self.apply_redirected(None, None, None,
107
 
                                       bzrlib.commands.run_bzr, args)
108
 
        self.assertEquals(result, retcode)
109
 
        
110
 
        
 
246
        retcode = kwargs.pop('retcode', 0)
 
247
        return self.run_bzr_captured(args, retcode)
 
248
 
111
249
    def check_inventory_shape(self, inv, shape):
112
 
        """
113
 
        Compare an inventory to a list of expected names.
 
250
        """Compare an inventory to a list of expected names.
114
251
 
115
252
        Fail if they are not precisely equal.
116
253
        """
134
271
        """Call callable with redirected std io pipes.
135
272
 
136
273
        Returns the return code."""
137
 
        from StringIO import StringIO
138
274
        if not callable(a_callable):
139
275
            raise ValueError("a_callable must be callable.")
140
276
        if stdin is None:
141
277
            stdin = StringIO("")
142
278
        if stdout is None:
143
 
            stdout = self._log_file
 
279
            if hasattr(self, "_log_file"):
 
280
                stdout = self._log_file
 
281
            else:
 
282
                stdout = StringIO()
144
283
        if stderr is None:
145
 
            stderr = self._log_file
 
284
            if hasattr(self, "_log_file"):
 
285
                stderr = self._log_file
 
286
            else:
 
287
                stderr = StringIO()
146
288
        real_stdin = sys.stdin
147
289
        real_stdout = sys.stdout
148
290
        real_stderr = sys.stderr
183
325
        if contents != expect:
184
326
            self.log("expected: %r" % expect)
185
327
            self.log("actually: %r" % contents)
186
 
            self.fail("contents of %s not as expected")
 
328
            self.fail("contents of %s not as expected" % filename)
187
329
 
188
330
    def _make_test_root(self):
189
331
        if TestCaseInTempDir.TEST_ROOT is not None:
208
350
 
209
351
    def setUp(self):
210
352
        super(TestCaseInTempDir, self).setUp()
211
 
        import os
212
353
        self._make_test_root()
213
354
        self._currentdir = os.getcwdu()
214
355
        short_id = self.id().replace('bzrlib.selftest.', '') \
218
359
        os.chdir(self.test_dir)
219
360
        
220
361
    def tearDown(self):
221
 
        import os
222
362
        os.chdir(self._currentdir)
223
363
        super(TestCaseInTempDir, self).tearDown()
224
364
 
225
 
    def _formcmd(self, cmd):
226
 
        if isinstance(cmd, basestring):
227
 
            cmd = cmd.split()
228
 
        if cmd[0] == 'bzr':
229
 
            cmd[0] = self.BZRPATH
230
 
            if self.OVERRIDE_PYTHON:
231
 
                cmd.insert(0, self.OVERRIDE_PYTHON)
232
 
        self.log('$ %r' % cmd)
233
 
        return cmd
234
 
 
235
 
    def runcmd(self, cmd, retcode=0):
236
 
        """Run one command and check the return code.
237
 
 
238
 
        Returns a tuple of (stdout,stderr) strings.
239
 
 
240
 
        If a single string is based, it is split into words.
241
 
        For commands that are not simple space-separated words, please
242
 
        pass a list instead."""
243
 
        cmd = self._formcmd(cmd)
244
 
        self.log('$ ' + ' '.join(cmd))
245
 
        actual_retcode = subprocess.call(cmd, stdout=self._log_file,
246
 
                                         stderr=self._log_file)
247
 
        if retcode != actual_retcode:
248
 
            raise CommandFailed("test failed: %r returned %d, expected %d"
249
 
                                % (cmd, actual_retcode, retcode))
250
 
 
251
 
    def backtick(self, cmd, retcode=0):
252
 
        """Run a command and return its output"""
253
 
        cmd = self._formcmd(cmd)
254
 
        child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=self._log_file)
255
 
        outd, errd = child.communicate()
256
 
        self.log(outd)
257
 
        actual_retcode = child.wait()
258
 
 
259
 
        outd = outd.replace('\r', '')
260
 
 
261
 
        if retcode != actual_retcode:
262
 
            raise CommandFailed("test failed: %r returned %d, expected %d"
263
 
                                % (cmd, actual_retcode, retcode))
264
 
 
265
 
        return outd
266
 
 
267
 
 
268
 
 
269
365
    def build_tree(self, shape):
270
366
        """Build a test tree according to a pattern.
271
367
 
275
371
        This doesn't add anything to a branch.
276
372
        """
277
373
        # XXX: It's OK to just create them using forward slashes on windows?
278
 
        import os
279
374
        for name in shape:
280
375
            assert isinstance(name, basestring)
281
376
            if name[-1] == '/':
284
379
                f = file(name, 'wt')
285
380
                print >>f, "contents of", name
286
381
                f.close()
287
 
                
288
382
 
 
383
    def failUnlessExists(self, path):
 
384
        """Fail unless path, which may be abs or relative, exists."""
 
385
        self.failUnless(os.path.exists(path))
 
386
        
289
387
 
290
388
class MetaTestLog(TestCase):
291
389
    def test_logging(self):
296
394
        ##assert 0
297
395
 
298
396
 
299
 
def selftest(verbose=False, pattern=".*"):
 
397
def filter_suite_by_re(suite, pattern):
 
398
    result = TestUtil.TestSuite()
 
399
    filter_re = re.compile(pattern)
 
400
    for test in iter_suite_tests(suite):
 
401
        if filter_re.match(test.id()):
 
402
            result.addTest(test)
 
403
    return result
 
404
 
 
405
 
 
406
def filter_suite_by_names(suite, wanted_names):
 
407
    """Return a new suite containing only selected tests.
 
408
    
 
409
    Names are considered to match if any name is a substring of the 
 
410
    fully-qualified test id (i.e. the class ."""
 
411
    result = TestSuite()
 
412
    for test in iter_suite_tests(suite):
 
413
        this_id = test.id()
 
414
        for p in wanted_names:
 
415
            if this_id.find(p) != -1:
 
416
                result.addTest(test)
 
417
    return result
 
418
 
 
419
 
 
420
def run_suite(suite, name='test', verbose=False, pattern=".*", testnames=None):
 
421
    TestCaseInTempDir._TEST_NAME = name
 
422
    if verbose:
 
423
        verbosity = 2
 
424
    else:
 
425
        verbosity = 1
 
426
    runner = TextTestRunner(stream=sys.stdout,
 
427
                            descriptions=0,
 
428
                            verbosity=verbosity)
 
429
    if testnames:
 
430
        suite = filter_suite_by_names(suite, testnames)
 
431
    if pattern != '.*':
 
432
        suite = filter_suite_by_re(suite, pattern)
 
433
    result = runner.run(suite)
 
434
    # This is still a little bogus, 
 
435
    # but only a little. Folk not using our testrunner will
 
436
    # have to delete their temp directories themselves.
 
437
    if result.wasSuccessful():
 
438
        if TestCaseInTempDir.TEST_ROOT is not None:
 
439
            shutil.rmtree(TestCaseInTempDir.TEST_ROOT) 
 
440
    else:
 
441
        print "Failed tests working directories are in '%s'\n" % TestCaseInTempDir.TEST_ROOT
 
442
    return result.wasSuccessful()
 
443
 
 
444
 
 
445
def selftest(verbose=False, pattern=".*", testnames=None):
300
446
    """Run the whole test suite under the enhanced runner"""
301
 
    return testsweet.run_suite(test_suite(), 'testbzr', verbose=verbose, pattern=pattern)
 
447
    return run_suite(test_suite(), 'testbzr', verbose=verbose, pattern=pattern,
 
448
                     testnames=testnames)
302
449
 
303
450
 
304
451
def test_suite():
305
452
    """Build and return TestSuite for the whole program."""
306
 
    from bzrlib.selftest.TestUtil import TestLoader, TestSuite
307
 
    import bzrlib, bzrlib.store, bzrlib.inventory, bzrlib.branch
308
 
    import bzrlib.osutils, bzrlib.commands, bzrlib.merge3, bzrlib.plugin
 
453
    import bzrlib.store, bzrlib.inventory, bzrlib.branch
 
454
    import bzrlib.osutils, bzrlib.merge3, bzrlib.plugin
309
455
    from doctest import DocTestSuite
310
 
    import os
311
 
    import shutil
312
 
    import time
313
 
    import sys
314
456
 
315
457
    global MODULES_TO_TEST, MODULES_TO_DOCTEST
316
458
 
317
459
    testmod_names = \
318
460
                  ['bzrlib.selftest.MetaTestLog',
 
461
                   'bzrlib.selftest.testidentitymap',
319
462
                   'bzrlib.selftest.testinv',
 
463
                   'bzrlib.selftest.test_ancestry',
 
464
                   'bzrlib.selftest.test_commit',
 
465
                   'bzrlib.selftest.test_commit_merge',
320
466
                   'bzrlib.selftest.versioning',
321
467
                   'bzrlib.selftest.testmerge3',
 
468
                   'bzrlib.selftest.testmerge',
322
469
                   'bzrlib.selftest.testhashcache',
323
470
                   'bzrlib.selftest.teststatus',
324
471
                   'bzrlib.selftest.testlog',
325
472
                   'bzrlib.selftest.testrevisionnamespaces',
326
473
                   'bzrlib.selftest.testbranch',
327
 
#                   'bzrlib.selftest.testrevision',
328
 
#                   'bzrlib.selftest.test_merge_core',
 
474
                   'bzrlib.selftest.testrevision',
 
475
                   'bzrlib.selftest.test_revision_info',
 
476
                   'bzrlib.selftest.test_merge_core',
329
477
                   'bzrlib.selftest.test_smart_add',
 
478
                   'bzrlib.selftest.test_bad_files',
330
479
                   'bzrlib.selftest.testdiff',
331
 
#                   'bzrlib.selftest.test_parent',
 
480
                   'bzrlib.selftest.test_parent',
332
481
                   'bzrlib.selftest.test_xml',
333
 
#                   'bzrlib.selftest.testfetch',
334
 
#                   'bzrlib.selftest.whitebox',
 
482
                   'bzrlib.selftest.test_weave',
 
483
                   'bzrlib.selftest.testfetch',
 
484
                   'bzrlib.selftest.whitebox',
335
485
                   'bzrlib.selftest.teststore',
336
 
#                   'bzrlib.selftest.blackbox',
 
486
                   'bzrlib.selftest.blackbox',
 
487
                   'bzrlib.selftest.testsampler',
 
488
                   'bzrlib.selftest.testtransactions',
 
489
                   'bzrlib.selftest.testtransport',
 
490
                   'bzrlib.selftest.testgraph',
 
491
                   'bzrlib.selftest.testworkingtree',
 
492
                   'bzrlib.selftest.test_upgrade',
 
493
                   'bzrlib.selftest.test_conflicts',
337
494
                   ]
338
495
 
339
496
    for m in (bzrlib.store, bzrlib.inventory, bzrlib.branch,