~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

[merge] up-to-date against 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
 
 
32
30
import bzrlib.commands
33
31
import bzrlib.trace
34
32
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
 
33
from bzrlib.trace import mutter
 
34
from bzrlib.tests.TestUtil import TestLoader, TestSuite
 
35
from bzrlib.tests.treeshape import build_tree_contents
 
36
from bzrlib.errors import BzrError
38
37
 
39
38
MODULES_TO_TEST = []
40
39
MODULES_TO_DOCTEST = []
65
64
 
66
65
 
67
66
class _MyResult(unittest._TextTestResult):
68
 
    """
69
 
    Custom TestResult.
70
 
 
71
 
    No special behaviour for now.
72
 
    """
73
 
 
 
67
    """Custom TestResult.
 
68
 
 
69
    Shows output in a different format, including displaying runtime for tests.
 
70
    """
 
71
 
 
72
    # assumes 80-column window, less 'ERROR 99999ms' = 13ch
74
73
    def _elapsedTime(self):
75
 
        return "(Took %.3fs)" % (time.time() - self._start_time)
 
74
        return "%5dms" % (1000 * (time.time() - self._start_time))
76
75
 
77
76
    def startTest(self, test):
78
77
        unittest.TestResult.startTest(self, test)
79
 
        # TODO: Maybe show test.shortDescription somewhere?
80
 
        what = test.shortDescription() or test.id()        
 
78
        # In a short description, the important words are in
 
79
        # the beginning, but in an id, the important words are
 
80
        # at the end
 
81
        SHOW_DESCRIPTIONS = False
 
82
        what = SHOW_DESCRIPTIONS and test.shortDescription()
 
83
        if what:
 
84
            if len(what) > 65:
 
85
                what = what[:62] + '...'
 
86
        else:
 
87
            what = test.id()
 
88
            if what.startswith('bzrlib.tests.'):
 
89
                what = what[13:]
 
90
            if len(what) > 65:
 
91
                what = '...' + what[-62:]
81
92
        if self.showAll:
82
 
            self.stream.write('%-70.70s' % what)
 
93
            self.stream.write('%-65.65s' % what)
83
94
        self.stream.flush()
84
95
        self._start_time = time.time()
85
96
 
94
105
    def addFailure(self, test, err):
95
106
        unittest.TestResult.addFailure(self, test, err)
96
107
        if self.showAll:
97
 
            self.stream.writeln("FAIL %s" % self._elapsedTime())
 
108
            self.stream.writeln(" FAIL %s" % self._elapsedTime())
98
109
        elif self.dots:
99
110
            self.stream.write('F')
100
111
        self.stream.flush()
101
112
 
102
113
    def addSuccess(self, test):
103
114
        if self.showAll:
104
 
            self.stream.writeln('OK %s' % self._elapsedTime())
 
115
            self.stream.writeln('   OK %s' % self._elapsedTime())
105
116
        elif self.dots:
106
117
            self.stream.write('~')
107
118
        self.stream.flush()
223
234
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
224
235
        self._log_file = os.fdopen(fileno, 'w+')
225
236
        bzrlib.trace.enable_test_log(self._log_file)
226
 
        debug('opened log file %s', name)
227
237
        self._log_file_name = name
228
238
        self.addCleanup(self._finishLogFile)
229
239
 
251
261
        self._cleanups.append(callable)
252
262
 
253
263
    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']
 
264
        new_env = {
 
265
            'HOME': os.getcwd(),
 
266
            'APPDATA': os.getcwd(),
 
267
            'BZREMAIL': None,
 
268
            'EMAIL': None,
 
269
        }
 
270
        self.__old_env = {}
262
271
        self.addCleanup(self._restoreEnvironment)
 
272
        for name, value in new_env.iteritems():
 
273
            self._captureVar(name, value)
 
274
 
 
275
 
 
276
    def _captureVar(self, name, newvalue):
 
277
        """Set an environment variable, preparing it to be reset when finished."""
 
278
        self.__old_env[name] = os.environ.get(name, None)
 
279
        if newvalue is None:
 
280
            if name in os.environ:
 
281
                del os.environ[name]
 
282
        else:
 
283
            os.environ[name] = newvalue
 
284
 
 
285
    @staticmethod
 
286
    def _restoreVar(name, value):
 
287
        if value is None:
 
288
            if name in os.environ:
 
289
                del os.environ[name]
 
290
        else:
 
291
            os.environ[name] = value
263
292
 
264
293
    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
 
