~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

[merge] bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
27
27
import unittest
28
28
import time
29
29
 
30
 
from logging import debug, warning, error
31
 
 
 
30
import bzrlib.branch
32
31
import bzrlib.commands
 
32
from bzrlib.errors import BzrError
 
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
33
39
import bzrlib.trace
34
 
import bzrlib.osutils as osutils
35
 
from bzrlib.selftest import TestUtil
36
 
from bzrlib.selftest.TestUtil import TestLoader, TestSuite
37
 
from bzrlib.selftest.treeshape import build_tree_contents
 
40
from bzrlib.trace import mutter
 
41
from bzrlib.tests.TestUtil import TestLoader, TestSuite
 
42
from bzrlib.tests.treeshape import build_tree_contents
38
43
 
39
44
MODULES_TO_TEST = []
40
 
MODULES_TO_DOCTEST = []
41
 
 
 
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
            ]
42
59
 
43
60
 
44
61
class EarlyStoppingTestResultAdapter(object):
65
82
 
66
83
 
67
84
class _MyResult(unittest._TextTestResult):
68
 
    """
69
 
    Custom TestResult.
 
85
    """Custom TestResult.
70
86
 
71
 
    No special behaviour for now.
 
87
    Shows output in a different format, including displaying runtime for tests.
72
88
    """
73
89
 
74
90
    def _elapsedTime(self):
75
 
        return "(Took %.3fs)" % (time.time() - self._start_time)
 
91
        return "%5dms" % (1000 * (time.time() - self._start_time))
76
92
 
77
93
    def startTest(self, test):
78
94
        unittest.TestResult.startTest(self, test)
79
 
        # TODO: Maybe show test.shortDescription somewhere?
80
 
        what = test.shortDescription() or test.id()        
 
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
 
98
        SHOW_DESCRIPTIONS = False
81
99
        if self.showAll:
82
 
            self.stream.write('%-70.70s' % what)
 
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)
83
116
        self.stream.flush()
84
117
        self._start_time = time.time()
85
118
 
94
127
    def addFailure(self, test, err):
95
128
        unittest.TestResult.addFailure(self, test, err)
96
129
        if self.showAll:
97
 
            self.stream.writeln("FAIL %s" % self._elapsedTime())
 
130
            self.stream.writeln(" FAIL %s" % self._elapsedTime())
98
131
        elif self.dots:
99
132
            self.stream.write('F')
100
133
        self.stream.flush()
101
134
 
102
135
    def addSuccess(self, test):
103
136
        if self.showAll:
104
 
            self.stream.writeln('OK %s' % self._elapsedTime())
 
137
            self.stream.writeln('   OK %s' % self._elapsedTime())
105
138
        elif self.dots:
106
139
            self.stream.write('~')
107
140
        self.stream.flush()
223
256
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
224
257
        self._log_file = os.fdopen(fileno, 'w+')
225
258
        bzrlib.trace.enable_test_log(self._log_file)
226
 
        debug('opened log file %s', name)
227
259
        self._log_file_name = name
228
260
        self.addCleanup(self._finishLogFile)
229
261
 
251
283
        self._cleanups.append(callable)
252
284
 
253
285
    def _cleanEnvironment(self):
254
 
        self.oldenv = os.environ.get('HOME', None)
255
 
        os.environ['HOME'] = os.getcwd()
256
 
        self.bzr_email = os.environ.get('BZREMAIL')
257
 
        if self.bzr_email is not None:
258
 
            del os.environ['BZREMAIL']
259
 
        self.email = os.environ.get('EMAIL')
260
 
        if self.email is not None:
261
 
            del os.environ['EMAIL']
 
286
        new_env = {
 
287
            'HOME': os.getcwd(),
 
288
            'APPDATA': os.getcwd(),
 
289
            'BZREMAIL': None,
 
290
            'EMAIL': None,
 
291
        }
 
292
        self.__old_env = {}
262
293
        self.addCleanup(self._restoreEnvironment)
 
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."""
 
300
        self.__old_env[name] = os.environ.get(name, None)
 
301
        if newvalue is None:
 
302
            if name in os.environ:
 
303
                del os.environ[name]
 
304
        else:
 
305
            os.environ[name] = newvalue
 
306
 
 
307
    @staticmethod
 
308
    def _restoreVar(name, value):
 
309
        if value is None:
 
310
            if name in os.environ:
 
311
                del os.environ[name]
 
312
        else:
 
313
            os.environ[name] = value
263
314
 
264
315
    def _restoreEnvironment(self):
