/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 breezy/tests/__init__.py

  • Committer: Jelmer Vernooij
  • Date: 2017-05-22 00:56:52 UTC
  • mfrom: (6621.2.26 py3_pokes)
  • Revision ID: jelmer@jelmer.uk-20170522005652-yjahcr9hwmjkno7n
Merge Python3 porting work ('py3 pokes')

Show diffs side-by-side

added added

removed removed

Lines of Context:
26
26
import atexit
27
27
import codecs
28
28
import copy
29
 
from cStringIO import StringIO
30
29
import difflib
31
30
import doctest
32
31
import errno
59
58
from testtools import content
60
59
 
61
60
import breezy
62
 
from breezy import (
 
61
from .. import (
63
62
    branchbuilder,
64
63
    controldir,
65
64
    chk_map,
88
87
except ImportError:
89
88
    # lsprof not available
90
89
    pass
91
 
from breezy.smart import client, request
92
 
from breezy.transport import (
 
90
from ..sixish import (
 
91
    BytesIO,
 
92
    string_types,
 
93
    text_type,
 
94
    )
 
95
from ..smart import client, request
 
96
from ..symbol_versioning import (
 
97
    deprecated_function,
 
98
    deprecated_in,
 
99
    deprecated_method,
 
100
    )
 
101
from ..transport import (
93
102
    memory,
94
103
    pathfilter,
95
104
    )
96
 
from breezy.symbol_versioning import (
 
105
from ..symbol_versioning import (
97
106
    deprecated_function,
98
107
    deprecated_in,
99
108
    )
100
 
from breezy.tests import (
 
109
from ..tests import (
101
110
    fixtures,
102
111
    test_server,
103
112
    TestUtil,
104
113
    treeshape,
 
114
    ui_testing,
105
115
    )
106
 
from breezy.ui import NullProgressView
107
 
from breezy.ui.text import TextUIFactory
108
 
from breezy.tests.features import _CompatabilityThunkFeature
 
116
from ..tests.features import _CompatabilityThunkFeature
109
117
 
110
118
# Mark this python module as being part of the implementation
111
119
# of unittest: this gives us better tracebacks where the last
159
167
    # Make sure that any text ui tests are consistent regardless of
160
168
    # the environment the test case is run in; you may want tests that
161
169
    # test other combinations.  'dumb' is a reasonable guess for tests
162
 
    # going to a pipe or a StringIO.
 
170
    # going to a pipe or a BytesIO.
163
171
    'TERM': 'dumb',
164
172
    'LINES': '25',
165
173
    'COLUMNS': '80',
198
206
    """
199
207
    if env is None:
200
208
        env = isolated_environ
201
 
    test._original_os_environ = dict([(var, value)
202
 
                                      for var, value in os.environ.iteritems()])
203
 
    for var, value in env.iteritems():
204
 
        osutils.set_or_unset_env(var, value)
 
209
    test._original_os_environ = dict(**os.environ)
 
210
    for var in env:
 
211
        osutils.set_or_unset_env(var, env[var])
205
212
        if var not in test._original_os_environ:
206
213
            # The var is new, add it with a value of None, so
207
214
            # restore_os_environ will delete it
213
220
 
214
221
    :param test: A test instance previously passed to override_os_environ.
215
222
    """
216
 
    for var, value in test._original_os_environ.iteritems():
 
223
    for var, value in test._original_os_environ.items():
217
224
        # Restore the original value (or delete it if the value has been set to
218
225
        # None in override_os_environ).
219
226
        osutils.set_or_unset_env(var, value)
792
799
        # to encode using ascii.
793
800
        new_encoding = osutils.get_terminal_encoding()
794
801
        codec = codecs.lookup(new_encoding)
795
 
        if type(codec) is tuple:
 
802
        if isinstance(codec, tuple):
796
803
            # Python 2.4
797
804
            encode = codec[0]
798
805
        else:
890
897
    """
891
898
 
892
899
 
893
 
class StringIOWrapper(object):
894
 
    """A wrapper around cStringIO which just adds an encoding attribute.
895
 
 
896
 
    Internally we can check sys.stdout to see what the output encoding
897
 
    should be. However, cStringIO has no encoding attribute that we can
898
 
    set. So we wrap it instead.
899
 
    """
900
 
    encoding='ascii'
901
 
    _cstring = None
902
 
 
 
900
class StringIOWrapper(ui_testing.BytesIOWithEncoding):
 
901
 
 
902
    @deprecated_method(deprecated_in((3, 0)))
903
903
    def __init__(self, s=None):
904
 
        if s is not None:
905
 
            self.__dict__['_cstring'] = StringIO(s)
906
 
        else:
907
 
            self.__dict__['_cstring'] = StringIO()
908
 
 
909
 
    def __getattr__(self, name, getattr=getattr):
910
 
        return getattr(self.__dict__['_cstring'], name)
911
 
 
912
 
    def __setattr__(self, name, val):
913
 
        if name == 'encoding':
914
 
            self.__dict__['encoding'] = val
915
 
        else:
916
 
            return setattr(self._cstring, name, val)
917
 
 
918
 
 
919
 
class TestUIFactory(TextUIFactory):
920
 
    """A UI Factory for testing.
921
 
 
922
 
    Hide the progress bar but emit note()s.
923
 
    Redirect stdin.
924
 
    Allows get_password to be tested without real tty attached.
925
 
 
926
 
    See also CannedInputUIFactory which lets you provide programmatic input in
927
 
    a structured way.
928
 
    """
929
 
    # TODO: Capture progress events at the model level and allow them to be
930
 
    # observed by tests that care.
931
 
    #
932
 
    # XXX: Should probably unify more with CannedInputUIFactory or a
933
 
    # particular configuration of TextUIFactory, or otherwise have a clearer
934
 
    # idea of how they're supposed to be different.
935
 
    # See https://bugs.launchpad.net/bzr/+bug/408213
936
 
 
937
 
    def __init__(self, stdout=None, stderr=None, stdin=None):
938
 
        if stdin is not None:
939
 
            # We use a StringIOWrapper to be able to test various
940
 
            # encodings, but the user is still responsible to
941
 
            # encode the string and to set the encoding attribute
942
 
            # of StringIOWrapper.
943
 
            stdin = StringIOWrapper(stdin)
944
 
        super(TestUIFactory, self).__init__(stdin, stdout, stderr)
945
 
 
946
 
    def get_non_echoed_password(self):
947
 
        """Get password from stdin without trying to handle the echo mode"""
948
 
        password = self.stdin.readline()
949
 
        if not password:
950
 
            raise EOFError
951
 
        if password[-1] == '\n':
952
 
            password = password[:-1]
953
 
        return password
954
 
 
955
 
    def make_progress_view(self):
956
 
        return NullProgressView()
 
904
        super(StringIOWrapper, self).__init__(s)
 
905
 
 
906
 
 
907
TestUIFactory = ui_testing.TestUIFactory
957
908
 
958
909
 
959
910
def isolated_doctest_setUp(test):
960
911
    override_os_environ(test)
 
912
    test._orig_ui_factory = ui.ui_factory
 
913
    ui.ui_factory = ui.SilentUIFactory()
961
914
 
962
915
 
963
916
def isolated_doctest_tearDown(test):
964
917
    restore_os_environ(test)
 
918
    ui.ui_factory = test._orig_ui_factory
965
919
 
966
920
 
967
921
def IsolatedDocTestSuite(*args, **kwargs):
1087
1041
        _counters = self._counters # Avoid closing over self
1088
1042
        if counter_name is None:
1089
1043
            counter_name = name
1090
 
        if _counters.has_key(counter_name):
 
1044
        if counter_name in _counters:
1091
1045
            raise AssertionError('%s is already used as a counter name'
1092
1046
                                  % (counter_name,))
1093
1047
        _counters[counter_name] = 0
1184
1138
                (acquired_locks, released_locks, broken_locks))
1185
1139
            if not self._lock_check_thorough:
1186
1140
                # Rather than fail, just warn
1187
 
                print "Broken test %s: %s" % (self, message)
 
1141
                print("Broken test %s: %s" % (self, message))
1188
1142
                return
1189
1143
            self.fail(message)
1190
1144
 
1359
1313
        try:
1360
1314
            if a == b:
1361
1315
                return
1362
 
        except UnicodeError, e:
 
1316
        except UnicodeError as e:
1363
1317
            # If we can't compare without getting a UnicodeError, then
1364
1318
            # obviously they are different
1365
1319
            trace.mutter('UnicodeError: %s', e)
1508
1462
        """
1509
1463
        try:
1510
1464
            list(func(*args, **kwargs))
1511
 
        except excClass, e:
 
1465
        except excClass as e:
1512
1466
            return e
1513
1467
        else:
1514
1468
            if getattr(excClass,'__name__', None) is not None:
1515
1469
                excName = excClass.__name__
1516
1470
            else:
1517
1471
                excName = str(excClass)
1518
 
            raise self.failureException, "%s not raised" % excName
 
1472
            raise self.failureException("%s not raised" % excName)
1519
1473
 
1520
1474
    def assertRaises(self, excClass, callableObj, *args, **kwargs):
1521
1475
        """Assert that a callable raises a particular exception.
1529
1483
        """
1530
1484
        try:
1531
1485
            callableObj(*args, **kwargs)
1532
 
        except excClass, e:
 
1486
        except excClass as e:
1533
1487
            return e
1534
1488
        else:
1535
1489
            if getattr(excClass,'__name__', None) is not None:
1537
1491
            else:
1538
1492
                # probably a tuple
1539
1493
                excName = str(excClass)
1540
 
            raise self.failureException, "%s not raised" % excName
 
1494
            raise self.failureException("%s not raised" % excName)
1541
1495
 
1542
1496
    def assertIs(self, left, right, message=None):
1543
1497
        if not (left is right):
1743
1697
        return result
1744
1698
 
1745
1699
    def _startLogFile(self):
1746
 
        """Setup a in-memory target for brz and testcase log messages"""
1747
 
        pseudo_log_file = StringIO()
 
1700
        """Setup a in-memory target for bzr and testcase log messages"""
 
1701
        pseudo_log_file = BytesIO()
1748
1702
        def _get_log_contents_for_weird_testtools_api():
1749
1703
            return [pseudo_log_file.getvalue().decode(
1750
1704
                "utf-8", "replace").encode("utf-8")]
1840
1794
        return calls
1841
1795
 
1842
1796
    def _cleanEnvironment(self):
1843
 
        for name, value in isolated_environ.iteritems():
 
1797
        for name, value in isolated_environ.items():
1844
1798
            self.overrideEnv(name, value)
1845
1799
 
1846
1800
    def _restoreHooks(self):
1987
1941
    def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
1988
1942
            working_dir):
1989
1943
        """Run bazaar command line, splitting up a string command line."""
1990
 
        if isinstance(args, basestring):
1991
 
            # shlex don't understand unicode strings,
1992
 
            # so args should be plain string (bialix 20070906)
1993
 
            args = list(shlex.split(str(args)))
 
1944
        if isinstance(args, string_types):
 
1945
            args = shlex.split(args)
1994
1946
        return self._run_bzr_core(args, retcode=retcode,
1995
1947
                encoding=encoding, stdin=stdin, working_dir=working_dir,
1996
1948
                )
2002
1954
        chk_map.clear_cache()
2003
1955
        if encoding is None:
2004
1956
            encoding = osutils.get_user_encoding()
2005
 
        stdout = StringIOWrapper()
2006
 
        stderr = StringIOWrapper()
2007
 
        stdout.encoding = encoding
2008
 
        stderr.encoding = encoding
2009
1957
 
2010
1958
        self.log('run brz: %r', args)
 
1959
 
 
1960
        stdout = ui_testing.BytesIOWithEncoding()
 
1961
        stderr = ui_testing.BytesIOWithEncoding()
 
1962
        stdout.encoding = stderr.encoding = encoding
 
1963
 
2011
1964
        # FIXME: don't call into logging here
2012
 
        handler = trace.EncodedStreamHandler(stderr, errors="replace",
2013
 
            level=logging.INFO)
 
1965
        handler = trace.EncodedStreamHandler(
 
1966
            stderr, errors="replace", level=logging.INFO)
2014
1967
        logger = logging.getLogger('')
2015
1968
        logger.addHandler(handler)
 
1969
 
 
1970
        self._last_cmd_stdout = codecs.getwriter(encoding)(stdout)
 
1971
        self._last_cmd_stderr = codecs.getwriter(encoding)(stderr)
 
1972
 
2016
1973
        old_ui_factory = ui.ui_factory
2017
 
        ui.ui_factory = TestUIFactory(stdin=stdin, stdout=stdout, stderr=stderr)
 
1974
        ui.ui_factory = ui_testing.TestUIFactory(
 
1975
            stdin=stdin,
 
1976
            stdout=self._last_cmd_stdout,
 
1977
            stderr=self._last_cmd_stderr)
2018
1978
 
2019
1979
        cwd = None
2020
1980
        if working_dir is not None:
2022
1982
            os.chdir(working_dir)
2023
1983
 
2024
1984
        try:
2025
 
            try:
2026
 
                result = self.apply_redirected(
2027
 
                    ui.ui_factory.stdin,
2028
 
                    stdout, stderr,
2029
 
                    _mod_commands.run_bzr_catch_user_errors,
2030
 
                    args)
2031
 
            except KeyboardInterrupt:
2032
 
                # Reraise KeyboardInterrupt with contents of redirected stdout
2033
 
                # and stderr as arguments, for tests which are interested in
2034
 
                # stdout and stderr and are expecting the exception.
2035
 
                out = stdout.getvalue()
2036
 
                err = stderr.getvalue()
2037
 
                if out:
2038
 
                    self.log('output:\n%r', out)
2039
 
                if err:
2040
 
                    self.log('errors:\n%r', err)
2041
 
                raise KeyboardInterrupt(out, err)
 
1985
            result = self.apply_redirected(
 
1986
                ui.ui_factory.stdin,
 
1987
                stdout, stderr,
 
1988
                _mod_commands.run_bzr_catch_user_errors,
 
1989
                args)
2042
1990
        finally:
2043
1991
            logger.removeHandler(handler)
2044
1992
            ui.ui_factory = old_ui_factory
2056
2004
                              message='Unexpected return code')
2057
2005
        return result, out, err
2058
2006
 
2059
 
    def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
2060
 
                working_dir=None, error_regexes=[], output_encoding=None):
 
2007
    def run_bzr(self, args, retcode=0, stdin=None, encoding=None,
 
2008
                working_dir=None, error_regexes=[]):
2061
2009
        """Invoke brz, as if it were run from the command line.
2062
2010
 
2063
2011
        The argument list should not include the brz program name - the
2212
2160
        old_env = {}
2213
2161
 
2214
2162
        def cleanup_environment():
2215
 
            for env_var, value in env_changes.iteritems():
 
2163
            for env_var, value in env_changes.items():
2216
2164
                old_env[env_var] = osutils.set_or_unset_env(env_var, value)
2217
2165
 
2218
2166
        def restore_environment():
2219
 
            for env_var, value in old_env.iteritems():
 
2167
            for env_var, value in old_env.items():
2220
2168
                osutils.set_or_unset_env(env_var, value)
2221
2169
 
2222
2170
        bzr_path = self.get_brz_path()
2356
2304
        if not callable(a_callable):
2357
2305
            raise ValueError("a_callable must be callable.")
2358
2306
        if stdin is None:
2359
 
            stdin = StringIO("")
 
2307
            stdin = BytesIO("")
2360
2308
        if stdout is None:
2361
2309
            if getattr(self, "_log_file", None) is not None:
2362
2310
                stdout = self._log_file
2363
2311
            else:
2364
 
                stdout = StringIO()
 
2312
                stdout = BytesIO()
2365
2313
        if stderr is None:
2366
2314
            if getattr(self, "_log_file", None is not None):
2367
2315
                stderr = self._log_file
2368
2316
            else:
2369
 
                stderr = StringIO()
 
2317
                stderr = BytesIO()
2370
2318
        real_stdin = sys.stdin
2371
2319
        real_stdout = sys.stdout
2372
2320
        real_stderr = sys.stderr
2389
2337
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
2390
2338
 
2391
2339
    def make_utf8_encoded_stringio(self, encoding_type=None):
2392
 
        """Return a StringIOWrapper instance, that will encode Unicode
2393
 
        input to UTF-8.
2394
 
        """
 
2340
        """Return a wrapped BytesIO, that will encode text input to UTF-8."""
2395
2341
        if encoding_type is None:
2396
2342
            encoding_type = 'strict'
2397
 
        sio = StringIO()
 
2343
        bio = BytesIO()
2398
2344
        output_encoding = 'utf-8'
2399
 
        sio = codecs.getwriter(output_encoding)(sio, errors=encoding_type)
 
2345
        sio = codecs.getwriter(output_encoding)(bio, errors=encoding_type)
2400
2346
        sio.encoding = output_encoding
2401
2347
        return sio
2402
2348
 
2410
2356
        self.addCleanup(request_handlers.register, verb, orig_method,
2411
2357
            info=orig_info)
2412
2358
 
 
2359
    def __hash__(self):
 
2360
        return id(self)
 
2361
 
2413
2362
 
2414
2363
class CapturedCall(object):
2415
2364
    """A helper for capturing smart server calls for easy debug analysis."""
2484
2433
            _add_disconnect_cleanup, None)
2485
2434
 
2486
2435
        self._make_test_root()
2487
 
        self.addCleanup(os.chdir, os.getcwdu())
 
2436
        self.addCleanup(os.chdir, osutils.getcwd())
2488
2437
        self.makeAndChdirToTestDir()
2489
2438
        self.overrideEnvironmentForTesting()
2490
2439
        self.__readonly_server = None
2651
2600
            os.environ['BRZ_HOME'] = root
2652
2601
            wt = controldir.ControlDir.create_standalone_workingtree(root)
2653
2602
            del os.environ['BRZ_HOME']
2654
 
        except Exception, e:
 
2603
        except Exception as e:
2655
2604
            self.fail("Fail to initialize the safety net: %r\n" % (e,))
2656
2605
        # Hack for speed: remember the raw bytes of the dirstate file so that
2657
2606
        # we don't need to re-open the wt to check it hasn't changed.
2776
2725
 
2777
2726
    def overrideEnvironmentForTesting(self):
2778
2727
        test_home_dir = self.test_home_dir
2779
 
        if isinstance(test_home_dir, unicode):
 
2728
        if isinstance(test_home_dir, text_type):
2780
2729
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
2781
2730
        self.overrideEnv('HOME', test_home_dir)
2782
2731
        self.overrideEnv('BRZ_HOME', test_home_dir)
3399
3348
 
3400
3349
def random_order(random_seed, runner):
3401
3350
    """Return a test suite decorator factory for randomising tests order.
3402
 
    
3403
 
    :param random_seed: now, a string which casts to a long, or a long.
 
3351
 
 
3352
    :param random_seed: now, a string which casts to an integer, or an integer.
3404
3353
    :param runner: A test runner with a stream attribute to report on.
3405
3354
    """
3406
3355
    if random_seed is None:
3478
3427
    @staticmethod
3479
3428
    def actual_seed(seed):
3480
3429
        if seed == "now":
3481
 
            # We convert the seed to a long to make it reuseable across
 
3430
            # We convert the seed to an integer to make it reuseable across
3482
3431
            # invocations (because the user can reenter it).
3483
 
            return long(time.time())
 
3432
            return int(time.time())
3484
3433
        else:
3485
 
            # Convert the seed to a long if we can
 
3434
            # Convert the seed to an integer if we can
3486
3435
            try:
3487
 
                return long(seed)
 
3436
                return int(seed)
3488
3437
            except (TypeError, ValueError):
3489
3438
                pass
3490
3439
        return seed
3783
3732
    test_list = []
3784
3733
    try:
3785
3734
        ftest = open(file_name, 'rt')
3786
 
    except IOError, e:
 
3735
    except IOError as e:
3787
3736
        if e.errno != errno.ENOENT:
3788
3737
            raise
3789
3738
        else:
3868
3817
 
3869
3818
    def refers_to(self, module_name):
3870
3819
        """Is there tests for the module or one of its sub modules."""
3871
 
        return self.modules.has_key(module_name)
 
3820
        return module_name in self.modules
3872
3821
 
3873
3822
    def includes(self, test_id):
3874
 
        return self.tests.has_key(test_id)
 
3823
        return test_id in self.tests
3875
3824
 
3876
3825
 
3877
3826
class TestPrefixAliasRegistry(registry.Registry):
4223
4172
            # still runs the rest of the examples
4224
4173
            doc_suite = IsolatedDocTestSuite(
4225
4174
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
4226
 
        except ValueError, e:
4227
 
            print '**failed to get doctest for: %s\n%s' % (mod, e)
 
4175
        except ValueError as e:
 
4176
            print('**failed to get doctest for: %s\n%s' % (mod, e))
4228
4177
            raise
4229
4178
        if len(doc_suite._tests) == 0:
4230
4179
            raise errors.BzrError("no doctests found in %s" % (mod,))
4413
4362
        the module is available.
4414
4363
    """
4415
4364
 
4416
 
    from breezy.tests.features import ModuleAvailableFeature
 
4365
    from .features import ModuleAvailableFeature
4417
4366
    py_module = pyutils.get_named_object(py_module_name)
4418
4367
    scenarios = [
4419
4368
        ('python', {'module': py_module}),
4441
4390
    # (they are either ascii or mbcs)
4442
4391
    if sys.platform == 'win32':
4443
4392
        # make sure we are using the unicode win32 api
4444
 
        dirname = unicode(dirname)
 
4393
        dirname = text_type(dirname)
4445
4394
    else:
4446
4395
        dirname = dirname.encode(sys.getfilesystemencoding())
4447
4396
    try:
4448
4397
        osutils.rmtree(dirname)
4449
 
    except OSError, e:
 
4398
    except OSError as e:
4450
4399
        # We don't want to fail here because some useful display will be lost
4451
4400
        # otherwise. Polluting the tmp dir is bad, but not giving all the
4452
4401
        # possible info to the test runner is even worse.