summaryrefslogtreecommitdiffstats
path: root/Lib/test
diff options
context:
space:
mode:
authorLarry Hastings <larry@hastings.org>2016-06-27 02:53:18 (GMT)
committerLarry Hastings <larry@hastings.org>2016-06-27 02:53:18 (GMT)
commit1b329e791ae3a3a2989f05e8c2019b67b4e1a7df (patch)
tree91e137c00f35f21a2c17b385f9746492b8347558 /Lib/test
parent9bb200545970bb920c83124658cb89c7d295166d (diff)
parent1e957d145fa1fc05ca1fbb9f135ab162c939ae14 (diff)
downloadcpython-1b329e791ae3a3a2989f05e8c2019b67b4e1a7df.zip
cpython-1b329e791ae3a3a2989f05e8c2019b67b4e1a7df.tar.gz
cpython-1b329e791ae3a3a2989f05e8c2019b67b4e1a7df.tar.bz2
Merge.
Diffstat (limited to 'Lib/test')
-rw-r--r--Lib/test/support/__init__.py3
-rw-r--r--Lib/test/support/script_helper.py4
-rw-r--r--Lib/test/test_asyncio/test_base_events.py8
-rw-r--r--Lib/test/test_compile.py7
-rw-r--r--Lib/test/test_contextlib.py34
-rw-r--r--Lib/test/test_coroutines.py2
-rw-r--r--Lib/test/test_curses.py54
-rw-r--r--Lib/test/test_decimal.py5
-rw-r--r--Lib/test/test_doctest.py24
-rw-r--r--Lib/test/test_extcall.py4
-rw-r--r--Lib/test/test_functools.py61
-rw-r--r--Lib/test/test_importlib/test_lazy.py16
-rw-r--r--Lib/test/test_parser.py16
-rw-r--r--Lib/test/test_pydoc.py2
-rw-r--r--Lib/test/test_readline.py161
-rw-r--r--Lib/test/test_symtable.py6
-rw-r--r--Lib/test/test_unpack_ex.py5
-rw-r--r--Lib/test/test_xml_etree.py8
-rw-r--r--Lib/test/test_zipimport.py15
19 files changed, 402 insertions, 33 deletions
diff --git a/Lib/test/support/__init__.py b/Lib/test/support/__init__.py
index e124fab..c9e36fb 100644
--- a/Lib/test/support/__init__.py
+++ b/Lib/test/support/__init__.py
@@ -1349,7 +1349,8 @@ def transient_internet(resource_name, *, timeout=30.0, errnos=()):
500 <= err.code <= 599) or
(isinstance(err, urllib.error.URLError) and
(("ConnectionRefusedError" in err.reason) or
- ("TimeoutError" in err.reason))) or
+ ("TimeoutError" in err.reason) or
+ ("EOFError" in err.reason))) or
n in captured_errnos):
if not verbose:
sys.stderr.write(denied.args[0] + "\n")
diff --git a/Lib/test/support/script_helper.py b/Lib/test/support/script_helper.py
index 9c2e9eb..c45d010 100644
--- a/Lib/test/support/script_helper.py
+++ b/Lib/test/support/script_helper.py
@@ -73,6 +73,10 @@ def run_python_until_end(*args, **env_vars):
# Need to preserve the original environment, for in-place testing of
# shared library builds.
env = os.environ.copy()
+ # set TERM='' unless the TERM environment variable is passed explicitly
+ # see issues #11390 and #18300
+ if 'TERM' not in env_vars:
+ env['TERM'] = ''
# But a special flag that can be set to override -- in this case, the
# caller is responsible to pass the full environment.
if env_vars.pop('__cleanenv', None):
diff --git a/Lib/test/test_asyncio/test_base_events.py b/Lib/test/test_asyncio/test_base_events.py
index 0807dfb..206ebc6 100644
--- a/Lib/test/test_asyncio/test_base_events.py
+++ b/Lib/test/test_asyncio/test_base_events.py
@@ -1185,14 +1185,14 @@ class BaseEventLoopWithSelectorTests(test_utils.TestCase):
test_utils.run_briefly(self.loop) # allow transport to close
sock.family = socket.AF_INET6
- coro = self.loop.create_connection(asyncio.Protocol, '::2', 80)
+ coro = self.loop.create_connection(asyncio.Protocol, '::1', 80)
t, p = self.loop.run_until_complete(coro)
try:
- # Without inet_pton we use getaddrinfo, which transforms ('::2', 80)
- # to ('::0.0.0.2', 80, 0, 0). The last 0s are flow info, scope id.
+ # Without inet_pton we use getaddrinfo, which transforms ('::1', 80)
+ # to ('::1', 80, 0, 0). The last 0s are flow info, scope id.
[address] = sock.connect.call_args[0]
host, port = address[:2]
- self.assertRegex(host, r'::(0\.)*2')
+ self.assertRegex(host, r'::(0\.)*1')
self.assertEqual(port, 80)
_, kwargs = m_socket.socket.call_args
self.assertEqual(kwargs['family'], m_socket.AF_INET6)
diff --git a/Lib/test/test_compile.py b/Lib/test/test_compile.py
index e0fdee3..824e843 100644
--- a/Lib/test/test_compile.py
+++ b/Lib/test/test_compile.py
@@ -472,6 +472,13 @@ if 1:
d = {f(): f(), f(): f()}
self.assertEqual(d, {1: 2, 3: 4})
+ def test_compile_filename(self):
+ for filename in ('file.py', b'file.py',
+ bytearray(b'file.py'), memoryview(b'file.py')):
+ code = compile('pass', filename, 'exec')
+ self.assertEqual(code.co_filename, 'file.py')
+ self.assertRaises(TypeError, compile, 'pass', list(b'file.py'), 'exec')
+
@support.cpython_only
def test_same_filename_used(self):
s = """def f(): pass\ndef g(): pass"""
diff --git a/Lib/test/test_contextlib.py b/Lib/test/test_contextlib.py
index 30a6377..516403e 100644
--- a/Lib/test/test_contextlib.py
+++ b/Lib/test/test_contextlib.py
@@ -762,6 +762,40 @@ class TestExitStack(unittest.TestCase):
stack.push(cm)
self.assertIs(stack._exit_callbacks[-1], cm)
+ def test_dont_reraise_RuntimeError(self):
+ # https://bugs.python.org/issue27122
+ class UniqueException(Exception): pass
+ class UniqueRuntimeError(RuntimeError): pass
+
+ @contextmanager
+ def second():
+ try:
+ yield 1
+ except Exception as exc:
+ raise UniqueException("new exception") from exc
+
+ @contextmanager
+ def first():
+ try:
+ yield 1
+ except Exception as exc:
+ raise exc
+
+ # The UniqueRuntimeError should be caught by second()'s exception
+ # handler which chain raised a new UniqueException.
+ with self.assertRaises(UniqueException) as err_ctx:
+ with ExitStack() as es_ctx:
+ es_ctx.enter_context(second())
+ es_ctx.enter_context(first())
+ raise UniqueRuntimeError("please no infinite loop.")
+
+ exc = err_ctx.exception
+ self.assertIsInstance(exc, UniqueException)
+ self.assertIsInstance(exc.__context__, UniqueRuntimeError)
+ self.assertIsNone(exc.__context__.__context__)
+ self.assertIsNone(exc.__context__.__cause__)
+ self.assertIs(exc.__cause__, exc.__context__)
+
class TestRedirectStream:
diff --git a/Lib/test/test_coroutines.py b/Lib/test/test_coroutines.py
index 4f725ae..d0cefb0 100644
--- a/Lib/test/test_coroutines.py
+++ b/Lib/test/test_coroutines.py
@@ -1423,7 +1423,7 @@ class CoroutineTest(unittest.TestCase):
with warnings.catch_warnings():
warnings.simplefilter("error")
- # Test that __aiter__ that returns an asyncronous iterator
+ # Test that __aiter__ that returns an asynchronous iterator
# directly does not throw any warnings.
run_async(main())
self.assertEqual(I, 111011)
diff --git a/Lib/test/test_curses.py b/Lib/test/test_curses.py
index 8411cdb..897d738 100644
--- a/Lib/test/test_curses.py
+++ b/Lib/test/test_curses.py
@@ -10,6 +10,7 @@
#
import os
+import string
import sys
import tempfile
import unittest
@@ -399,6 +400,55 @@ class MiscTests(unittest.TestCase):
class TestAscii(unittest.TestCase):
+ def test_controlnames(self):
+ for name in curses.ascii.controlnames:
+ self.assertTrue(hasattr(curses.ascii, name), name)
+
+ def test_ctypes(self):
+ def check(func, expected):
+ with self.subTest(ch=c, func=func):
+ self.assertEqual(func(i), expected)
+ self.assertEqual(func(c), expected)
+
+ for i in range(256):
+ c = chr(i)
+ b = bytes([i])
+ check(curses.ascii.isalnum, b.isalnum())
+ check(curses.ascii.isalpha, b.isalpha())
+ check(curses.ascii.isdigit, b.isdigit())
+ check(curses.ascii.islower, b.islower())
+ check(curses.ascii.isspace, b.isspace())
+ check(curses.ascii.isupper, b.isupper())
+
+ check(curses.ascii.isascii, i < 128)
+ check(curses.ascii.ismeta, i >= 128)
+ check(curses.ascii.isctrl, i < 32)
+ check(curses.ascii.iscntrl, i < 32 or i == 127)
+ check(curses.ascii.isblank, c in ' \t')
+ check(curses.ascii.isgraph, 32 < i <= 126)
+ check(curses.ascii.isprint, 32 <= i <= 126)
+ check(curses.ascii.ispunct, c in string.punctuation)
+ check(curses.ascii.isxdigit, c in string.hexdigits)
+
+ def test_ascii(self):
+ ascii = curses.ascii.ascii
+ self.assertEqual(ascii('\xc1'), 'A')
+ self.assertEqual(ascii('A'), 'A')
+ self.assertEqual(ascii(ord('\xc1')), ord('A'))
+
+ def test_ctrl(self):
+ ctrl = curses.ascii.ctrl
+ self.assertEqual(ctrl('J'), '\n')
+ self.assertEqual(ctrl('\n'), '\n')
+ self.assertEqual(ctrl('@'), '\0')
+ self.assertEqual(ctrl(ord('J')), ord('\n'))
+
+ def test_alt(self):
+ alt = curses.ascii.alt
+ self.assertEqual(alt('\n'), '\x8a')
+ self.assertEqual(alt('A'), '\xc1')
+ self.assertEqual(alt(ord('A')), 0xc1)
+
def test_unctrl(self):
unctrl = curses.ascii.unctrl
self.assertEqual(unctrl('a'), 'a')
@@ -408,9 +458,13 @@ class TestAscii(unittest.TestCase):
self.assertEqual(unctrl('\x7f'), '^?')
self.assertEqual(unctrl('\n'), '^J')
self.assertEqual(unctrl('\0'), '^@')
+ self.assertEqual(unctrl(ord('A')), 'A')
+ self.assertEqual(unctrl(ord('\n')), '^J')
# Meta-bit characters
self.assertEqual(unctrl('\x8a'), '!^J')
self.assertEqual(unctrl('\xc1'), '!A')
+ self.assertEqual(unctrl(ord('\x8a')), '!^J')
+ self.assertEqual(unctrl(ord('\xc1')), '!A')
if __name__ == '__main__':
diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py
index c0d21b1..cde5d78 100644
--- a/Lib/test/test_decimal.py
+++ b/Lib/test/test_decimal.py
@@ -2491,7 +2491,8 @@ class PythonAPItests(unittest.TestCase):
Decimal = self.decimal.Decimal
class MyDecimal(Decimal):
- pass
+ def __init__(self, _):
+ self.x = 'y'
self.assertTrue(issubclass(MyDecimal, Decimal))
@@ -2499,6 +2500,8 @@ class PythonAPItests(unittest.TestCase):
self.assertEqual(type(r), MyDecimal)
self.assertEqual(str(r),
'0.1000000000000000055511151231257827021181583404541015625')
+ self.assertEqual(r.x, 'y')
+
bigint = 12345678901234567890123456789
self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint))
self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan())
diff --git a/Lib/test/test_doctest.py b/Lib/test/test_doctest.py
index 29426a3..33163b9 100644
--- a/Lib/test/test_doctest.py
+++ b/Lib/test/test_doctest.py
@@ -2719,12 +2719,6 @@ output into something we can doctest against:
>>> def normalize(s):
... return '\n'.join(s.decode().splitlines())
-Note: we also pass TERM='' to all the assert_python calls to avoid a bug
-in the readline library that is triggered in these tests because we are
-running them in a new python process. See:
-
- http://lists.gnu.org/archive/html/bug-readline/2013-06/msg00000.html
-
With those preliminaries out of the way, we'll start with a file with two
simple tests and no errors. We'll run both the unadorned doctest command, and
the verbose version, and then check the output:
@@ -2741,9 +2735,9 @@ the verbose version, and then check the output:
... _ = f.write('\n')
... _ = f.write('And that is it.\n')
... rc1, out1, err1 = script_helper.assert_python_ok(
- ... '-m', 'doctest', fn, TERM='')
+ ... '-m', 'doctest', fn)
... rc2, out2, err2 = script_helper.assert_python_ok(
- ... '-m', 'doctest', '-v', fn, TERM='')
+ ... '-m', 'doctest', '-v', fn)
With no arguments and passing tests, we should get no output:
@@ -2806,17 +2800,17 @@ text files).
... _ = f.write(' \"\"\"\n')
... import shutil
... rc1, out1, err1 = script_helper.assert_python_failure(
- ... '-m', 'doctest', fn, fn2, TERM='')
+ ... '-m', 'doctest', fn, fn2)
... rc2, out2, err2 = script_helper.assert_python_ok(
- ... '-m', 'doctest', '-o', 'ELLIPSIS', fn, TERM='')
+ ... '-m', 'doctest', '-o', 'ELLIPSIS', fn)
... rc3, out3, err3 = script_helper.assert_python_ok(
... '-m', 'doctest', '-o', 'ELLIPSIS',
- ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2, TERM='')
+ ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
... rc4, out4, err4 = script_helper.assert_python_failure(
- ... '-m', 'doctest', '-f', fn, fn2, TERM='')
+ ... '-m', 'doctest', '-f', fn, fn2)
... rc5, out5, err5 = script_helper.assert_python_ok(
... '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
- ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2, TERM='')
+ ... '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
Our first test run will show the errors from the first file (doctest stops if a
file has errors). Note that doctest test-run error output appears on stdout,
@@ -2922,7 +2916,7 @@ We should also check some typical error cases.
Invalid file name:
>>> rc, out, err = script_helper.assert_python_failure(
- ... '-m', 'doctest', 'nosuchfile', TERM='')
+ ... '-m', 'doctest', 'nosuchfile')
>>> rc, out
(1, b'')
>>> print(normalize(err)) # doctest: +ELLIPSIS
@@ -2933,7 +2927,7 @@ Invalid file name:
Invalid doctest option:
>>> rc, out, err = script_helper.assert_python_failure(
- ... '-m', 'doctest', '-o', 'nosuchoption', TERM='')
+ ... '-m', 'doctest', '-o', 'nosuchoption')
>>> rc, out
(2, b'')
>>> print(normalize(err)) # doctest: +ELLIPSIS
diff --git a/Lib/test/test_extcall.py b/Lib/test/test_extcall.py
index d526b5f..5eea379 100644
--- a/Lib/test/test_extcall.py
+++ b/Lib/test/test_extcall.py
@@ -57,6 +57,10 @@ Here we add keyword arguments
Traceback (most recent call last):
...
TypeError: f() got multiple values for keyword argument 'a'
+ >>> f(1, 2, a=3, **{'a': 4}, **{'a': 5})
+ Traceback (most recent call last):
+ ...
+ TypeError: f() got multiple values for keyword argument 'a'
>>> f(1, 2, 3, *[4, 5], **{'a':6, 'b':7})
(1, 2, 3, 4, 5) {'a': 6, 'b': 7}
>>> f(1, 2, 3, x=4, y=5, *(6, 7), **{'a':8, 'b': 9})
diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py
index 9abe984..ab51a35 100644
--- a/Lib/test/test_functools.py
+++ b/Lib/test/test_functools.py
@@ -217,6 +217,33 @@ class TestPartialC(TestPartial, unittest.TestCase):
['{}({!r}, {}, {})'.format(name, capture, args_repr, kwargs_repr)
for kwargs_repr in kwargs_reprs])
+ def test_recursive_repr(self):
+ if self.partial is c_functools.partial:
+ name = 'functools.partial'
+ else:
+ name = self.partial.__name__
+
+ f = self.partial(capture)
+ f.__setstate__((f, (), {}, {}))
+ try:
+ self.assertEqual(repr(f), '%s(%s(...))' % (name, name))
+ finally:
+ f.__setstate__((capture, (), {}, {}))
+
+ f = self.partial(capture)
+ f.__setstate__((capture, (f,), {}, {}))
+ try:
+ self.assertEqual(repr(f), '%s(%r, %s(...))' % (name, capture, name))
+ finally:
+ f.__setstate__((capture, (), {}, {}))
+
+ f = self.partial(capture)
+ f.__setstate__((capture, (), {'a': f}, {}))
+ try:
+ self.assertEqual(repr(f), '%s(%r, a=%s(...))' % (name, capture, name))
+ finally:
+ f.__setstate__((capture, (), {}, {}))
+
def test_pickle(self):
f = self.partial(signature, ['asdf'], bar=[True])
f.attr = []
@@ -297,6 +324,40 @@ class TestPartialC(TestPartial, unittest.TestCase):
self.assertEqual(r, ((1, 2), {}))
self.assertIs(type(r[0]), tuple)
+ def test_recursive_pickle(self):
+ f = self.partial(capture)
+ f.__setstate__((f, (), {}, {}))
+ try:
+ for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+ with self.assertRaises(RecursionError):
+ pickle.dumps(f, proto)
+ finally:
+ f.__setstate__((capture, (), {}, {}))
+
+ f = self.partial(capture)
+ f.__setstate__((capture, (f,), {}, {}))
+ try:
+ for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+ f_copy = pickle.loads(pickle.dumps(f, proto))
+ try:
+ self.assertIs(f_copy.args[0], f_copy)
+ finally:
+ f_copy.__setstate__((capture, (), {}, {}))
+ finally:
+ f.__setstate__((capture, (), {}, {}))
+
+ f = self.partial(capture)
+ f.__setstate__((capture, (), {'a': f}, {}))
+ try:
+ for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+ f_copy = pickle.loads(pickle.dumps(f, proto))
+ try:
+ self.assertIs(f_copy.keywords['a'], f_copy)
+ finally:
+ f_copy.__setstate__((capture, (), {}, {}))
+ finally:
+ f.__setstate__((capture, (), {}, {}))
+
# Issue 6083: Reference counting bug
def test_setstate_refcount(self):
class BadSequence:
diff --git a/Lib/test/test_importlib/test_lazy.py b/Lib/test/test_importlib/test_lazy.py
index 774b7a4..cc383c2 100644
--- a/Lib/test/test_importlib/test_lazy.py
+++ b/Lib/test/test_importlib/test_lazy.py
@@ -1,6 +1,8 @@
import importlib
from importlib import abc
from importlib import util
+import sys
+import types
import unittest
from . import util as test_util
@@ -122,12 +124,20 @@ class LazyLoaderTests(unittest.TestCase):
self.assertFalse(hasattr(module, '__name__'))
def test_module_substitution_error(self):
- source_code = 'import sys; sys.modules[__name__] = 42'
- module = self.new_module(source_code)
with test_util.uncache(TestingImporter.module_name):
- with self.assertRaises(ValueError):
+ fresh_module = types.ModuleType(TestingImporter.module_name)
+ sys.modules[TestingImporter.module_name] = fresh_module
+ module = self.new_module()
+ with self.assertRaisesRegex(ValueError, "substituted"):
module.__name__
+ def test_module_already_in_sys(self):
+ with test_util.uncache(TestingImporter.module_name):
+ module = self.new_module()
+ sys.modules[TestingImporter.module_name] = module
+ # Force the load; just care that no exception is raised.
+ module.__name__
+
if __name__ == '__main__':
unittest.main()
diff --git a/Lib/test/test_parser.py b/Lib/test/test_parser.py
index 3d301b4..ab6577f 100644
--- a/Lib/test/test_parser.py
+++ b/Lib/test/test_parser.py
@@ -627,6 +627,22 @@ class CompileTestCase(unittest.TestCase):
code2 = parser.compilest(st)
self.assertEqual(eval(code2), -3)
+ def test_compile_filename(self):
+ st = parser.expr('a + 5')
+ code = parser.compilest(st)
+ self.assertEqual(code.co_filename, '<syntax-tree>')
+ code = st.compile()
+ self.assertEqual(code.co_filename, '<syntax-tree>')
+ for filename in ('file.py', b'file.py',
+ bytearray(b'file.py'), memoryview(b'file.py')):
+ code = parser.compilest(st, filename)
+ self.assertEqual(code.co_filename, 'file.py')
+ code = st.compile(filename)
+ self.assertEqual(code.co_filename, 'file.py')
+ self.assertRaises(TypeError, parser.compilest, st, list(b'file.py'))
+ self.assertRaises(TypeError, st.compile, list(b'file.py'))
+
+
class ParserStackLimitTestCase(unittest.TestCase):
"""try to push the parser to/over its limits.
see http://bugs.python.org/issue1881 for a discussion
diff --git a/Lib/test/test_pydoc.py b/Lib/test/test_pydoc.py
index 59aa715..aee979b 100644
--- a/Lib/test/test_pydoc.py
+++ b/Lib/test/test_pydoc.py
@@ -356,7 +356,7 @@ def get_pydoc_html(module):
def get_pydoc_link(module):
"Returns a documentation web link of a module"
dirname = os.path.dirname
- basedir = os.path.join(dirname(dirname(__file__)))
+ basedir = dirname(dirname(__file__))
doc = pydoc.TextDoc()
loc = doc.getdocloc(module, basedir=basedir)
return loc
diff --git a/Lib/test/test_readline.py b/Lib/test/test_readline.py
index 35330ab..8c2ad85 100644
--- a/Lib/test/test_readline.py
+++ b/Lib/test/test_readline.py
@@ -1,15 +1,25 @@
"""
Very minimal unittests for parts of the readline module.
"""
+from contextlib import ExitStack
+from errno import EIO
import os
+import selectors
+import subprocess
+import sys
import tempfile
import unittest
-from test.support import import_module, unlink
+from test.support import import_module, unlink, TESTFN
from test.support.script_helper import assert_python_ok
# Skip tests if there is no readline module
readline = import_module('readline')
+is_editline = readline.__doc__ and "libedit" in readline.__doc__
+
+@unittest.skipUnless(hasattr(readline, "clear_history"),
+ "The history update test cannot be run because the "
+ "clear_history method is not available.")
class TestHistoryManipulation (unittest.TestCase):
"""
These tests were added to check that the libedit emulation on OSX and the
@@ -17,9 +27,6 @@ class TestHistoryManipulation (unittest.TestCase):
why the tests cover only a small subset of the interface.
"""
- @unittest.skipUnless(hasattr(readline, "clear_history"),
- "The history update test cannot be run because the "
- "clear_history method is not available.")
def testHistoryUpdates(self):
readline.clear_history()
@@ -82,11 +89,29 @@ class TestHistoryManipulation (unittest.TestCase):
# write_history_file can create the target
readline.write_history_file(hfilename)
+ def test_nonascii_history(self):
+ readline.clear_history()
+ try:
+ readline.add_history("entrée 1")
+ except UnicodeEncodeError as err:
+ self.skipTest("Locale cannot encode test data: " + format(err))
+ readline.add_history("entrée 2")
+ readline.replace_history_item(1, "entrée 22")
+ readline.write_history_file(TESTFN)
+ self.addCleanup(os.remove, TESTFN)
+ readline.clear_history()
+ readline.read_history_file(TESTFN)
+ if is_editline:
+ # An add_history() call seems to be required for get_history_
+ # item() to register items from the file
+ readline.add_history("dummy")
+ self.assertEqual(readline.get_history_item(1), "entrée 1")
+ self.assertEqual(readline.get_history_item(2), "entrée 22")
+
class TestReadline(unittest.TestCase):
- @unittest.skipIf(readline._READLINE_VERSION < 0x0600
- and "libedit" not in readline.__doc__,
+ @unittest.skipIf(readline._READLINE_VERSION < 0x0600 and not is_editline,
"not supported in this library version")
def test_init(self):
# Issue #19884: Ensure that the ANSI sequence "\033[1034h" is not
@@ -96,6 +121,130 @@ class TestReadline(unittest.TestCase):
TERM='xterm-256color')
self.assertEqual(stdout, b'')
+ def test_nonascii(self):
+ try:
+ readline.add_history("\xEB\xEF")
+ except UnicodeEncodeError as err:
+ self.skipTest("Locale cannot encode test data: " + format(err))
+
+ script = r"""import readline
+
+is_editline = readline.__doc__ and "libedit" in readline.__doc__
+inserted = "[\xEFnserted]"
+macro = "|t\xEB[after]"
+set_pre_input_hook = getattr(readline, "set_pre_input_hook", None)
+if is_editline or not set_pre_input_hook:
+ # The insert_line() call via pre_input_hook() does nothing with Editline,
+ # so include the extra text that would have been inserted here
+ macro = inserted + macro
+
+if is_editline:
+ readline.parse_and_bind(r'bind ^B ed-prev-char')
+ readline.parse_and_bind(r'bind "\t" rl_complete')
+ readline.parse_and_bind(r'bind -s ^A "{}"'.format(macro))
+else:
+ readline.parse_and_bind(r'Control-b: backward-char')
+ readline.parse_and_bind(r'"\t": complete')
+ readline.parse_and_bind(r'set disable-completion off')
+ readline.parse_and_bind(r'set show-all-if-ambiguous off')
+ readline.parse_and_bind(r'set show-all-if-unmodified off')
+ readline.parse_and_bind(r'Control-a: "{}"'.format(macro))
+
+def pre_input_hook():
+ readline.insert_text(inserted)
+ readline.redisplay()
+if set_pre_input_hook:
+ set_pre_input_hook(pre_input_hook)
+
+def completer(text, state):
+ if text == "t\xEB":
+ if state == 0:
+ print("text", ascii(text))
+ print("line", ascii(readline.get_line_buffer()))
+ print("indexes", readline.get_begidx(), readline.get_endidx())
+ return "t\xEBnt"
+ if state == 1:
+ return "t\xEBxt"
+ if text == "t\xEBx" and state == 0:
+ return "t\xEBxt"
+ return None
+readline.set_completer(completer)
+
+def display(substitution, matches, longest_match_length):
+ print("substitution", ascii(substitution))
+ print("matches", ascii(matches))
+readline.set_completion_display_matches_hook(display)
+
+print("result", ascii(input()))
+print("history", ascii(readline.get_history_item(1)))
+"""
+
+ input = b"\x01" # Ctrl-A, expands to "|t\xEB[after]"
+ input += b"\x02" * len("[after]") # Move cursor back
+ input += b"\t\t" # Display possible completions
+ input += b"x\t" # Complete "t\xEBx" -> "t\xEBxt"
+ input += b"\r"
+ output = run_pty(script, input)
+ self.assertIn(b"text 't\\xeb'\r\n", output)
+ self.assertIn(b"line '[\\xefnserted]|t\\xeb[after]'\r\n", output)
+ self.assertIn(b"indexes 11 13\r\n", output)
+ if not is_editline and hasattr(readline, "set_pre_input_hook"):
+ self.assertIn(b"substitution 't\\xeb'\r\n", output)
+ self.assertIn(b"matches ['t\\xebnt', 't\\xebxt']\r\n", output)
+ expected = br"'[\xefnserted]|t\xebxt[after]'"
+ self.assertIn(b"result " + expected + b"\r\n", output)
+ self.assertIn(b"history " + expected + b"\r\n", output)
+
+
+def run_pty(script, input=b"dummy input\r"):
+ pty = import_module('pty')
+ output = bytearray()
+ [master, slave] = pty.openpty()
+ args = (sys.executable, '-c', script)
+ proc = subprocess.Popen(args, stdin=slave, stdout=slave, stderr=slave)
+ os.close(slave)
+ with ExitStack() as cleanup:
+ cleanup.enter_context(proc)
+ def terminate(proc):
+ try:
+ proc.terminate()
+ except ProcessLookupError:
+ # Workaround for Open/Net BSD bug (Issue 16762)
+ pass
+ cleanup.callback(terminate, proc)
+ cleanup.callback(os.close, master)
+ # Avoid using DefaultSelector and PollSelector. Kqueue() does not
+ # work with pseudo-terminals on OS X < 10.9 (Issue 20365) and Open
+ # BSD (Issue 20667). Poll() does not work with OS X 10.6 or 10.4
+ # either (Issue 20472). Hopefully the file descriptor is low enough
+ # to use with select().
+ sel = cleanup.enter_context(selectors.SelectSelector())
+ sel.register(master, selectors.EVENT_READ | selectors.EVENT_WRITE)
+ os.set_blocking(master, False)
+ while True:
+ for [_, events] in sel.select():
+ if events & selectors.EVENT_READ:
+ try:
+ chunk = os.read(master, 0x10000)
+ except OSError as err:
+ # Linux raises EIO when slave is closed (Issue 5380)
+ if err.errno != EIO:
+ raise
+ chunk = b""
+ if not chunk:
+ return output
+ output.extend(chunk)
+ if events & selectors.EVENT_WRITE:
+ try:
+ input = input[os.write(master, input):]
+ except OSError as err:
+ # Apparently EIO means the slave was closed
+ if err.errno != EIO:
+ raise
+ input = b"" # Stop writing
+ if not input:
+ sel.modify(master, selectors.EVENT_READ)
+
if __name__ == "__main__":
unittest.main()
diff --git a/Lib/test/test_symtable.py b/Lib/test/test_symtable.py
index e5e7b83..c5d7fac 100644
--- a/Lib/test/test_symtable.py
+++ b/Lib/test/test_symtable.py
@@ -157,6 +157,12 @@ class SymtableTest(unittest.TestCase):
self.fail("no SyntaxError for %r" % (brokencode,))
checkfilename("def f(x): foo)(") # parse-time
checkfilename("def f(x): global x") # symtable-build-time
+ symtable.symtable("pass", b"spam", "exec")
+ with self.assertRaises(TypeError):
+ symtable.symtable("pass", bytearray(b"spam"), "exec")
+ symtable.symtable("pass", memoryview(b"spam"), "exec")
+ with self.assertRaises(TypeError):
+ symtable.symtable("pass", list(b"spam"), "exec")
def test_eval(self):
symbols = symtable.symtable("42", "?", "eval")
diff --git a/Lib/test/test_unpack_ex.py b/Lib/test/test_unpack_ex.py
index d27eef0..74346b4 100644
--- a/Lib/test/test_unpack_ex.py
+++ b/Lib/test/test_unpack_ex.py
@@ -248,6 +248,11 @@ Overridden parameters
...
TypeError: f() got multiple values for keyword argument 'x'
+ >>> f(x=5, **{'x': 3}, **{'x': 2})
+ Traceback (most recent call last):
+ ...
+ TypeError: f() got multiple values for keyword argument 'x'
+
>>> f(**{1: 3}, **{1: 5})
Traceback (most recent call last):
...
diff --git a/Lib/test/test_xml_etree.py b/Lib/test/test_xml_etree.py
index 44e3142..bc1dd14 100644
--- a/Lib/test/test_xml_etree.py
+++ b/Lib/test/test_xml_etree.py
@@ -18,7 +18,7 @@ import weakref
from itertools import product
from test import support
-from test.support import TESTFN, findfile, import_fresh_module, gc_collect
+from test.support import TESTFN, findfile, import_fresh_module, gc_collect, swap_attr
# pyET is the pure-Python implementation.
#
@@ -1860,6 +1860,12 @@ class BadElementTest(ElementTestCase, unittest.TestCase):
e.extend([ET.Element('bar')])
self.assertRaises(ValueError, e.remove, X('baz'))
+ def test_recursive_repr(self):
+ # Issue #25455
+ e = ET.Element('foo')
+ with swap_attr(e, 'tag', e):
+ with self.assertRaises(RuntimeError):
+ repr(e) # Should not crash
class MutatingElementPath(str):
def __new__(cls, elem, *args):
diff --git a/Lib/test/test_zipimport.py b/Lib/test/test_zipimport.py
index 0da5906..8e5e12d 100644
--- a/Lib/test/test_zipimport.py
+++ b/Lib/test/test_zipimport.py
@@ -600,6 +600,19 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
finally:
os.remove(filename)
+ def testBytesPath(self):
+ filename = support.TESTFN + ".zip"
+ self.addCleanup(support.unlink, filename)
+ with ZipFile(filename, "w") as z:
+ zinfo = ZipInfo(TESTMOD + ".py", time.localtime(NOW))
+ zinfo.compress_type = self.compression
+ z.writestr(zinfo, test_src)
+
+ zipimport.zipimporter(filename)
+ zipimport.zipimporter(os.fsencode(filename))
+ zipimport.zipimporter(bytearray(os.fsencode(filename)))
+ zipimport.zipimporter(memoryview(os.fsencode(filename)))
+
@support.requires_zlib
class CompressedZipImportTestCase(UncompressedZipImportTestCase):
@@ -620,6 +633,8 @@ class BadFileZipImportTestCase(unittest.TestCase):
def testBadArgs(self):
self.assertRaises(TypeError, zipimport.zipimporter, None)
self.assertRaises(TypeError, zipimport.zipimporter, TESTMOD, kwd=None)
+ self.assertRaises(TypeError, zipimport.zipimporter,
+ list(os.fsencode(TESTMOD)))
def testFilenameTooLong(self):
self.assertZipFailure('A' * 33000)