265
 
        os.environ['HOME'] = self.oldenv
266
 
        if os.environ.get('BZREMAIL') is not None:
267
 
            del os.environ['BZREMAIL']
268
 
        if self.bzr_email is not None:
269
 
            os.environ['BZREMAIL'] = self.bzr_email
270
 
        if os.environ.get('EMAIL') is not None:
271
 
            del os.environ['EMAIL']
272
 
        if self.email is not None:
273
 
            os.environ['EMAIL'] = self.email
 
316
        for name, value in self.__old_env.iteritems():
 
317
            self._restoreVar(name, value)
274
318
 
275
319
    def tearDown(self):
276
320
        self._runCleanups()
285
329
            callable()
286
330
 
287
331
    def log(self, *args):
288
 
        logging.debug(*args)
 
332
        mutter(*args)
289
333
 
290
334
    def _get_log(self):
291
335
        """Return as a string the log for this test"""
293
337
            return open(self._log_file_name).read()
294
338
        else:
295
339
            return self._log_contents
 
340
        # TODO: Delete the log after it's been read in
296
341
 
297
342
    def capture(self, cmd, retcode=0):
298
343
        """Shortcut that splits cmd into words, runs, and returns stdout"""
321
366
        stdout = StringIO()
322
367
        stderr = StringIO()
323
368
        self.log('run bzr: %s', ' '.join(argv))
 
369
        # FIXME: don't call into logging here
324
370
        handler = logging.StreamHandler(stderr)
325
371
        handler.setFormatter(bzrlib.trace.QuietFormatter())
326
372
        handler.setLevel(logging.INFO)
461
507
        super(TestCaseInTempDir, self).setUp()
462
508
        self._make_test_root()
463
509
        _currentdir = os.getcwdu()
464
 
        short_id = self.id().replace('bzrlib.selftest.', '') \
 
510
        short_id = self.id().replace('bzrlib.tests.', '') \
465
511
                   .replace('__main__.', '')
466
512
        self.test_dir = os.path.join(self.TEST_ROOT, short_id)
467
513
        os.mkdir(self.test_dir)
471
517
            os.chdir(_currentdir)
472
518
        self.addCleanup(_leaveDirectory)
473
519
        
474
 
    def build_tree(self, shape):
 
520
    def build_tree(self, shape, line_endings='native'):
475
521
        """Build a test tree according to a pattern.
476
522
 
477
523
        shape is a sequence of file specifications.  If the final
478
524
        character is '/', a directory is created.
479
525
 
480
526
        This doesn't add anything to a branch.
 
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.
481
531
        """
482
532
        # XXX: It's OK to just create them using forward slashes on windows?
483
533
        for name in shape:
485
535
            if name[-1] == '/':
486
536
                os.mkdir(name[:-1])
487
537
            else:
488
 
                f = file(name, 'wt')
 
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,))
489
544
                print >>f, "contents of", name
490
545
                f.close()
491
546
 
492
547
    def build_tree_contents(self, shape):
493
 
        bzrlib.selftest.build_tree_contents(shape)
 
548
        build_tree_contents(shape)
494
549
 
495
550
    def failUnlessExists(self, path):
496
551
        """Fail unless path, which may be abs or relative, exists."""
506
561
    def test_logging(self):
507
562
        """Test logs are captured when a test fails."""
508
563
        self.log('a test message')
 
564
        self._log_file.flush()
509
565
        self.assertContainsRe(self._get_log(), 'a test message\n')
510
566
 
511
567
 
552
608
 
553
609
def test_suite():
554
610
    """Build and return TestSuite for the whole program."""
555
 
    import bzrlib.store, bzrlib.inventory, bzrlib.branch
556
 
    import bzrlib.osutils, bzrlib.merge3, bzrlib.plugin
557
611
    from doctest import DocTestSuite
558
612
 
559
 
    global MODULES_TO_TEST, MODULES_TO_DOCTEST
 
613
    global MODULES_TO_DOCTEST
560
614
 
561
615
    # FIXME: If these fail to load, e.g. because of a syntax error, the
562
616
    # exception is hidden by unittest.  Sucks.  Should either fix that or
563
617
    # perhaps import them and pass them to unittest as modules.
564
618
    testmod_names = \
