88
87
except ImportError:
89
88
# lsprof not available
91
from breezy.smart import client, request
92
from breezy.transport import (
90
from ..sixish import (
95
from ..smart import client, request
96
from ..symbol_versioning import (
101
from ..transport import (
96
from breezy.symbol_versioning import (
105
from ..symbol_versioning import (
97
106
deprecated_function,
100
from breezy.tests import (
109
from ..tests import (
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
110
118
# Mark this python module as being part of the implementation
111
119
# of unittest: this gives us better tracebacks where the last
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)
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
893
class StringIOWrapper(object):
894
"""A wrapper around cStringIO which just adds an encoding attribute.
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.
900
class StringIOWrapper(ui_testing.BytesIOWithEncoding):
902
@deprecated_method(deprecated_in((3, 0)))
903
903
def __init__(self, s=None):
905
self.__dict__['_cstring'] = StringIO(s)
907
self.__dict__['_cstring'] = StringIO()
909
def __getattr__(self, name, getattr=getattr):
910
return getattr(self.__dict__['_cstring'], name)
912
def __setattr__(self, name, val):
913
if name == 'encoding':
914
self.__dict__['encoding'] = val
916
return setattr(self._cstring, name, val)
919
class TestUIFactory(TextUIFactory):
920
"""A UI Factory for testing.
922
Hide the progress bar but emit note()s.
924
Allows get_password to be tested without real tty attached.
926
See also CannedInputUIFactory which lets you provide programmatic input in
929
# TODO: Capture progress events at the model level and allow them to be
930
# observed by tests that care.
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
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)
946
def get_non_echoed_password(self):
947
"""Get password from stdin without trying to handle the echo mode"""
948
password = self.stdin.readline()
951
if password[-1] == '\n':
952
password = password[:-1]
955
def make_progress_view(self):
956
return NullProgressView()
904
super(StringIOWrapper, self).__init__(s)
907
TestUIFactory = ui_testing.TestUIFactory
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()
963
916
def isolated_doctest_tearDown(test):
964
917
restore_os_environ(test)
918
ui.ui_factory = test._orig_ui_factory
967
921
def IsolatedDocTestSuite(*args, **kwargs):
1510
1464
list(func(*args, **kwargs))
1465
except excClass as e:
1514
1468
if getattr(excClass,'__name__', None) is not None:
1515
1469
excName = excClass.__name__
1517
1471
excName = str(excClass)
1518
raise self.failureException, "%s not raised" % excName
1472
raise self.failureException("%s not raised" % excName)
1520
1474
def assertRaises(self, excClass, callableObj, *args, **kwargs):
1521
1475
"""Assert that a callable raises a particular exception.
1987
1941
def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
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,
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
2010
1958
self.log('run brz: %r', args)
1960
stdout = ui_testing.BytesIOWithEncoding()
1961
stderr = ui_testing.BytesIOWithEncoding()
1962
stdout.encoding = stderr.encoding = encoding
2011
1964
# FIXME: don't call into logging here
2012
handler = trace.EncodedStreamHandler(stderr, errors="replace",
1965
handler = trace.EncodedStreamHandler(
1966
stderr, errors="replace", level=logging.INFO)
2014
1967
logger = logging.getLogger('')
2015
1968
logger.addHandler(handler)
1970
self._last_cmd_stdout = codecs.getwriter(encoding)(stdout)
1971
self._last_cmd_stderr = codecs.getwriter(encoding)(stderr)
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(
1976
stdout=self._last_cmd_stdout,
1977
stderr=self._last_cmd_stderr)
2020
1980
if working_dir is not None:
2022
1982
os.chdir(working_dir)
2026
result = self.apply_redirected(
2027
ui.ui_factory.stdin,
2029
_mod_commands.run_bzr_catch_user_errors,
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()
2038
self.log('output:\n%r', out)
2040
self.log('errors:\n%r', err)
2041
raise KeyboardInterrupt(out, err)
1985
result = self.apply_redirected(
1986
ui.ui_factory.stdin,
1988
_mod_commands.run_bzr_catch_user_errors,
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
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.
2063
2011
The argument list should not include the brz program name - the
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)
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)
2222
2170
bzr_path = self.get_brz_path()
2389
2337
self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
2391
2339
def make_utf8_encoded_stringio(self, encoding_type=None):
2392
"""Return a StringIOWrapper instance, that will encode Unicode
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'
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
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)
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
3873
3822
def includes(self, test_id):
3874
return self.tests.has_key(test_id)
3823
return test_id in self.tests
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))
4229
4178
if len(doc_suite._tests) == 0:
4230
4179
raise errors.BzrError("no doctests found in %s" % (mod,))
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)
4446
4395
dirname = dirname.encode(sys.getfilesystemencoding())
4448
4397
osutils.rmtree(dirname)
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.