294
        for name, value in self.__old_env.iteritems():
 
295
            self._restoreVar(name, value)
274
296
 
275
297
    def tearDown(self):
276
298
        self._runCleanups()
285
307
            callable()
286
308
 
287
309
    def log(self, *args):
288
 
        logging.debug(*args)
 
310
        mutter(*args)
289
311
 
290
312
    def _get_log(self):
291
313
        """Return as a string the log for this test"""
293
315
            return open(self._log_file_name).read()
294
316
        else:
295
317
            return self._log_contents
 
318
        # TODO: Delete the log after it's been read in
296
319
 
297
320
    def capture(self, cmd, retcode=0):
298
321
        """Shortcut that splits cmd into words, runs, and returns stdout"""
321
344
        stdout = StringIO()
322
345
        stderr = StringIO()
323
346
        self.log('run bzr: %s', ' '.join(argv))
 
347
        # FIXME: don't call into logging here
324
348
        handler = logging.StreamHandler(stderr)
325
349
        handler.setFormatter(bzrlib.trace.QuietFormatter())
326
350
        handler.setLevel(logging.INFO)
461
485
        super(TestCaseInTempDir, self).setUp()
462
486
        self._make_test_root()
463
487
        _currentdir = os.getcwdu()
464
 
        short_id = self.id().replace('bzrlib.selftest.', '') \
 
488
        short_id = self.id().replace('bzrlib.tests.', '') \
465
489
                   .replace('__main__.', '')
466
490
        self.test_dir = os.path.join(self.TEST_ROOT, short_id)
467
491
        os.mkdir(self.test_dir)
471
495
            os.chdir(_currentdir)
472
496
        self.addCleanup(_leaveDirectory)
473
497
        
474
 
    def build_tree(self, shape):
 
498
    def build_tree(self, shape, line_endings='native'):
475
499
        """Build a test tree according to a pattern.
476
500
 
477
501
        shape is a sequence of file specifications.  If the final
478
502
        character is '/', a directory is created.
479
503
 
480
504
        This doesn't add anything to a branch.
 
505
        :param line_endings: Either 'binary' or 'native'
 
506
                             in binary mode, exact contents are written
 
507
                             in native mode, the line endings match the
 
508
                             default platform endings.
481
509
        """
482
510
        # XXX: It's OK to just create them using forward slashes on windows?
483
511
        for name in shape:
485
513
            if name[-1] == '/':
486
514
                os.mkdir(name[:-1])
487
515
            else:
488
 
                f = file(name, 'wt')
 
516
                if line_endings == 'binary':
 
517
                    f = file(name, 'wb')
 
518
                elif line_endings == 'native':
 
519
                    f = file(name, 'wt')
 
520
                else:
 
521
                    raise BzrError('Invalid line ending request %r' % (line_endings,))
489
522
                print >>f, "contents of", name
490
523
                f.close()
491
524
 
492
525
    def build_tree_contents(self, shape):
493
 
        bzrlib.selftest.build_tree_contents(shape)
 
526
        bzrlib.tests.build_tree_contents(shape)
494
527
 
495
528
    def failUnlessExists(self, path):
496
529
        """Fail unless path, which may be abs or relative, exists."""
506
539
    def test_logging(self):
507
540
        """Test logs are captured when a test fails."""
508
541
        self.log('a test message')
 
542
        self._log_file.flush()
509
543
        self.assertContainsRe(self._get_log(), 'a test message\n')
510
544
 
511
545
 
562
596
    # exception is hidden by unittest.  Sucks.  Should either fix that or
563
597
    # perhaps import them and pass them to unittest as modules.
564
598
    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.testmerge3',
576
 
                   'bzrlib.selftest.testmerge',
577
 
                   'bzrlib.selftest.testhashcache',
578
 
                   'bzrlib.selftest.teststatus',
579
 
                   'bzrlib.selftest.testlog',
580
 
                   'bzrlib.selftest.testrevisionnamespaces',
581
 
                   'bzrlib.selftest.testbranch',
582
 
                   'bzrlib.selftest.testrevision',
583
 
                   'bzrlib.selftest.test_revision_info',
584
 
                   'bzrlib.selftest.test_merge_core',
585
 
                   'bzrlib.selftest.test_smart_add',
586
 
                   'bzrlib.selftest.test_bad_files',
587
 
                   'bzrlib.selftest.testdiff',
588
 
                   'bzrlib.selftest.test_parent',
589
 
                   'bzrlib.selftest.test_xml',
590
 
                   'bzrlib.selftest.test_weave',
591
 
                   'bzrlib.selftest.testfetch',
592
 
                   'bzrlib.selftest.whitebox',
593
 
                   'bzrlib.selftest.teststore',
594
 
                   'bzrlib.selftest.blackbox',
595
 
                   'bzrlib.selftest.blackbox.test_bound_branches',
596
 
                   'bzrlib.selftest.blackbox.versioning',
597
 
                   'bzrlib.selftest.testsampler',
598
 
                   'bzrlib.selftest.testtransactions',
599
 
                   'bzrlib.selftest.testtransport',
600
 
                   'bzrlib.selftest.testsftp',
601
 
                   'bzrlib.selftest.testgraph',
602
 
                   'bzrlib.selftest.testworkingtree',
603
 
                   'bzrlib.selftest.test_upgrade',
604
 
                   'bzrlib.selftest.test_conflicts',
605
 
                   'bzrlib.selftest.testtestament',
606
 
                   'bzrlib.selftest.testannotate',
607
 
                   'bzrlib.selftest.testrevprops',
608
 
                   'bzrlib.selftest.testoptions',
609
 
                   'bzrlib.selftest.testhttp',
610
 
                   'bzrlib.selftest.testnonascii',
611
 
                   'bzrlib.selftest.testreweave',
612
 
                   'bzrlib.selftest.testtsort',
613
 
                   'bzrlib.selftest.testtrace',
 
599
                  ['bzrlib.tests.MetaTestLog',
 
600
                   'bzrlib.tests.test_api',
 
601
                   'bzrlib.tests.test_gpg',
 
602
                   'bzrlib.tests.test_identitymap',
 
603
                   'bzrlib.tests.test_inv',
 
604
                   'bzrlib.tests.test_ancestry',
 
605
                   'bzrlib.tests.test_commit',
 
606
                   'bzrlib.tests.test_command',
 
607
                   'bzrlib.tests.test_commit_merge',
 
608
                   'bzrlib.tests.test_config',
 
609
                   'bzrlib.tests.test_merge3',
 
610
                   'bzrlib.tests.test_merge',
 
611
                   'bzrlib.tests.test_hashcache',
 
612
                   'bzrlib.tests.test_status',
 
613
                   'bzrlib.tests.test_log',
 
614
                   'bzrlib.tests.test_revisionnamespaces',
 
615
                   'bzrlib.tests.test_branch',
 
616
                   'bzrlib.tests.test_revision',
 
617
                   'bzrlib.tests.test_revision_info',
 
618
                   'bzrlib.tests.test_merge_core',
 
619
                   'bzrlib.tests.test_smart_add',
 
620
                   'bzrlib.tests.test_bad_files',
 
621
                   'bzrlib.tests.test_diff',
 
622
                   'bzrlib.tests.test_parent',
 
623
                   'bzrlib.tests.test_xml',
 
624
                   'bzrlib.tests.test_weave',
 
625
                   'bzrlib.tests.test_fetch',
 
626
                   'bzrlib.tests.test_whitebox',
 
627
                   'bzrlib.tests.test_store',
 
628
                   'bzrlib.tests.blackbox',
 
629
                   'bzrlib.tests.blackbox.versioning',
 
630
                   'bzrlib.tests.blackbox.test_bound_branch',
 
631
                   'bzrlib.tests.test_sampler',
 
632
                   'bzrlib.tests.test_transactions',
 
633
                   'bzrlib.tests.test_transport',
 
634
                   'bzrlib.tests.test_sftp',
 
635
                   'bzrlib.tests.test_graph',
 
636
                   'bzrlib.tests.test_workingtree',
 
637
                   'bzrlib.tests.test_upgrade',
 
638
                   'bzrlib.tests.test_uncommit',
 
639
                   'bzrlib.tests.test_conflicts',
 
640
                   'bzrlib.tests.test_testament',
 
641
                   'bzrlib.tests.test_annotate',
 
642
                   'bzrlib.tests.test_revprops',
 
643
                   'bzrlib.tests.test_options',
 
644
                   'bzrlib.tests.test_http',
 
645
                   'bzrlib.tests.test_nonascii',
 
646
                   'bzrlib.tests.test_reweave',
 
647
                   'bzrlib.tests.test_tsort',
 
648
                   'bzrlib.tests.test_trace',
 
649
                   'bzrlib.tests.test_basicio',
614
650
                   ]
615
651
 
616
652
    for m in (bzrlib.store, bzrlib.inventory, bzrlib.branch,