565
 
                  ['bzrlib.selftest.MetaTestLog',
566
 
                   'bzrlib.selftest.testapi',
567
 
                   'bzrlib.selftest.testgpg',
568
 
                   'bzrlib.selftest.testidentitymap',
569
 
                   'bzrlib.selftest.testinv',
570
 
                   'bzrlib.selftest.test_ancestry',
571
 
                   'bzrlib.selftest.test_commit',
572
 
                   'bzrlib.selftest.test_command',
573
 
                   'bzrlib.selftest.test_commit_merge',
574
 
                   'bzrlib.selftest.testconfig',
575
 
                   'bzrlib.selftest.versioning',
576
 
                   'bzrlib.selftest.testmerge3',
577
 
                   'bzrlib.selftest.testmerge',
578
 
                   'bzrlib.selftest.testhashcache',
579
 
                   'bzrlib.selftest.teststatus',
580
 
                   'bzrlib.selftest.testlog',
581
 
                   'bzrlib.selftest.testrevisionnamespaces',
582
 
                   'bzrlib.selftest.testbranch',
583
 
                   'bzrlib.selftest.testrevision',
584
 
                   'bzrlib.selftest.test_revision_info',
585
 
                   'bzrlib.selftest.test_merge_core',
586
 
                   'bzrlib.selftest.test_smart_add',
587
 
                   'bzrlib.selftest.test_bad_files',
588
 
                   'bzrlib.selftest.testdiff',
589
 
                   'bzrlib.selftest.test_parent',
590
 
                   'bzrlib.selftest.test_xml',
591
 
                   'bzrlib.selftest.test_weave',
592
 
                   'bzrlib.selftest.testfetch',
593
 
                   'bzrlib.selftest.whitebox',
594
 
                   'bzrlib.selftest.teststore',
595
 
                   'bzrlib.selftest.blackbox',
596
 
                   'bzrlib.selftest.testsampler',
597
 
                   'bzrlib.selftest.testtransactions',
598
 
                   'bzrlib.selftest.testtransport',
599
 
                   'bzrlib.selftest.testsftp',
600
 
                   'bzrlib.selftest.testgraph',
601
 
                   'bzrlib.selftest.testworkingtree',
602
 
                   'bzrlib.selftest.test_upgrade',
603
 
                   'bzrlib.selftest.test_conflicts',
604
 
                   'bzrlib.selftest.testtestament',
605
 
                   'bzrlib.selftest.testannotate',
606
 
                   'bzrlib.selftest.testrevprops',
607
 
                   'bzrlib.selftest.testoptions',
608
 
                   'bzrlib.selftest.testhttp',
609
 
                   'bzrlib.selftest.testnonascii',
610
 
                   'bzrlib.selftest.testreweave',
611
 
                   'bzrlib.selftest.testtsort',
612
 
                   'bzrlib.selftest.testtrace',
 
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',
 
656
                   'bzrlib.tests.test_conflicts',
 
657
                   'bzrlib.tests.test_testament',
 
658
                   'bzrlib.tests.test_annotate',
 
659
                   'bzrlib.tests.test_revprops',
 
660
                   'bzrlib.tests.test_options',
 
661
                   'bzrlib.tests.test_http',
 
662
                   'bzrlib.tests.test_nonascii',
 
663
                   'bzrlib.tests.test_reweave',
 
664
                   'bzrlib.tests.test_tsort',
 
665
                   'bzrlib.tests.test_trace',
 
666
                   'bzrlib.tests.test_rio',
613
667
                   ]
614
668
 
615
 
    for m in (bzrlib.store, bzrlib.inventory, bzrlib.branch,
616
 
              bzrlib.osutils, bzrlib.commands, bzrlib.merge3,
617
 
              bzrlib.errors,
618
 
              ):
619
 
        if m not in MODULES_TO_DOCTEST:
620
 
            MODULES_TO_DOCTEST.append(m)
621
 
 
622
669
    TestCase.BZRPATH = os.path.join(os.path.realpath(os.path.dirname(bzrlib.__path__[0])), 'bzr')
623
670
    print '%-30s %s' % ('bzr binary', TestCase.BZRPATH)
624
671
    print
625
672
    suite = TestSuite()
626
673
    suite.addTest(TestLoader().loadTestsFromNames(testmod_names))
 
674
    for package in packages_to_test():
 
675
        suite.addTest(package.test_suite())
627
676
    for m in MODULES_TO_TEST:
628
 
         suite.addTest(TestLoader().loadTestsFromModule(m))
 
677
        suite.addTest(TestLoader().loadTestsFromModule(m))
629
678
    for m in (MODULES_TO_DOCTEST):
630
679
        suite.addTest(DocTestSuite(m))
631
680
    for p in bzrlib.plugin.all_plugins: