/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Robert Collins
  • Date: 2006-06-09 09:04:53 UTC
  • mfrom: (1755.2.1 add)
  • mto: (1755.1.2 integration)
  • mto: This revision was merged to the branch mainline in revision 1757.
  • Revision ID: robertc@robertcollins.net-20060609090453-10e94172dc5f670b
MergeĀ currentĀ head.

Show diffs side-by-side

added added

removed removed

Lines of Context:
33
33
import logging
34
34
import os
35
35
import re
 
36
import shlex
36
37
import stat
 
38
from subprocess import Popen, PIPE
37
39
import sys
38
40
import tempfile
39
41
import unittest
43
45
import bzrlib.branch
44
46
import bzrlib.bzrdir as bzrdir
45
47
import bzrlib.commands
 
48
import bzrlib.bundle.serializer
46
49
import bzrlib.errors as errors
47
50
import bzrlib.inventory
48
51
import bzrlib.iterablefile
61
64
from bzrlib.revision import common_ancestor
62
65
import bzrlib.store
63
66
import bzrlib.trace
64
 
from bzrlib.transport import urlescape, get_transport
 
67
from bzrlib.transport import get_transport
65
68
import bzrlib.transport
66
69
from bzrlib.transport.local import LocalRelpathServer
67
70
from bzrlib.transport.readonly import ReadonlyServer
68
71
from bzrlib.trace import mutter
69
72
from bzrlib.tests.TestUtil import TestLoader, TestSuite
70
73
from bzrlib.tests.treeshape import build_tree_contents
 
74
import bzrlib.urlutils as urlutils
71
75
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
72
76
 
73
77
default_transport = LocalRelpathServer
75
79
MODULES_TO_TEST = []
76
80
MODULES_TO_DOCTEST = [
77
81
                      bzrlib.branch,
 
82
                      bzrlib.bundle.serializer,
78
83
                      bzrlib.commands,
79
84
                      bzrlib.errors,
80
85
                      bzrlib.inventory,
85
90
                      bzrlib.osutils,
86
91
                      bzrlib.store
87
92
                      ]
 
93
 
 
94
 
88
95
def packages_to_test():
89
96
    """Return a list of packages to test.
90
97
 
228
235
        self.extractBenchmarkTime(test)
229
236
        if self.showAll:
230
237
            self.stream.writeln('   OK %s' % self._testTimeString())
231
 
            for bench_called, stats in test._benchcalls:
 
238
            for bench_called, stats in getattr(test, '_benchcalls', []):
232
239
                self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
233
240
                stats.pprint(file=self.stream)
234
241
        elif self.dots and self.pb is None:
324
331
        test_root = TestCaseInTempDir.TEST_ROOT
325
332
        if result.wasSuccessful() or not self.keep_output:
326
333
            if test_root is not None:
327
 
                    osutils.rmtree(test_root)
 
334
                # If LANG=C we probably have created some bogus paths
 
335
                # which rmtree(unicode) will fail to delete
 
336
                # so make sure we are using rmtree(str) to delete everything
 
337
                osutils.rmtree(test_root.encode(
 
338
                    sys.getfilesystemencoding()))
328
339
        else:
329
340
            if self.pb is not None:
330
341
                self.pb.note("Failed tests working directories are in '%s'\n",
360
371
class CommandFailed(Exception):
361
372
    pass
362
373
 
 
374
 
 
375
class StringIOWrapper(object):
 
376
    """A wrapper around cStringIO which just adds an encoding attribute.
 
377
    
 
378
    Internally we can check sys.stdout to see what the output encoding
 
379
    should be. However, cStringIO has no encoding attribute that we can
 
380
    set. So we wrap it instead.
 
381
    """
 
382
    encoding='ascii'
 
383
    _cstring = None
 
384
 
 
385
    def __init__(self, s=None):
 
386
        if s is not None:
 
387
            self.__dict__['_cstring'] = StringIO(s)
 
388
        else:
 
389
            self.__dict__['_cstring'] = StringIO()
 
390
 
 
391
    def __getattr__(self, name, getattr=getattr):
 
392
        return getattr(self.__dict__['_cstring'], name)
 
393
 
 
394
    def __setattr__(self, name, val):
 
395
        if name == 'encoding':
 
396
            self.__dict__['encoding'] = val
 
397
        else:
 
398
            return setattr(self._cstring, name, val)
 
399
 
 
400
 
363
401
class TestCase(unittest.TestCase):
364
402
    """Base class for bzr unit tests.
365
403
    
598
636
        """Shortcut that splits cmd into words, runs, and returns stdout"""
599
637
        return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
600
638
 
601
 
    def run_bzr_captured(self, argv, retcode=0, stdin=None):
 
639
    def run_bzr_captured(self, argv, retcode=0, encoding=None, stdin=None):
602
640
        """Invoke bzr and return (stdout, stderr).
603
641
 
604
642
        Useful for code that wants to check the contents of the
615
653
        errors, and with logging set to something approximating the
616
654
        default, so that error reporting can be checked.
617
655
 
618
 
        argv -- arguments to invoke bzr
619
 
        retcode -- expected return code, or None for don't-care.
 
656
        :param argv: arguments to invoke bzr
 
657
        :param retcode: expected return code, or None for don't-care.
 
658
        :param encoding: encoding for sys.stdout and sys.stderr
620
659
        :param stdin: A string to be used as stdin for the command.
621
660
        """
 
661
        if encoding is None:
 
662
            encoding = bzrlib.user_encoding
622
663
        if stdin is not None:
623
664
            stdin = StringIO(stdin)
624
 
        stdout = StringIO()
625
 
        stderr = StringIO()
626
 
        self.log('run bzr: %s', ' '.join(argv))
 
665
        stdout = StringIOWrapper()
 
666
        stderr = StringIOWrapper()
 
667
        stdout.encoding = encoding
 
668
        stderr.encoding = encoding
 
669
 
 
670
        self.log('run bzr: %r', argv)
627
671
        # FIXME: don't call into logging here
628
672
        handler = logging.StreamHandler(stderr)
629
673
        handler.setFormatter(bzrlib.trace.QuietFormatter())
642
686
        finally:
643
687
            logger.removeHandler(handler)
644
688
            bzrlib.ui.ui_factory = old_ui_factory
 
689
 
645
690
        out = stdout.getvalue()
646
691
        err = stderr.getvalue()
647
692
        if out:
648
 
            self.log('output:\n%s', out)
 
693
            self.log('output:\n%r', out)
649
694
        if err:
650
 
            self.log('errors:\n%s', err)
 
695
            self.log('errors:\n%r', err)
651
696
        if retcode is not None:
652
 
            self.assertEquals(result, retcode)
 
697
            self.assertEquals(retcode, result)
653
698
        return out, err
654
699
 
655
700
    def run_bzr(self, *args, **kwargs):
665
710
        :param stdin: A string to be used as stdin for the command.
666
711
        """
667
712
        retcode = kwargs.pop('retcode', 0)
 
713
        encoding = kwargs.pop('encoding', None)
668
714
        stdin = kwargs.pop('stdin', None)
669
 
        return self.run_bzr_captured(args, retcode, stdin)
 
715
        return self.run_bzr_captured(args, retcode=retcode, encoding=encoding, stdin=stdin)
 
716
 
 
717
    def run_bzr_decode(self, *args, **kwargs):
 
718
        if kwargs.has_key('encoding'):
 
719
            encoding = kwargs['encoding']
 
720
        else:
 
721
            encoding = bzrlib.user_encoding
 
722
        return self.run_bzr(*args, **kwargs)[0].decode(encoding)
 
723
 
 
724
    def run_bzr_external(self, *args, **kwargs):
 
725
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
 
726
        if len(args) == 1:
 
727
            args = shlex.split(args[0])
 
728
        args = list(args)
 
729
        process = Popen([bzr_path]+args, stdout=PIPE, stderr=PIPE)
 
730
        out = process.stdout.read()
 
731
        err = process.stderr.read()
 
732
        retcode = process.wait()
 
733
        supplied_retcode = kwargs.get('retcode')
 
734
        if supplied_retcode is not None:
 
735
            assert supplied_retcode == retcode
 
736
        else:
 
737
            assert retcode == 0
 
738
        return [out, err]
670
739
 
671
740
    def check_inventory_shape(self, inv, shape):
672
741
        """Compare an inventory to a list of expected names.
837
906
        for name in shape:
838
907
            self.assert_(isinstance(name, basestring))
839
908
            if name[-1] == '/':
840
 
                transport.mkdir(urlescape(name[:-1]))
 
909
                transport.mkdir(urlutils.escape(name[:-1]))
841
910
            else:
842
911
                if line_endings == 'binary':
843
912
                    end = '\n'
845
914
                    end = os.linesep
846
915
                else:
847
916
                    raise errors.BzrError('Invalid line ending request %r' % (line_endings,))
848
 
                content = "contents of %s%s" % (name, end)
849
 
                transport.put(urlescape(name), StringIO(content))
 
917
                content = "contents of %s%s" % (name.encode('utf-8'), end)
 
918
                transport.put(urlutils.escape(name), StringIO(content))
850
919
 
851
920
    def build_tree_contents(self, shape):
852
921
        build_tree_contents(shape)
862
931
    def assertFileEqual(self, content, path):
863
932
        """Fail if path does not contain 'content'."""
864
933
        self.failUnless(osutils.lexists(path))
 
934
        # TODO: jam 20060427 Shouldn't this be 'rb'?
865
935
        self.assertEqualDiff(content, open(path, 'r').read())
866
936
 
867
937
 
943
1013
        if relpath is not None and relpath != '.':
944
1014
            if not base.endswith('/'):
945
1015
                base = base + '/'
946
 
            base = base + relpath
 
1016
            base = base + urlutils.escape(relpath)
947
1017
        return base
948
1018
 
949
1019
    def get_transport(self):
970
1040
    def make_bzrdir(self, relpath, format=None):
971
1041
        try:
972
1042
            url = self.get_url(relpath)
973
 
            segments = relpath.split('/')
 
1043
            mutter('relpath %r => url %r', relpath, url)
 
1044
            segments = url.split('/')
974
1045
            if segments and segments[-1] not in ('', '.'):
975
 
                parent = self.get_url('/'.join(segments[:-1]))
 
1046
                parent = '/'.join(segments[:-1])
976
1047
                t = get_transport(parent)
977
1048
                try:
978
1049
                    t.mkdir(segments[-1])
1114
1185
                   'bzrlib.tests.test_api',
1115
1186
                   'bzrlib.tests.test_bad_files',
1116
1187
                   'bzrlib.tests.test_branch',
 
1188
                   'bzrlib.tests.test_bundle',
1117
1189
                   'bzrlib.tests.test_bzrdir',
1118
1190
                   'bzrlib.tests.test_command',
1119
1191
                   'bzrlib.tests.test_commit',
1145
1217
                   'bzrlib.tests.test_options',
1146
1218
                   'bzrlib.tests.test_osutils',
1147
1219
                   'bzrlib.tests.test_patch',
 
1220
                   'bzrlib.tests.test_patches',
1148
1221
                   'bzrlib.tests.test_permissions',
1149
1222
                   'bzrlib.tests.test_plugins',
1150
1223
                   'bzrlib.tests.test_progress',
1174
1247
                   'bzrlib.tests.test_tuned_gzip',
1175
1248
                   'bzrlib.tests.test_ui',
1176
1249
                   'bzrlib.tests.test_upgrade',
 
1250
                   'bzrlib.tests.test_urlutils',
1177
1251
                   'bzrlib.tests.test_versionedfile',
1178
1252
                   'bzrlib.tests.test_weave',
1179
1253
                   'bzrlib.tests.test_whitebox',