path
stringlengths 14
112
| content
stringlengths 0
6.32M
| size
int64 0
6.32M
| max_lines
int64 1
100k
| repo_name
stringclasses 2
values | autogenerated
bool 1
class |
---|---|---|---|---|---|
cosmopolitan/third_party/python/Lib/test/test_module.py | # Test the module type
import cosmo
import unittest
import weakref
from test.support import gc_collect, requires_type_collecting
from test.support.script_helper import assert_python_ok
import sys
ModuleType = type(sys)
class FullLoader:
@classmethod
def module_repr(cls, m):
return "<module '{}' (crafted)>".format(m.__name__)
class BareLoader:
pass
class ModuleTests(unittest.TestCase):
def test_uninitialized(self):
# An uninitialized module has no __dict__ or __name__,
# and __doc__ is None
foo = ModuleType.__new__(ModuleType)
self.assertTrue(foo.__dict__ is None)
self.assertRaises(SystemError, dir, foo)
try:
s = foo.__name__
self.fail("__name__ = %s" % repr(s))
except AttributeError:
pass
if 'tiny' not in cosmo.MODE:
self.assertEqual(foo.__doc__, ModuleType.__doc__)
def test_uninitialized_missing_getattr(self):
# Issue 8297
# test the text in the AttributeError of an uninitialized module
foo = ModuleType.__new__(ModuleType)
self.assertRaisesRegex(
AttributeError, "module has no attribute 'not_here'",
getattr, foo, "not_here")
def test_missing_getattr(self):
# Issue 8297
# test the text in the AttributeError
foo = ModuleType("foo")
self.assertRaisesRegex(
AttributeError, "module 'foo' has no attribute 'not_here'",
getattr, foo, "not_here")
def test_no_docstring(self):
# Regularly initialized module, no docstring
foo = ModuleType("foo")
self.assertEqual(foo.__name__, "foo")
self.assertEqual(foo.__doc__, None)
self.assertIs(foo.__loader__, None)
self.assertIs(foo.__package__, None)
self.assertIs(foo.__spec__, None)
self.assertEqual(foo.__dict__, {"__name__": "foo", "__doc__": None,
"__loader__": None, "__package__": None,
"__spec__": None})
def test_ascii_docstring(self):
# ASCII docstring
foo = ModuleType("foo", "foodoc")
self.assertEqual(foo.__name__, "foo")
self.assertEqual(foo.__doc__, "foodoc")
self.assertEqual(foo.__dict__,
{"__name__": "foo", "__doc__": "foodoc",
"__loader__": None, "__package__": None,
"__spec__": None})
def test_unicode_docstring(self):
# Unicode docstring
foo = ModuleType("foo", "foodoc\u1234")
self.assertEqual(foo.__name__, "foo")
self.assertEqual(foo.__doc__, "foodoc\u1234")
self.assertEqual(foo.__dict__,
{"__name__": "foo", "__doc__": "foodoc\u1234",
"__loader__": None, "__package__": None,
"__spec__": None})
def test_reinit(self):
# Reinitialization should not replace the __dict__
foo = ModuleType("foo", "foodoc\u1234")
foo.bar = 42
d = foo.__dict__
foo.__init__("foo", "foodoc")
self.assertEqual(foo.__name__, "foo")
self.assertEqual(foo.__doc__, "foodoc")
self.assertEqual(foo.bar, 42)
self.assertEqual(foo.__dict__,
{"__name__": "foo", "__doc__": "foodoc", "bar": 42,
"__loader__": None, "__package__": None, "__spec__": None})
self.assertTrue(foo.__dict__ is d)
def test_dont_clear_dict(self):
# See issue 7140.
def f():
foo = ModuleType("foo")
foo.bar = 4
return foo
gc_collect()
self.assertEqual(f().__dict__["bar"], 4)
@requires_type_collecting
def test_clear_dict_in_ref_cycle(self):
destroyed = []
m = ModuleType("foo")
m.destroyed = destroyed
s = """class A:
def __init__(self, l):
self.l = l
def __del__(self):
self.l.append(1)
a = A(destroyed)"""
exec(s, m.__dict__)
del m
gc_collect()
self.assertEqual(destroyed, [1])
def test_weakref(self):
m = ModuleType("foo")
wr = weakref.ref(m)
self.assertIs(wr(), m)
del m
gc_collect()
self.assertIs(wr(), None)
def test_module_repr_minimal(self):
# reprs when modules have no __file__, __name__, or __loader__
m = ModuleType('foo')
del m.__name__
self.assertEqual(repr(m), "<module '?'>")
def test_module_repr_with_name(self):
m = ModuleType('foo')
self.assertEqual(repr(m), "<module 'foo'>")
def test_module_repr_with_name_and_filename(self):
m = ModuleType('foo')
m.__file__ = '/tmp/foo.py'
self.assertEqual(repr(m), "<module 'foo' from '/tmp/foo.py'>")
def test_module_repr_with_filename_only(self):
m = ModuleType('foo')
del m.__name__
m.__file__ = '/tmp/foo.py'
self.assertEqual(repr(m), "<module '?' from '/tmp/foo.py'>")
def test_module_repr_with_loader_as_None(self):
m = ModuleType('foo')
assert m.__loader__ is None
self.assertEqual(repr(m), "<module 'foo'>")
def test_module_repr_with_bare_loader_but_no_name(self):
m = ModuleType('foo')
del m.__name__
# Yes, a class not an instance.
m.__loader__ = BareLoader
loader_repr = repr(BareLoader)
self.assertEqual(
repr(m), "<module '?' ({})>".format(loader_repr))
def test_module_repr_with_full_loader_but_no_name(self):
# m.__loader__.module_repr() will fail because the module has no
# m.__name__. This exception will get suppressed and instead the
# loader's repr will be used.
m = ModuleType('foo')
del m.__name__
# Yes, a class not an instance.
m.__loader__ = FullLoader
loader_repr = repr(FullLoader)
self.assertEqual(
repr(m), "<module '?' ({})>".format(loader_repr))
def test_module_repr_with_bare_loader(self):
m = ModuleType('foo')
# Yes, a class not an instance.
m.__loader__ = BareLoader
module_repr = repr(BareLoader)
self.assertEqual(
repr(m), "<module 'foo' ({})>".format(module_repr))
def test_module_repr_with_full_loader(self):
m = ModuleType('foo')
# Yes, a class not an instance.
m.__loader__ = FullLoader
self.assertEqual(
repr(m), "<module 'foo' (crafted)>")
def test_module_repr_with_bare_loader_and_filename(self):
# Because the loader has no module_repr(), use the file name.
m = ModuleType('foo')
# Yes, a class not an instance.
m.__loader__ = BareLoader
m.__file__ = '/tmp/foo.py'
self.assertEqual(repr(m), "<module 'foo' from '/tmp/foo.py'>")
def test_module_repr_with_full_loader_and_filename(self):
# Even though the module has an __file__, use __loader__.module_repr()
m = ModuleType('foo')
# Yes, a class not an instance.
m.__loader__ = FullLoader
m.__file__ = '/tmp/foo.py'
self.assertEqual(repr(m), "<module 'foo' (crafted)>")
def test_module_repr_builtin(self):
self.assertEqual(repr(sys), "<module 'sys' (built-in)>")
def test_module_repr_source(self):
r = repr(unittest)
starts_with = "<module 'unittest' from '"
ends_with = "__init__.pyc'>"
self.assertEqual(r[:len(starts_with)], starts_with,
'{!r} does not start with {!r}'.format(r, starts_with))
self.assertEqual(r[-len(ends_with):], ends_with,
'{!r} does not end with {!r}'.format(r, ends_with))
@unittest.skipIf(True, "TODO: find out why final_a import fails")
@requires_type_collecting
def test_module_finalization_at_shutdown(self):
# Module globals and builtins should still be available during shutdown
rc, out, err = assert_python_ok("-c", "from test import final_a")
self.assertFalse(err)
lines = out.splitlines()
self.assertEqual(set(lines), {
b"x = a",
b"x = b",
b"final_a.x = a",
b"final_b.x = b",
b"len = len",
b"shutil.rmtree = rmtree"})
def test_descriptor_errors_propagate(self):
class Descr:
def __get__(self, o, t):
raise RuntimeError
class M(ModuleType):
melon = Descr()
self.assertRaises(RuntimeError, getattr, M("mymod"), "melon")
# frozen and namespace module reprs are tested in importlib.
if __name__ == '__main__':
unittest.main()
| 8,769 | 248 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/ssl_key.passwd.pem | -----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,8064BE1494B24B13
KJrffOMbo8M0I3PzcYxRZGMpKD1yB3Ii4+bT5XoanxjIJ+4fdx6LfZ0Rsx+riyzs
tymsQu/iYY9j+4rCvN9+eetsL1X6iZpiimKsLexcid9M3fb0vxED5Sgw0dvunCUA
xhqjLIKR92MKbODHf6KrDKCpsiPbjq4gZ7P+uCGXAMHL3MXIJSC0hW9rK7Ce6oyO
CjpIcgB8x+GUWZZZhAFdlzIHMZrteNP2P5HK6QcaT71P034Dz1hhqoj4Q0t+Fta2
4tfsM/bnTR/l6hwlhPa1e3Uj322tDTDWBScgWANn5+sEWldLmozMaWhZsn22pfk2
KjRMGXG024JVheV882nbdOBvG7oq+lxkZ/ZP+vvqJqnvYtf7WtM8UivzYpe5Hz5b
kVvWzPjBLUSZ9whM9rDLqSSqMPyPvDTuEmLkuq+xm7pYJmsLqIMP2klZLqRxLX6K
uqwplb8UG440qauxgnQ905PId1l2fJEnRtV+7vXprA0L0QotgXLVHBhLmTFM+3PH
9H3onf31dionUAPrn3nfVE36HhvVgRyvDBnBzJSIMighgq21Qx/d1dk0DRYi1hUI
nCHl0YJPXheVcXR7JiSF2XQCAaFuS1Mr7NCXfWZOZQC/0dkvmHnl9DUAhuqq9BNZ
1cKhZXcKHadg2/r0Zup/oDzmHPUEfTAXT0xbqoWlhkdwbF2veWQ96A/ncx3ISTb4
PkXBlX9rdia8nmtyQDQRn4NuvchbaGkj4WKFC8pF8Hn7naHqwjpHaDUimBc0CoQW
edNJqruKWwtSVLuwKHCC2gZFX9AXSKJXJz/QRSUlhFGOhuF/J6yKaXj6n5lxWNiQ
54J+OP/hz2aS95CD2+Zf1SKpxdWiLZSIQqESpmmUrXROixNJZ/Z7gI74Dd9dSJOH
W+3AU03vrrFZVrJVZhjcINHoH1Skh6JKscH18L6x4U868nSr4SrRLX8BhHllOQyD
bmU+PZAjF8ZBIaCtTGulDXD29F73MeAZeTSsgQjFu0iKLj1wPiphbx8i/SUtR4YP
X6PVA04g66r1NBw+3RQASVorZ3g1MSFvITHXcbKkBDeJH2z1+c6t/VVyTONnQhM5
lLgRSk6HCbetvT9PKxWrWutA12pdBYEHdZhMHVf2+xclky7l09w8hg2/qqcdGRGe
oAOZ72t0l5ObNyaruDKUS6f4AjOyWq/Xj5xuFtf1n3tQHyslSyCTPcAbQhDfTHUx
vixb/V9qvYPt7OCn8py7v1M69NH42QVFAvwveDIFjZdqfIKBoJK2V4qPoevJI6uj
Q5ByMt8OXOjSXNpHXpYQWUiWeCwOEBXJX8rzCHdMtg37jJ0zCmeErR1NTdg+EujM
TWYgd06jlT67tURST0aB2kg4ijKgUJefD313LW1zC6gVsTbjSZxYyRbPfSP6flQB
yCi1C19E2OsgleqbkBVC5GlYUzaJT7SGjCRmGx1eqtbrALu+LVH24Wceexlpjydl
+s2nf/DZlKun/tlPh6YioifPCJjByZMQOCEfIox6BkemZETz8uYA4TTWimG13Z03
gyDGC2jdpEW414J2qcQDvrdUgJ+HlhrAAHaWpMQDbXYxBGoZ+3+ORvQV4kAsCwL8
k3EIrVpePdik+1xgOWsyLj6QxFXlTMvL6Wc5pnArFPORsgHEolJvxSPTf9aAHNPn
V2WBvxiLBtYpGrujAUM40Syx/aN2RPtcXYPAusHUBw+S8/p+/8Kg8GZmnIXG3F89
45Eepl2quZYIrou7a1fwIpIIZ0hFiBQ1mlHVMFtxwVHS1bQb3SU2GeO+JcGjdVXc
04qeGuQ5M164eQ5C0T7ZQ1ULiUlFWKD30m+cjqmZzt3d7Q0mKpMKuESIuZJo/wpD
Nas432aLKUhcNx/pOYLkKJRpGZKOupQoD5iUj/j44o8JoFkDK33v2S57XB5QGz28
9Zuhx49b3W8mbM6EBanlQKLWJGCxXqc/jhYhFWn+b0MhidynFgA0oeWvf6ZDyt6H
Yi5Etxsar09xp0Do3NxtQXLuSUu0ji2pQzSIKuoqQWKqldm6VrpwojiqJhy4WQBQ
aVVyFeWBC7G3Zj76dO+yp2sfJ0itJUQ8AIB9Cg0f34rEZu+r9luPmqBoUeL95Tk7
YvCOU3Jl8Iqysv8aNpVXT8sa8rrSbruWCByEePZ37RIdHLMVBwVY0eVaFQjrjU7E
mXmM9eaoYLfXOllsQ+M2+qPFUITr/GU3Qig13DhK/+yC1R6V2a0l0WRhMltIPYKW
Ztvvr4hK5LcYCeS113BLiMbDIMMZZYGDZGMdC8DnnVbT2loF0Rfmp80Af31KmMQ4
6XvMatW9UDjBoY5a/YMpdm7SRwm+MgV2KNPpc2kST87/yi9oprGAb8qiarHiHTM0
-----END RSA PRIVATE KEY-----
| 2,531 | 43 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_sysconfig.py | import unittest
import sys
import os
import subprocess
import shutil
from copy import copy
from test.support import (run_unittest,
import_module, TESTFN, unlink, check_warnings,
captured_stdout, skip_unless_symlink, change_cwd)
import sysconfig
from sysconfig import (get_paths, get_platform, get_config_vars,
get_path, get_path_names, _INSTALL_SCHEMES,
_get_default_scheme, _expand_vars,
get_scheme_names, get_config_var, _main)
import _osx_support
class TestSysConfig(unittest.TestCase):
def setUp(self):
super(TestSysConfig, self).setUp()
self.sys_path = sys.path[:]
# patching os.uname
if hasattr(os, 'uname'):
self.uname = os.uname
self._uname = os.uname()
else:
self.uname = None
self._set_uname(('',)*5)
os.uname = self._get_uname
# saving the environment
self.name = os.name
self.platform = sys.platform
self.version = sys.version
self.sep = os.sep
self.join = os.path.join
self.isabs = os.path.isabs
self.splitdrive = os.path.splitdrive
self._config_vars = sysconfig._CONFIG_VARS, copy(sysconfig._CONFIG_VARS)
self._added_envvars = []
self._changed_envvars = []
for var in ('MACOSX_DEPLOYMENT_TARGET', 'PATH'):
if var in os.environ:
self._changed_envvars.append((var, os.environ[var]))
else:
self._added_envvars.append(var)
def tearDown(self):
sys.path[:] = self.sys_path
self._cleanup_testfn()
if self.uname is not None:
os.uname = self.uname
else:
del os.uname
os.name = self.name
sys.platform = self.platform
sys.version = self.version
os.sep = self.sep
os.path.join = self.join
os.path.isabs = self.isabs
os.path.splitdrive = self.splitdrive
sysconfig._CONFIG_VARS = self._config_vars[0]
sysconfig._CONFIG_VARS.clear()
sysconfig._CONFIG_VARS.update(self._config_vars[1])
for var, value in self._changed_envvars:
os.environ[var] = value
for var in self._added_envvars:
os.environ.pop(var, None)
super(TestSysConfig, self).tearDown()
def _set_uname(self, uname):
self._uname = os.uname_result(uname)
def _get_uname(self):
return self._uname
def _cleanup_testfn(self):
path = TESTFN
if os.path.isfile(path):
os.remove(path)
elif os.path.isdir(path):
shutil.rmtree(path)
def test_get_path_names(self):
self.assertEqual(get_path_names(), sysconfig._SCHEME_KEYS)
def test_get_paths(self):
scheme = get_paths()
default_scheme = _get_default_scheme()
wanted = _expand_vars(default_scheme, None)
wanted = sorted(wanted.items())
scheme = sorted(scheme.items())
self.assertEqual(scheme, wanted)
def test_get_path(self):
# XXX make real tests here
for scheme in _INSTALL_SCHEMES:
for name in _INSTALL_SCHEMES[scheme]:
res = get_path(name, scheme)
def test_get_config_vars(self):
cvars = get_config_vars()
self.assertIsInstance(cvars, dict)
self.assertTrue(cvars)
def test_get_platform(self):
# windows XP, 32bits
os.name = 'nt'
sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
'[MSC v.1310 32 bit (Intel)]')
sys.platform = 'win32'
self.assertEqual(get_platform(), 'win32')
# windows XP, amd64
os.name = 'nt'
sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
'[MSC v.1310 32 bit (Amd64)]')
sys.platform = 'win32'
self.assertEqual(get_platform(), 'win-amd64')
# windows XP, itanium
os.name = 'nt'
sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
'[MSC v.1310 32 bit (Itanium)]')
sys.platform = 'win32'
self.assertEqual(get_platform(), 'win-ia64')
# macbook
os.name = 'posix'
sys.version = ('2.5 (r25:51918, Sep 19 2006, 08:49:13) '
'\n[GCC 4.0.1 (Apple Computer, Inc. build 5341)]')
sys.platform = 'darwin'
self._set_uname(('Darwin', 'macziade', '8.11.1',
('Darwin Kernel Version 8.11.1: '
'Wed Oct 10 18:23:28 PDT 2007; '
'root:xnu-792.25.20~1/RELEASE_I386'), 'PowerPC'))
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3'
get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g '
'-fwrapv -O3 -Wall -Wstrict-prototypes')
maxint = sys.maxsize
try:
sys.maxsize = 2147483647
self.assertEqual(get_platform(), 'macosx-10.3-ppc')
sys.maxsize = 9223372036854775807
self.assertEqual(get_platform(), 'macosx-10.3-ppc64')
finally:
sys.maxsize = maxint
self._set_uname(('Darwin', 'macziade', '8.11.1',
('Darwin Kernel Version 8.11.1: '
'Wed Oct 10 18:23:28 PDT 2007; '
'root:xnu-792.25.20~1/RELEASE_I386'), 'i386'))
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3'
get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g '
'-fwrapv -O3 -Wall -Wstrict-prototypes')
maxint = sys.maxsize
try:
sys.maxsize = 2147483647
self.assertEqual(get_platform(), 'macosx-10.3-i386')
sys.maxsize = 9223372036854775807
self.assertEqual(get_platform(), 'macosx-10.3-x86_64')
finally:
sys.maxsize = maxint
# macbook with fat binaries (fat, universal or fat64)
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.4'
get_config_vars()['CFLAGS'] = ('-arch ppc -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
self.assertEqual(get_platform(), 'macosx-10.4-fat')
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
self.assertEqual(get_platform(), 'macosx-10.4-intel')
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
self.assertEqual(get_platform(), 'macosx-10.4-fat3')
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['CFLAGS'] = ('-arch ppc64 -arch x86_64 -arch ppc -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
self.assertEqual(get_platform(), 'macosx-10.4-universal')
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc64 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
self.assertEqual(get_platform(), 'macosx-10.4-fat64')
for arch in ('ppc', 'i386', 'x86_64', 'ppc64'):
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['CFLAGS'] = ('-arch %s -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3' % arch)
self.assertEqual(get_platform(), 'macosx-10.4-%s' % arch)
# linux debian sarge
os.name = 'posix'
sys.version = ('2.3.5 (#1, Jul 4 2007, 17:28:59) '
'\n[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)]')
sys.platform = 'linux2'
self._set_uname(('Linux', 'aglae', '2.6.21.1dedibox-r7',
'#1 Mon Apr 30 17:25:38 CEST 2007', 'i686'))
self.assertEqual(get_platform(), 'linux-i686')
# XXX more platforms to tests here
def test_get_config_h_filename(self):
config_h = sysconfig.get_config_h_filename()
self.assertTrue(os.path.isfile(config_h), config_h)
def test_get_scheme_names(self):
wanted = ('nt', 'nt_user', 'osx_framework_user',
'posix_home', 'posix_prefix', 'posix_user')
self.assertEqual(get_scheme_names(), wanted)
@skip_unless_symlink
def test_symlink(self):
# On Windows, the EXE needs to know where pythonXY.dll is at so we have
# to add the directory to the path.
env = None
if sys.platform == "win32":
env = {k.upper(): os.environ[k] for k in os.environ}
env["PATH"] = "{};{}".format(
os.path.dirname(sys.executable), env.get("PATH", ""))
# Requires PYTHONHOME as well since we locate stdlib from the
# EXE path and not the DLL path (which should be fixed)
env["PYTHONHOME"] = os.path.dirname(sys.executable)
if sysconfig.is_python_build(True):
env["PYTHONPATH"] = os.path.dirname(os.__file__)
# Issue 7880
def get(python, env=None):
cmd = [python, '-c',
'import sysconfig; print(sysconfig.get_platform())']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, env=env)
out, err = p.communicate()
if p.returncode:
print((out, err))
self.fail('Non-zero return code {0} (0x{0:08X})'
.format(p.returncode))
return out, err
real = os.path.realpath(sys.executable)
link = os.path.abspath(TESTFN)
os.symlink(real, link)
try:
self.assertEqual(get(real), get(link, env))
finally:
unlink(link)
def test_user_similar(self):
# Issue #8759: make sure the posix scheme for the users
# is similar to the global posix_prefix one
base = get_config_var('base')
user = get_config_var('userbase')
# the global scheme mirrors the distinction between prefix and
# exec-prefix but not the user scheme, so we have to adapt the paths
# before comparing (issue #9100)
adapt = sys.base_prefix != sys.base_exec_prefix
for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'):
global_path = get_path(name, 'posix_prefix')
if adapt:
global_path = global_path.replace(sys.exec_prefix, sys.base_prefix)
base = base.replace(sys.exec_prefix, sys.base_prefix)
elif sys.base_prefix != sys.prefix:
# virtual environment? Likewise, we have to adapt the paths
# before comparing
global_path = global_path.replace(sys.base_prefix, sys.prefix)
base = base.replace(sys.base_prefix, sys.prefix)
user_path = get_path(name, 'posix_user')
self.assertEqual(user_path, global_path.replace(base, user, 1))
def test_main(self):
# just making sure _main() runs and returns things in the stdout
with captured_stdout() as output:
_main()
self.assertTrue(len(output.getvalue().split('\n')) > 0)
@unittest.skipIf(sys.platform == "win32", "Does not apply to Windows")
def test_ldshared_value(self):
ldflags = sysconfig.get_config_var('LDFLAGS')
ldshared = sysconfig.get_config_var('LDSHARED')
self.assertIn(ldflags, ldshared)
@unittest.skipUnless(sys.platform == "darwin", "test only relevant on MacOSX")
def test_platform_in_subprocess(self):
my_platform = sysconfig.get_platform()
# Test without MACOSX_DEPLOYMENT_TARGET in the environment
env = os.environ.copy()
if 'MACOSX_DEPLOYMENT_TARGET' in env:
del env['MACOSX_DEPLOYMENT_TARGET']
p = subprocess.Popen([
sys.executable, '-c',
'import sysconfig; print(sysconfig.get_platform())',
],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
env=env)
test_platform = p.communicate()[0].strip()
test_platform = test_platform.decode('utf-8')
status = p.wait()
self.assertEqual(status, 0)
self.assertEqual(my_platform, test_platform)
# Test with MACOSX_DEPLOYMENT_TARGET in the environment, and
# using a value that is unlikely to be the default one.
env = os.environ.copy()
env['MACOSX_DEPLOYMENT_TARGET'] = '10.1'
p = subprocess.Popen([
sys.executable, '-c',
'import sysconfig; print(sysconfig.get_platform())',
],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
env=env)
test_platform = p.communicate()[0].strip()
test_platform = test_platform.decode('utf-8')
status = p.wait()
self.assertEqual(status, 0)
self.assertEqual(my_platform, test_platform)
def test_srcdir(self):
# See Issues #15322, #15364.
srcdir = sysconfig.get_config_var('srcdir')
self.assertTrue(os.path.isabs(srcdir), srcdir)
self.assertTrue(os.path.isdir(srcdir), srcdir)
if sysconfig._PYTHON_BUILD:
# The python executable has not been installed so srcdir
# should be a full source checkout.
Python_h = os.path.join(srcdir, 'Include', 'Python.h')
self.assertTrue(os.path.exists(Python_h), Python_h)
self.assertTrue(sysconfig._is_python_source_dir(srcdir))
elif os.name == 'posix':
makefile_dir = os.path.dirname(sysconfig.get_makefile_filename())
# Issue #19340: srcdir has been realpath'ed already
makefile_dir = os.path.realpath(makefile_dir)
self.assertEqual(makefile_dir, srcdir)
def test_srcdir_independent_of_cwd(self):
# srcdir should be independent of the current working directory
# See Issues #15322, #15364.
srcdir = sysconfig.get_config_var('srcdir')
with change_cwd(os.pardir):
srcdir2 = sysconfig.get_config_var('srcdir')
self.assertEqual(srcdir, srcdir2)
@unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None,
'EXT_SUFFIX required for this test')
def test_SO_deprecation(self):
self.assertWarns(DeprecationWarning,
sysconfig.get_config_var, 'SO')
@unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None,
'EXT_SUFFIX required for this test')
def test_SO_value(self):
with check_warnings(('', DeprecationWarning)):
self.assertEqual(sysconfig.get_config_var('SO'),
sysconfig.get_config_var('EXT_SUFFIX'))
@unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None,
'EXT_SUFFIX required for this test')
def test_SO_in_vars(self):
vars = sysconfig.get_config_vars()
self.assertIsNotNone(vars['SO'])
self.assertEqual(vars['SO'], vars['EXT_SUFFIX'])
@unittest.skipUnless(sys.platform == 'linux' and
hasattr(sys.implementation, '_multiarch'),
'multiarch-specific test')
def test_triplet_in_ext_suffix(self):
ctypes = import_module('ctypes')
import platform, re
machine = platform.machine()
suffix = sysconfig.get_config_var('EXT_SUFFIX')
if re.match('(aarch64|arm|mips|ppc|powerpc|s390|sparc)', machine):
self.assertTrue('linux' in suffix, suffix)
if re.match('(i[3-6]86|x86_64)$', machine):
if ctypes.sizeof(ctypes.c_char_p()) == 4:
self.assertTrue(suffix.endswith('i386-linux-gnu.so') or
suffix.endswith('x86_64-linux-gnux32.so'),
suffix)
else: # 8 byte pointer size
self.assertTrue(suffix.endswith('x86_64-linux-gnu.so'), suffix)
@unittest.skipUnless(sys.platform == 'darwin', 'OS X-specific test')
def test_osx_ext_suffix(self):
suffix = sysconfig.get_config_var('EXT_SUFFIX')
self.assertTrue(suffix.endswith('-darwin.so'), suffix)
class MakefileTests(unittest.TestCase):
@unittest.skipIf(sys.platform.startswith('win'),
'Test is not Windows compatible')
def test_get_makefile_filename(self):
makefile = sysconfig.get_makefile_filename()
self.assertTrue(os.path.isfile(makefile), makefile)
def test_parse_makefile(self):
self.addCleanup(unlink, TESTFN)
with open(TESTFN, "w") as makefile:
print("var1=a$(VAR2)", file=makefile)
print("VAR2=b$(var3)", file=makefile)
print("var3=42", file=makefile)
print("var4=$/invalid", file=makefile)
print("var5=dollar$$5", file=makefile)
print("var6=${var3}/lib/python3.5/config-$(VAR2)$(var5)"
"-x86_64-linux-gnu", file=makefile)
vars = sysconfig._parse_makefile(TESTFN)
self.assertEqual(vars, {
'var1': 'ab42',
'VAR2': 'b42',
'var3': 42,
'var4': '$/invalid',
'var5': 'dollar$5',
'var6': '42/lib/python3.5/config-b42dollar$5-x86_64-linux-gnu',
})
def test_main():
run_unittest(TestSysConfig, MakefileTests)
if __name__ == "__main__":
test_main()
| 18,880 | 459 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_tcl.py | import unittest
import re
import subprocess
import sys
import os
from test import support
# Skip this test if the _tkinter module wasn't built.
_tkinter = support.import_module('_tkinter')
import tkinter
from tkinter import Tcl
from _tkinter import TclError
try:
from _testcapi import INT_MAX, PY_SSIZE_T_MAX
except ImportError:
INT_MAX = PY_SSIZE_T_MAX = sys.maxsize
tcl_version = tuple(map(int, _tkinter.TCL_VERSION.split('.')))
_tk_patchlevel = None
def get_tk_patchlevel():
global _tk_patchlevel
if _tk_patchlevel is None:
tcl = Tcl()
patchlevel = tcl.call('info', 'patchlevel')
m = re.fullmatch(r'(\d+)\.(\d+)([ab.])(\d+)', patchlevel)
major, minor, releaselevel, serial = m.groups()
major, minor, serial = int(major), int(minor), int(serial)
releaselevel = {'a': 'alpha', 'b': 'beta', '.': 'final'}[releaselevel]
if releaselevel == 'final':
_tk_patchlevel = major, minor, serial, releaselevel, 0
else:
_tk_patchlevel = major, minor, 0, releaselevel, serial
return _tk_patchlevel
class TkinterTest(unittest.TestCase):
def testFlattenLen(self):
# flatten(<object with no length>)
self.assertRaises(TypeError, _tkinter._flatten, True)
class TclTest(unittest.TestCase):
def setUp(self):
self.interp = Tcl()
self.wantobjects = self.interp.tk.wantobjects()
def testEval(self):
tcl = self.interp
tcl.eval('set a 1')
self.assertEqual(tcl.eval('set a'),'1')
def test_eval_null_in_result(self):
tcl = self.interp
self.assertEqual(tcl.eval('set a "a\\0b"'), 'a\x00b')
def testEvalException(self):
tcl = self.interp
self.assertRaises(TclError,tcl.eval,'set a')
def testEvalException2(self):
tcl = self.interp
self.assertRaises(TclError,tcl.eval,'this is wrong')
def testCall(self):
tcl = self.interp
tcl.call('set','a','1')
self.assertEqual(tcl.call('set','a'),'1')
def testCallException(self):
tcl = self.interp
self.assertRaises(TclError,tcl.call,'set','a')
def testCallException2(self):
tcl = self.interp
self.assertRaises(TclError,tcl.call,'this','is','wrong')
def testSetVar(self):
tcl = self.interp
tcl.setvar('a','1')
self.assertEqual(tcl.eval('set a'),'1')
def testSetVarArray(self):
tcl = self.interp
tcl.setvar('a(1)','1')
self.assertEqual(tcl.eval('set a(1)'),'1')
def testGetVar(self):
tcl = self.interp
tcl.eval('set a 1')
self.assertEqual(tcl.getvar('a'),'1')
def testGetVarArray(self):
tcl = self.interp
tcl.eval('set a(1) 1')
self.assertEqual(tcl.getvar('a(1)'),'1')
def testGetVarException(self):
tcl = self.interp
self.assertRaises(TclError,tcl.getvar,'a')
def testGetVarArrayException(self):
tcl = self.interp
self.assertRaises(TclError,tcl.getvar,'a(1)')
def testUnsetVar(self):
tcl = self.interp
tcl.setvar('a',1)
self.assertEqual(tcl.eval('info exists a'),'1')
tcl.unsetvar('a')
self.assertEqual(tcl.eval('info exists a'),'0')
def testUnsetVarArray(self):
tcl = self.interp
tcl.setvar('a(1)',1)
tcl.setvar('a(2)',2)
self.assertEqual(tcl.eval('info exists a(1)'),'1')
self.assertEqual(tcl.eval('info exists a(2)'),'1')
tcl.unsetvar('a(1)')
self.assertEqual(tcl.eval('info exists a(1)'),'0')
self.assertEqual(tcl.eval('info exists a(2)'),'1')
def testUnsetVarException(self):
tcl = self.interp
self.assertRaises(TclError,tcl.unsetvar,'a')
def get_integers(self):
integers = (0, 1, -1, 2**31-1, -2**31, 2**31, -2**31-1, 2**63-1, -2**63)
# bignum was added in Tcl 8.5, but its support is able only since 8.5.8
if (get_tk_patchlevel() >= (8, 6, 0, 'final') or
(8, 5, 8) <= get_tk_patchlevel() < (8, 6)):
integers += (2**63, -2**63-1, 2**1000, -2**1000)
return integers
def test_getint(self):
tcl = self.interp.tk
for i in self.get_integers():
self.assertEqual(tcl.getint(' %d ' % i), i)
if tcl_version >= (8, 5):
self.assertEqual(tcl.getint(' %#o ' % i), i)
self.assertEqual(tcl.getint((' %#o ' % i).replace('o', '')), i)
self.assertEqual(tcl.getint(' %#x ' % i), i)
if tcl_version < (8, 5): # bignum was added in Tcl 8.5
self.assertRaises(TclError, tcl.getint, str(2**1000))
self.assertEqual(tcl.getint(42), 42)
self.assertRaises(TypeError, tcl.getint)
self.assertRaises(TypeError, tcl.getint, '42', '10')
self.assertRaises(TypeError, tcl.getint, b'42')
self.assertRaises(TypeError, tcl.getint, 42.0)
self.assertRaises(TclError, tcl.getint, 'a')
self.assertRaises((TypeError, ValueError, TclError),
tcl.getint, '42\0')
self.assertRaises((UnicodeEncodeError, ValueError, TclError),
tcl.getint, '42\ud800')
def test_getdouble(self):
tcl = self.interp.tk
self.assertEqual(tcl.getdouble(' 42 '), 42.0)
self.assertEqual(tcl.getdouble(' 42.5 '), 42.5)
self.assertEqual(tcl.getdouble(42.5), 42.5)
self.assertEqual(tcl.getdouble(42), 42.0)
self.assertRaises(TypeError, tcl.getdouble)
self.assertRaises(TypeError, tcl.getdouble, '42.5', '10')
self.assertRaises(TypeError, tcl.getdouble, b'42.5')
self.assertRaises(TclError, tcl.getdouble, 'a')
self.assertRaises((TypeError, ValueError, TclError),
tcl.getdouble, '42.5\0')
self.assertRaises((UnicodeEncodeError, ValueError, TclError),
tcl.getdouble, '42.5\ud800')
def test_getboolean(self):
tcl = self.interp.tk
self.assertIs(tcl.getboolean('on'), True)
self.assertIs(tcl.getboolean('1'), True)
self.assertIs(tcl.getboolean(42), True)
self.assertIs(tcl.getboolean(0), False)
self.assertRaises(TypeError, tcl.getboolean)
self.assertRaises(TypeError, tcl.getboolean, 'on', '1')
self.assertRaises(TypeError, tcl.getboolean, b'on')
self.assertRaises(TypeError, tcl.getboolean, 1.0)
self.assertRaises(TclError, tcl.getboolean, 'a')
self.assertRaises((TypeError, ValueError, TclError),
tcl.getboolean, 'on\0')
self.assertRaises((UnicodeEncodeError, ValueError, TclError),
tcl.getboolean, 'on\ud800')
def testEvalFile(self):
tcl = self.interp
with open(support.TESTFN, 'w') as f:
self.addCleanup(support.unlink, support.TESTFN)
f.write("""set a 1
set b 2
set c [ expr $a + $b ]
""")
tcl.evalfile(support.TESTFN)
self.assertEqual(tcl.eval('set a'),'1')
self.assertEqual(tcl.eval('set b'),'2')
self.assertEqual(tcl.eval('set c'),'3')
def test_evalfile_null_in_result(self):
tcl = self.interp
with open(support.TESTFN, 'w') as f:
self.addCleanup(support.unlink, support.TESTFN)
f.write("""
set a "a\0b"
set b "a\\0b"
""")
tcl.evalfile(support.TESTFN)
self.assertEqual(tcl.eval('set a'), 'a\x00b')
self.assertEqual(tcl.eval('set b'), 'a\x00b')
def testEvalFileException(self):
tcl = self.interp
filename = "doesnotexists"
try:
os.remove(filename)
except Exception as e:
pass
self.assertRaises(TclError,tcl.evalfile,filename)
def testPackageRequireException(self):
tcl = self.interp
self.assertRaises(TclError,tcl.eval,'package require DNE')
@unittest.skipUnless(sys.platform == 'win32', 'Requires Windows')
def testLoadWithUNC(self):
# Build a UNC path from the regular path.
# Something like
# \\%COMPUTERNAME%\c$\python27\python.exe
fullname = os.path.abspath(sys.executable)
if fullname[1] != ':':
raise unittest.SkipTest('Absolute path should have drive part')
unc_name = r'\\%s\%s$\%s' % (os.environ['COMPUTERNAME'],
fullname[0],
fullname[3:])
if not os.path.exists(unc_name):
raise unittest.SkipTest('Cannot connect to UNC Path')
with support.EnvironmentVarGuard() as env:
env.unset("TCL_LIBRARY")
stdout = subprocess.check_output(
[unc_name, '-c', 'import tkinter; print(tkinter)'])
self.assertIn(b'tkinter', stdout)
def test_exprstring(self):
tcl = self.interp
tcl.call('set', 'a', 3)
tcl.call('set', 'b', 6)
def check(expr, expected):
result = tcl.exprstring(expr)
self.assertEqual(result, expected)
self.assertIsInstance(result, str)
self.assertRaises(TypeError, tcl.exprstring)
self.assertRaises(TypeError, tcl.exprstring, '8.2', '+6')
self.assertRaises(TypeError, tcl.exprstring, b'8.2 + 6')
self.assertRaises(TclError, tcl.exprstring, 'spam')
check('', '0')
check('8.2 + 6', '14.2')
check('3.1 + $a', '6.1')
check('2 + "$a.$b"', '5.6')
check('4*[llength "6 2"]', '8')
check('{word one} < "word $a"', '0')
check('4*2 < 7', '0')
check('hypot($a, 4)', '5.0')
check('5 / 4', '1')
check('5 / 4.0', '1.25')
check('5 / ( [string length "abcd"] + 0.0 )', '1.25')
check('20.0/5.0', '4.0')
check('"0x03" > "2"', '1')
check('[string length "a\xbd\u20ac"]', '3')
check(r'[string length "a\xbd\u20ac"]', '3')
check('"abc"', 'abc')
check('"a\xbd\u20ac"', 'a\xbd\u20ac')
check(r'"a\xbd\u20ac"', 'a\xbd\u20ac')
check(r'"a\0b"', 'a\x00b')
if tcl_version >= (8, 5): # bignum was added in Tcl 8.5
check('2**64', str(2**64))
def test_exprdouble(self):
tcl = self.interp
tcl.call('set', 'a', 3)
tcl.call('set', 'b', 6)
def check(expr, expected):
result = tcl.exprdouble(expr)
self.assertEqual(result, expected)
self.assertIsInstance(result, float)
self.assertRaises(TypeError, tcl.exprdouble)
self.assertRaises(TypeError, tcl.exprdouble, '8.2', '+6')
self.assertRaises(TypeError, tcl.exprdouble, b'8.2 + 6')
self.assertRaises(TclError, tcl.exprdouble, 'spam')
check('', 0.0)
check('8.2 + 6', 14.2)
check('3.1 + $a', 6.1)
check('2 + "$a.$b"', 5.6)
check('4*[llength "6 2"]', 8.0)
check('{word one} < "word $a"', 0.0)
check('4*2 < 7', 0.0)
check('hypot($a, 4)', 5.0)
check('5 / 4', 1.0)
check('5 / 4.0', 1.25)
check('5 / ( [string length "abcd"] + 0.0 )', 1.25)
check('20.0/5.0', 4.0)
check('"0x03" > "2"', 1.0)
check('[string length "a\xbd\u20ac"]', 3.0)
check(r'[string length "a\xbd\u20ac"]', 3.0)
self.assertRaises(TclError, tcl.exprdouble, '"abc"')
if tcl_version >= (8, 5): # bignum was added in Tcl 8.5
check('2**64', float(2**64))
def test_exprlong(self):
tcl = self.interp
tcl.call('set', 'a', 3)
tcl.call('set', 'b', 6)
def check(expr, expected):
result = tcl.exprlong(expr)
self.assertEqual(result, expected)
self.assertIsInstance(result, int)
self.assertRaises(TypeError, tcl.exprlong)
self.assertRaises(TypeError, tcl.exprlong, '8.2', '+6')
self.assertRaises(TypeError, tcl.exprlong, b'8.2 + 6')
self.assertRaises(TclError, tcl.exprlong, 'spam')
check('', 0)
check('8.2 + 6', 14)
check('3.1 + $a', 6)
check('2 + "$a.$b"', 5)
check('4*[llength "6 2"]', 8)
check('{word one} < "word $a"', 0)
check('4*2 < 7', 0)
check('hypot($a, 4)', 5)
check('5 / 4', 1)
check('5 / 4.0', 1)
check('5 / ( [string length "abcd"] + 0.0 )', 1)
check('20.0/5.0', 4)
check('"0x03" > "2"', 1)
check('[string length "a\xbd\u20ac"]', 3)
check(r'[string length "a\xbd\u20ac"]', 3)
self.assertRaises(TclError, tcl.exprlong, '"abc"')
if tcl_version >= (8, 5): # bignum was added in Tcl 8.5
self.assertRaises(TclError, tcl.exprlong, '2**64')
def test_exprboolean(self):
tcl = self.interp
tcl.call('set', 'a', 3)
tcl.call('set', 'b', 6)
def check(expr, expected):
result = tcl.exprboolean(expr)
self.assertEqual(result, expected)
self.assertIsInstance(result, int)
self.assertNotIsInstance(result, bool)
self.assertRaises(TypeError, tcl.exprboolean)
self.assertRaises(TypeError, tcl.exprboolean, '8.2', '+6')
self.assertRaises(TypeError, tcl.exprboolean, b'8.2 + 6')
self.assertRaises(TclError, tcl.exprboolean, 'spam')
check('', False)
for value in ('0', 'false', 'no', 'off'):
check(value, False)
check('"%s"' % value, False)
check('{%s}' % value, False)
for value in ('1', 'true', 'yes', 'on'):
check(value, True)
check('"%s"' % value, True)
check('{%s}' % value, True)
check('8.2 + 6', True)
check('3.1 + $a', True)
check('2 + "$a.$b"', True)
check('4*[llength "6 2"]', True)
check('{word one} < "word $a"', False)
check('4*2 < 7', False)
check('hypot($a, 4)', True)
check('5 / 4', True)
check('5 / 4.0', True)
check('5 / ( [string length "abcd"] + 0.0 )', True)
check('20.0/5.0', True)
check('"0x03" > "2"', True)
check('[string length "a\xbd\u20ac"]', True)
check(r'[string length "a\xbd\u20ac"]', True)
self.assertRaises(TclError, tcl.exprboolean, '"abc"')
if tcl_version >= (8, 5): # bignum was added in Tcl 8.5
check('2**64', True)
@unittest.skipUnless(tcl_version >= (8, 5), 'requires Tcl version >= 8.5')
def test_booleans(self):
tcl = self.interp
def check(expr, expected):
result = tcl.call('expr', expr)
if tcl.wantobjects():
self.assertEqual(result, expected)
self.assertIsInstance(result, int)
else:
self.assertIn(result, (expr, str(int(expected))))
self.assertIsInstance(result, str)
check('true', True)
check('yes', True)
check('on', True)
check('false', False)
check('no', False)
check('off', False)
check('1 < 2', True)
check('1 > 2', False)
def test_expr_bignum(self):
tcl = self.interp
for i in self.get_integers():
result = tcl.call('expr', str(i))
if self.wantobjects:
self.assertEqual(result, i)
self.assertIsInstance(result, int)
else:
self.assertEqual(result, str(i))
self.assertIsInstance(result, str)
if tcl_version < (8, 5): # bignum was added in Tcl 8.5
self.assertRaises(TclError, tcl.call, 'expr', str(2**1000))
def test_passing_values(self):
def passValue(value):
return self.interp.call('set', '_', value)
self.assertEqual(passValue(True), True if self.wantobjects else '1')
self.assertEqual(passValue(False), False if self.wantobjects else '0')
self.assertEqual(passValue('string'), 'string')
self.assertEqual(passValue('string\u20ac'), 'string\u20ac')
self.assertEqual(passValue('str\x00ing'), 'str\x00ing')
self.assertEqual(passValue('str\x00ing\xbd'), 'str\x00ing\xbd')
self.assertEqual(passValue('str\x00ing\u20ac'), 'str\x00ing\u20ac')
self.assertEqual(passValue(b'str\x00ing'),
b'str\x00ing' if self.wantobjects else 'str\x00ing')
self.assertEqual(passValue(b'str\xc0\x80ing'),
b'str\xc0\x80ing' if self.wantobjects else 'str\xc0\x80ing')
self.assertEqual(passValue(b'str\xbding'),
b'str\xbding' if self.wantobjects else 'str\xbding')
for i in self.get_integers():
self.assertEqual(passValue(i), i if self.wantobjects else str(i))
if tcl_version < (8, 5): # bignum was added in Tcl 8.5
self.assertEqual(passValue(2**1000), str(2**1000))
for f in (0.0, 1.0, -1.0, 1/3,
sys.float_info.min, sys.float_info.max,
-sys.float_info.min, -sys.float_info.max):
if self.wantobjects:
self.assertEqual(passValue(f), f)
else:
self.assertEqual(float(passValue(f)), f)
if self.wantobjects:
f = passValue(float('nan'))
self.assertNotEqual(f, f)
self.assertEqual(passValue(float('inf')), float('inf'))
self.assertEqual(passValue(-float('inf')), -float('inf'))
else:
self.assertEqual(float(passValue(float('inf'))), float('inf'))
self.assertEqual(float(passValue(-float('inf'))), -float('inf'))
# XXX NaN representation can be not parsable by float()
self.assertEqual(passValue((1, '2', (3.4,))),
(1, '2', (3.4,)) if self.wantobjects else '1 2 3.4')
self.assertEqual(passValue(['a', ['b', 'c']]),
('a', ('b', 'c')) if self.wantobjects else 'a {b c}')
def test_user_command(self):
result = None
def testfunc(arg):
nonlocal result
result = arg
return arg
self.interp.createcommand('testfunc', testfunc)
self.addCleanup(self.interp.tk.deletecommand, 'testfunc')
def check(value, expected=None, *, eq=self.assertEqual):
if expected is None:
expected = value
nonlocal result
result = None
r = self.interp.call('testfunc', value)
self.assertIsInstance(result, str)
eq(result, expected)
self.assertIsInstance(r, str)
eq(r, expected)
def float_eq(actual, expected):
self.assertAlmostEqual(float(actual), expected,
delta=abs(expected) * 1e-10)
check(True, '1')
check(False, '0')
check('string')
check('string\xbd')
check('string\u20ac')
check('')
check(b'string', 'string')
check(b'string\xe2\x82\xac', 'string\xe2\x82\xac')
check(b'string\xbd', 'string\xbd')
check(b'', '')
check('str\x00ing')
check('str\x00ing\xbd')
check('str\x00ing\u20ac')
check(b'str\x00ing', 'str\x00ing')
check(b'str\xc0\x80ing', 'str\xc0\x80ing')
check(b'str\xc0\x80ing\xe2\x82\xac', 'str\xc0\x80ing\xe2\x82\xac')
for i in self.get_integers():
check(i, str(i))
if tcl_version < (8, 5): # bignum was added in Tcl 8.5
check(2**1000, str(2**1000))
for f in (0.0, 1.0, -1.0):
check(f, repr(f))
for f in (1/3.0, sys.float_info.min, sys.float_info.max,
-sys.float_info.min, -sys.float_info.max):
check(f, eq=float_eq)
check(float('inf'), eq=float_eq)
check(-float('inf'), eq=float_eq)
# XXX NaN representation can be not parsable by float()
check((), '')
check((1, (2,), (3, 4), '5 6', ()), '1 2 {3 4} {5 6} {}')
check([1, [2,], [3, 4], '5 6', []], '1 2 {3 4} {5 6} {}')
def test_splitlist(self):
splitlist = self.interp.tk.splitlist
call = self.interp.tk.call
self.assertRaises(TypeError, splitlist)
self.assertRaises(TypeError, splitlist, 'a', 'b')
self.assertRaises(TypeError, splitlist, 2)
testcases = [
('2', ('2',)),
('', ()),
('{}', ('',)),
('""', ('',)),
('a\n b\t\r c\n ', ('a', 'b', 'c')),
(b'a\n b\t\r c\n ', ('a', 'b', 'c')),
('a \u20ac', ('a', '\u20ac')),
(b'a \xe2\x82\xac', ('a', '\u20ac')),
(b'a\xc0\x80b c\xc0\x80d', ('a\x00b', 'c\x00d')),
('a {b c}', ('a', 'b c')),
(r'a b\ c', ('a', 'b c')),
(('a', 'b c'), ('a', 'b c')),
('a 2', ('a', '2')),
(('a', 2), ('a', 2)),
('a 3.4', ('a', '3.4')),
(('a', 3.4), ('a', 3.4)),
((), ()),
([], ()),
(['a', ['b', 'c']], ('a', ['b', 'c'])),
(call('list', 1, '2', (3.4,)),
(1, '2', (3.4,)) if self.wantobjects else
('1', '2', '3.4')),
]
tk_patchlevel = get_tk_patchlevel()
if tcl_version >= (8, 5):
if not self.wantobjects or tk_patchlevel < (8, 5, 5):
# Before 8.5.5 dicts were converted to lists through string
expected = ('12', '\u20ac', '\xe2\x82\xac', '3.4')
else:
expected = (12, '\u20ac', b'\xe2\x82\xac', (3.4,))
testcases += [
(call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac', (3.4,)),
expected),
]
dbg_info = ('want objects? %s, Tcl version: %s, Tk patchlevel: %s'
% (self.wantobjects, tcl_version, tk_patchlevel))
for arg, res in testcases:
self.assertEqual(splitlist(arg), res,
'arg=%a, %s' % (arg, dbg_info))
self.assertRaises(TclError, splitlist, '{')
def test_split(self):
split = self.interp.tk.split
call = self.interp.tk.call
self.assertRaises(TypeError, split)
self.assertRaises(TypeError, split, 'a', 'b')
self.assertRaises(TypeError, split, 2)
testcases = [
('2', '2'),
('', ''),
('{}', ''),
('""', ''),
('{', '{'),
('a\n b\t\r c\n ', ('a', 'b', 'c')),
(b'a\n b\t\r c\n ', ('a', 'b', 'c')),
('a \u20ac', ('a', '\u20ac')),
(b'a \xe2\x82\xac', ('a', '\u20ac')),
(b'a\xc0\x80b', 'a\x00b'),
(b'a\xc0\x80b c\xc0\x80d', ('a\x00b', 'c\x00d')),
(b'{a\xc0\x80b c\xc0\x80d', '{a\x00b c\x00d'),
('a {b c}', ('a', ('b', 'c'))),
(r'a b\ c', ('a', ('b', 'c'))),
(('a', b'b c'), ('a', ('b', 'c'))),
(('a', 'b c'), ('a', ('b', 'c'))),
('a 2', ('a', '2')),
(('a', 2), ('a', 2)),
('a 3.4', ('a', '3.4')),
(('a', 3.4), ('a', 3.4)),
(('a', (2, 3.4)), ('a', (2, 3.4))),
((), ()),
([], ()),
(['a', 'b c'], ('a', ('b', 'c'))),
(['a', ['b', 'c']], ('a', ('b', 'c'))),
(call('list', 1, '2', (3.4,)),
(1, '2', (3.4,)) if self.wantobjects else
('1', '2', '3.4')),
]
if tcl_version >= (8, 5):
if not self.wantobjects or get_tk_patchlevel() < (8, 5, 5):
# Before 8.5.5 dicts were converted to lists through string
expected = ('12', '\u20ac', '\xe2\x82\xac', '3.4')
else:
expected = (12, '\u20ac', b'\xe2\x82\xac', (3.4,))
testcases += [
(call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac', (3.4,)),
expected),
]
for arg, res in testcases:
self.assertEqual(split(arg), res, msg=arg)
def test_splitdict(self):
splitdict = tkinter._splitdict
tcl = self.interp.tk
arg = '-a {1 2 3} -something foo status {}'
self.assertEqual(splitdict(tcl, arg, False),
{'-a': '1 2 3', '-something': 'foo', 'status': ''})
self.assertEqual(splitdict(tcl, arg),
{'a': '1 2 3', 'something': 'foo', 'status': ''})
arg = ('-a', (1, 2, 3), '-something', 'foo', 'status', '{}')
self.assertEqual(splitdict(tcl, arg, False),
{'-a': (1, 2, 3), '-something': 'foo', 'status': '{}'})
self.assertEqual(splitdict(tcl, arg),
{'a': (1, 2, 3), 'something': 'foo', 'status': '{}'})
self.assertRaises(RuntimeError, splitdict, tcl, '-a b -c ')
self.assertRaises(RuntimeError, splitdict, tcl, ('-a', 'b', '-c'))
arg = tcl.call('list',
'-a', (1, 2, 3), '-something', 'foo', 'status', ())
self.assertEqual(splitdict(tcl, arg),
{'a': (1, 2, 3) if self.wantobjects else '1 2 3',
'something': 'foo', 'status': ''})
if tcl_version >= (8, 5):
arg = tcl.call('dict', 'create',
'-a', (1, 2, 3), '-something', 'foo', 'status', ())
if not self.wantobjects or get_tk_patchlevel() < (8, 5, 5):
# Before 8.5.5 dicts were converted to lists through string
expected = {'a': '1 2 3', 'something': 'foo', 'status': ''}
else:
expected = {'a': (1, 2, 3), 'something': 'foo', 'status': ''}
self.assertEqual(splitdict(tcl, arg), expected)
def test_join(self):
join = tkinter._join
tcl = self.interp.tk
def unpack(s):
return tcl.call('lindex', s, 0)
def check(value):
self.assertEqual(unpack(join([value])), value)
self.assertEqual(unpack(join([value, 0])), value)
self.assertEqual(unpack(unpack(join([[value]]))), value)
self.assertEqual(unpack(unpack(join([[value, 0]]))), value)
self.assertEqual(unpack(unpack(join([[value], 0]))), value)
self.assertEqual(unpack(unpack(join([[value, 0], 0]))), value)
check('')
check('spam')
check('sp am')
check('sp\tam')
check('sp\nam')
check(' \t\n')
check('{spam}')
check('{sp am}')
check('"spam"')
check('"sp am"')
check('{"spam"}')
check('"{spam}"')
check('sp\\am')
check('"sp\\am"')
check('"{}" "{}"')
check('"\\')
check('"{')
check('"}')
check('\n\\')
check('\n{')
check('\n}')
check('\\\n')
check('{\n')
check('}\n')
def test_new_tcl_obj(self):
self.assertRaises(TypeError, _tkinter.Tcl_Obj)
class BigmemTclTest(unittest.TestCase):
def setUp(self):
self.interp = Tcl()
@support.cpython_only
@unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX, "needs UINT_MAX < SIZE_MAX")
@support.bigmemtest(size=INT_MAX + 1, memuse=5, dry_run=False)
def test_huge_string_call(self, size):
value = ' ' * size
self.assertRaises(OverflowError, self.interp.call, 'string', 'index', value, 0)
@support.cpython_only
@unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX, "needs UINT_MAX < SIZE_MAX")
@support.bigmemtest(size=INT_MAX + 1, memuse=2, dry_run=False)
def test_huge_string_builtins(self, size):
tk = self.interp.tk
value = '1' + ' ' * size
self.assertRaises(OverflowError, tk.getint, value)
self.assertRaises(OverflowError, tk.getdouble, value)
self.assertRaises(OverflowError, tk.getboolean, value)
self.assertRaises(OverflowError, tk.eval, value)
self.assertRaises(OverflowError, tk.evalfile, value)
self.assertRaises(OverflowError, tk.record, value)
self.assertRaises(OverflowError, tk.adderrorinfo, value)
self.assertRaises(OverflowError, tk.setvar, value, 'x', 'a')
self.assertRaises(OverflowError, tk.setvar, 'x', value, 'a')
self.assertRaises(OverflowError, tk.unsetvar, value)
self.assertRaises(OverflowError, tk.unsetvar, 'x', value)
self.assertRaises(OverflowError, tk.adderrorinfo, value)
self.assertRaises(OverflowError, tk.exprstring, value)
self.assertRaises(OverflowError, tk.exprlong, value)
self.assertRaises(OverflowError, tk.exprboolean, value)
self.assertRaises(OverflowError, tk.splitlist, value)
self.assertRaises(OverflowError, tk.split, value)
self.assertRaises(OverflowError, tk.createcommand, value, max)
self.assertRaises(OverflowError, tk.deletecommand, value)
@support.cpython_only
@unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX, "needs UINT_MAX < SIZE_MAX")
@support.bigmemtest(size=INT_MAX + 1, memuse=6, dry_run=False)
def test_huge_string_builtins2(self, size):
# These commands require larger memory for possible error messages
tk = self.interp.tk
value = '1' + ' ' * size
self.assertRaises(OverflowError, tk.evalfile, value)
self.assertRaises(OverflowError, tk.unsetvar, value)
self.assertRaises(OverflowError, tk.unsetvar, 'x', value)
def setUpModule():
if support.verbose:
tcl = Tcl()
print('patchlevel =', tcl.call('info', 'patchlevel'))
def test_main():
support.run_unittest(TclTest, TkinterTest, BigmemTclTest)
if __name__ == "__main__":
test_main()
| 29,633 | 753 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/randv2_32.pck | crandom
Random
p0
(tRp1
(I2
(I-2147483648
I-845974985
I-1294090086
I1193659239
I-1849481736
I-946579732
I-34406770
I1749049471
I1997774682
I1432026457
I1288127073
I-943175655
I-1718073964
I339993548
I-1045260575
I582505037
I-1555108250
I-1114765620
I1578648750
I-350384412
I-20845848
I-288255314
I738790953
I1901249641
I1999324672
I-277361068
I-1515885839
I2061761596
I-809068089
I1287981136
I258129492
I-6303745
I-765148337
I1090344911
I1653434703
I-1242923628
I1639171313
I-1870042660
I-1655014050
I345609048
I2093410138
I1963263374
I-2122098342
I1336859961
I-810942729
I945857753
I2103049942
I623922684
I1418349549
I690877342
I754973107
I-1605111847
I1607137813
I-1704917131
I1317536428
I1714882872
I-1665385120
I1823694397
I-1790836866
I-1696724812
I-603979847
I-498599394
I-341265291
I927388804
I1778562135
I1716895781
I1023198122
I1726145967
I941955525
I1240148950
I-1929634545
I-1288147083
I-519318335
I754559777
I-707571958
I374604022
I420424061
I-1095443486
I1621934944
I-1220502522
I-140049608
I-918917122
I304341024
I-1637446057
I-353934485
I1973436235
I433380241
I-686759465
I-2111563154
I-573422032
I804304541
I1513063483
I1417381689
I-804778729
I211756408
I544537322
I890881641
I150378374
I1765739392
I1011604116
I584889095
I1400520554
I413747808
I-1741992587
I-1882421574
I-1373001903
I-1885348538
I903819480
I1083220038
I-1318105424
I1740421404
I1693089625
I775965557
I1319608037
I-2127475785
I-367562895
I-1416273451
I1693000327
I-1217438421
I834405522
I-128287275
I864057548
I-973917356
I7304111
I1712253182
I1353897741
I672982288
I1778575559
I-403058377
I-38540378
I-1393713496
I13193171
I1127196200
I205176472
I-2104790506
I299985416
I1403541685
I-1018270667
I-1980677490
I-1182625797
I1637015181
I-1795357414
I1514413405
I-924516237
I-1841873650
I-1014591269
I1576616065
I-1319103135
I-120847840
I2062259778
I-9285070
I1160890300
I-575137313
I-1509108275
I46701926
I-287560914
I-256824960
I577558250
I900598310
I944607867
I2121154920
I-1170505192
I-1347170575
I77247778
I-1899015765
I1234103327
I1027053658
I1934632322
I-792031234
I1147322536
I1290655117
I1002059715
I1325898538
I896029793
I-790940694
I-980470721
I-1922648255
I-951672814
I291543943
I1158740218
I-1959023736
I-1977185236
I1527900076
I514104195
I-814154113
I-593157883
I-1023704660
I1285688377
I-2117525386
I768954360
I-38676846
I-799848659
I-1305517259
I-1938213641
I-462146758
I-1663302892
I1899591069
I-22935388
I-275856976
I-443736893
I-739441156
I93862068
I-838105669
I1735629845
I-817484206
I280814555
I1753547179
I1811123479
I1974543632
I-48447465
I-642694345
I-531149613
I518698953
I-221642627
I-686519187
I776644303
I257774400
I-1499134857
I-1055273455
I-237023943
I1981752330
I-917671662
I-372905983
I1588058420
I1171936660
I-1730977121
I1360028989
I1769469287
I1910709542
I-852692959
I1396944667
I-1723999155
I-310975435
I-1965453954
I-1636858570
I2005650794
I680293715
I1355629386
I844514684
I-1909152807
I-808646074
I1936510018
I1134413810
I-143411047
I-1478436304
I1394969244
I-1170110660
I1963112086
I-1518351049
I-1506287443
I-455023090
I-855366028
I-1746785568
I933990882
I-703625141
I-285036872
I188277905
I1471578620
I-981382835
I-586974220
I945619758
I1608778444
I-1708548066
I-1897629320
I-42617810
I-836840790
I539154487
I-235706962
I332074418
I-575700589
I1534608003
I632116560
I-1819760653
I642052958
I-722391771
I-1104719475
I-1196847084
I582413973
I1563394876
I642007944
I108989456
I361625014
I677308625
I-1806529496
I-959050708
I-1858251070
I-216069832
I701624579
I501238033
I12287030
I1895107107
I2089098638
I-874806230
I1236279203
I563718890
I-544352489
I-1879707498
I1767583393
I-1776604656
I-693294301
I-88882831
I169303357
I1299196152
I-1122791089
I-379157172
I1934671851
I1575736961
I-19573174
I-1401511009
I9305167
I-1115174467
I1670735537
I1226436501
I-2004524535
I1767463878
I-1722855079
I-559413926
I1529810851
I1201272087
I-1297130971
I-1188149982
I1396557188
I-370358342
I-1006619702
I1600942463
I906087130
I-76991909
I2069580179
I-1674195181
I-2098404729
I-940972459
I-573399187
I-1930386277
I-721311199
I-647834744
I1452181671
I688681916
I1812793731
I1704380620
I-1389615179
I866287837
I-1435265007
I388400782
I-147986600
I-1613598851
I-1040347408
I782063323
I-239282031
I-575966722
I-1865208174
I-481365146
I579572803
I-1239481494
I335361280
I-429722947
I1881772789
I1908103808
I1653690013
I-1668588344
I1933787953
I-2033480609
I22162797
I-1516527040
I-461232482
I-16201372
I-2043092030
I114990337
I-1524090084
I1456374020
I458606440
I-1928083218
I227773125
I-1129028159
I1678689
I1575896907
I-1792935220
I-151387575
I64084088
I-95737215
I1337335688
I-1963466345
I1243315130
I-1798518411
I-546013212
I-607065396
I1219824160
I1715218469
I-1368163783
I1701552913
I-381114888
I1068821717
I266062971
I-2066513172
I1767407229
I-780936414
I-705413443
I-1256268847
I1646874149
I1107690353
I839133072
I67001749
I860763503
I884880613
I91977084
I755371933
I420745153
I-578480690
I-1520193551
I1011369331
I-99754575
I-733141064
I-500598588
I1081124271
I-1341266575
I921002612
I-848852487
I-1904467341
I-1294256973
I-94074714
I-1778758498
I-1401188547
I2101830578
I2058864877
I-272875991
I-1375854779
I-1332937870
I619425525
I-1034529639
I-36454393
I-2030499985
I-1637127500
I-1408110287
I-2108625749
I-961007436
I1475654951
I-791946251
I1667792115
I1818978830
I1897980514
I1959546477
I-74478911
I-508643347
I461594399
I538802715
I-2094970071
I-2076660253
I1091358944
I1944029246
I-343957436
I-1915845022
I1237620188
I1144125174
I1522190520
I-670252952
I-19469226
I675626510
I758750096
I909724354
I-1846259652
I544669343
I445182495
I-821519930
I-1124279685
I-1668995122
I1653284793
I-678555151
I-687513207
I1558259445
I-1978866839
I1558835601
I1732138472
I-1904793363
I620020296
I1562597874
I1942617227
I-549632552
I721603795
I417978456
I-1355281522
I-538065208
I-1079523196
I187375699
I449064972
I1018083947
I1632388882
I-493269866
I92769041
I1477146750
I1782708404
I444873376
I1085851104
I-6823272
I-1302251853
I1602050688
I-1042187824
I287161745
I-1972094479
I103271491
I2131619773
I-2064115870
I766815498
I990861458
I-1664407378
I1083746756
I-1018331904
I-677315687
I-951670647
I-952356874
I451460609
I-818615564
I851439508
I656362634
I-1351240485
I823378078
I1985597385
I597757740
I-1512303057
I1590872798
I1108424213
I818850898
I-1368594306
I-201107761
I1793370378
I1247597611
I-1594326264
I-601653890
I427642759
I248322113
I-292545338
I1708985870
I1917042771
I429354503
I-478470329
I793960014
I369939133
I1728189157
I-518963626
I-278523974
I-1877289696
I-2088617658
I-1367940049
I-62295925
I197975119
I-252900777
I803430539
I485759441
I-528283480
I-1287443963
I-478617444
I-861906946
I-649095555
I-893184337
I2050571322
I803433133
I1629574571
I1649720417
I-2050225209
I1208598977
I720314344
I-615166251
I-835077127
I-1405372429
I995698064
I148123240
I-943016676
I-594609622
I-1381596711
I1017195301
I-1268893013
I-1815985179
I-1393570351
I-870027364
I-476064472
I185582645
I569863326
I1098584267
I-1599147006
I-485054391
I-852098365
I1477320135
I222316762
I-1515583064
I-935051367
I393383063
I819617226
I722921837
I-1241806499
I-1358566385
I1666813591
I1333875114
I-1663688317
I-47254623
I-885800726
I307388991
I-1219459496
I1374870300
I2132047877
I-1385624198
I-245139206
I1015139214
I-926198559
I1969798868
I-1950480619
I-559193432
I-1256446518
I-1983476981
I790179655
I1004289659
I1541827617
I1555805575
I501127333
I-1123446797
I-453230915
I2035104883
I1296122398
I-1843698604
I-715464588
I337143971
I-1972119192
I606777909
I726977302
I-1149501872
I-1963733522
I-1797504644
I624
tp2
Ntp3
b. | 7,517 | 633 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_audioop.py | import audioop
import sys
import unittest
def pack(width, data):
return b''.join(v.to_bytes(width, sys.byteorder, signed=True) for v in data)
def unpack(width, data):
return [int.from_bytes(data[i: i + width], sys.byteorder, signed=True)
for i in range(0, len(data), width)]
packs = {w: (lambda *data, width=w: pack(width, data)) for w in (1, 2, 3, 4)}
maxvalues = {w: (1 << (8 * w - 1)) - 1 for w in (1, 2, 3, 4)}
minvalues = {w: -1 << (8 * w - 1) for w in (1, 2, 3, 4)}
datas = {
1: b'\x00\x12\x45\xbb\x7f\x80\xff',
2: packs[2](0, 0x1234, 0x4567, -0x4567, 0x7fff, -0x8000, -1),
3: packs[3](0, 0x123456, 0x456789, -0x456789, 0x7fffff, -0x800000, -1),
4: packs[4](0, 0x12345678, 0x456789ab, -0x456789ab,
0x7fffffff, -0x80000000, -1),
}
INVALID_DATA = [
(b'abc', 0),
(b'abc', 2),
(b'ab', 3),
(b'abc', 4),
]
class TestAudioop(unittest.TestCase):
def test_max(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.max(b'', w), 0)
self.assertEqual(audioop.max(bytearray(), w), 0)
self.assertEqual(audioop.max(memoryview(b''), w), 0)
p = packs[w]
self.assertEqual(audioop.max(p(5), w), 5)
self.assertEqual(audioop.max(p(5, -8, -1), w), 8)
self.assertEqual(audioop.max(p(maxvalues[w]), w), maxvalues[w])
self.assertEqual(audioop.max(p(minvalues[w]), w), -minvalues[w])
self.assertEqual(audioop.max(datas[w], w), -minvalues[w])
def test_minmax(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.minmax(b'', w),
(0x7fffffff, -0x80000000))
self.assertEqual(audioop.minmax(bytearray(), w),
(0x7fffffff, -0x80000000))
self.assertEqual(audioop.minmax(memoryview(b''), w),
(0x7fffffff, -0x80000000))
p = packs[w]
self.assertEqual(audioop.minmax(p(5), w), (5, 5))
self.assertEqual(audioop.minmax(p(5, -8, -1), w), (-8, 5))
self.assertEqual(audioop.minmax(p(maxvalues[w]), w),
(maxvalues[w], maxvalues[w]))
self.assertEqual(audioop.minmax(p(minvalues[w]), w),
(minvalues[w], minvalues[w]))
self.assertEqual(audioop.minmax(datas[w], w),
(minvalues[w], maxvalues[w]))
def test_maxpp(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.maxpp(b'', w), 0)
self.assertEqual(audioop.maxpp(bytearray(), w), 0)
self.assertEqual(audioop.maxpp(memoryview(b''), w), 0)
self.assertEqual(audioop.maxpp(packs[w](*range(100)), w), 0)
self.assertEqual(audioop.maxpp(packs[w](9, 10, 5, 5, 0, 1), w), 10)
self.assertEqual(audioop.maxpp(datas[w], w),
maxvalues[w] - minvalues[w])
def test_avg(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.avg(b'', w), 0)
self.assertEqual(audioop.avg(bytearray(), w), 0)
self.assertEqual(audioop.avg(memoryview(b''), w), 0)
p = packs[w]
self.assertEqual(audioop.avg(p(5), w), 5)
self .assertEqual(audioop.avg(p(5, 8), w), 6)
self.assertEqual(audioop.avg(p(5, -8), w), -2)
self.assertEqual(audioop.avg(p(maxvalues[w], maxvalues[w]), w),
maxvalues[w])
self.assertEqual(audioop.avg(p(minvalues[w], minvalues[w]), w),
minvalues[w])
self.assertEqual(audioop.avg(packs[4](0x50000000, 0x70000000), 4),
0x60000000)
self.assertEqual(audioop.avg(packs[4](-0x50000000, -0x70000000), 4),
-0x60000000)
def test_avgpp(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.avgpp(b'', w), 0)
self.assertEqual(audioop.avgpp(bytearray(), w), 0)
self.assertEqual(audioop.avgpp(memoryview(b''), w), 0)
self.assertEqual(audioop.avgpp(packs[w](*range(100)), w), 0)
self.assertEqual(audioop.avgpp(packs[w](9, 10, 5, 5, 0, 1), w), 10)
self.assertEqual(audioop.avgpp(datas[1], 1), 196)
self.assertEqual(audioop.avgpp(datas[2], 2), 50534)
self.assertEqual(audioop.avgpp(datas[3], 3), 12937096)
self.assertEqual(audioop.avgpp(datas[4], 4), 3311897002)
def test_rms(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.rms(b'', w), 0)
self.assertEqual(audioop.rms(bytearray(), w), 0)
self.assertEqual(audioop.rms(memoryview(b''), w), 0)
p = packs[w]
self.assertEqual(audioop.rms(p(*range(100)), w), 57)
self.assertAlmostEqual(audioop.rms(p(maxvalues[w]) * 5, w),
maxvalues[w], delta=1)
self.assertAlmostEqual(audioop.rms(p(minvalues[w]) * 5, w),
-minvalues[w], delta=1)
self.assertEqual(audioop.rms(datas[1], 1), 77)
self.assertEqual(audioop.rms(datas[2], 2), 20001)
self.assertEqual(audioop.rms(datas[3], 3), 5120523)
self.assertEqual(audioop.rms(datas[4], 4), 1310854152)
def test_cross(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.cross(b'', w), -1)
self.assertEqual(audioop.cross(bytearray(), w), -1)
self.assertEqual(audioop.cross(memoryview(b''), w), -1)
p = packs[w]
self.assertEqual(audioop.cross(p(0, 1, 2), w), 0)
self.assertEqual(audioop.cross(p(1, 2, -3, -4), w), 1)
self.assertEqual(audioop.cross(p(-1, -2, 3, 4), w), 1)
self.assertEqual(audioop.cross(p(0, minvalues[w]), w), 1)
self.assertEqual(audioop.cross(p(minvalues[w], maxvalues[w]), w), 1)
def test_add(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.add(b'', b'', w), b'')
self.assertEqual(audioop.add(bytearray(), bytearray(), w), b'')
self.assertEqual(audioop.add(memoryview(b''), memoryview(b''), w), b'')
self.assertEqual(audioop.add(datas[w], b'\0' * len(datas[w]), w),
datas[w])
self.assertEqual(audioop.add(datas[1], datas[1], 1),
b'\x00\x24\x7f\x80\x7f\x80\xfe')
self.assertEqual(audioop.add(datas[2], datas[2], 2),
packs[2](0, 0x2468, 0x7fff, -0x8000, 0x7fff, -0x8000, -2))
self.assertEqual(audioop.add(datas[3], datas[3], 3),
packs[3](0, 0x2468ac, 0x7fffff, -0x800000,
0x7fffff, -0x800000, -2))
self.assertEqual(audioop.add(datas[4], datas[4], 4),
packs[4](0, 0x2468acf0, 0x7fffffff, -0x80000000,
0x7fffffff, -0x80000000, -2))
def test_bias(self):
for w in 1, 2, 3, 4:
for bias in 0, 1, -1, 127, -128, 0x7fffffff, -0x80000000:
self.assertEqual(audioop.bias(b'', w, bias), b'')
self.assertEqual(audioop.bias(bytearray(), w, bias), b'')
self.assertEqual(audioop.bias(memoryview(b''), w, bias), b'')
self.assertEqual(audioop.bias(datas[1], 1, 1),
b'\x01\x13\x46\xbc\x80\x81\x00')
self.assertEqual(audioop.bias(datas[1], 1, -1),
b'\xff\x11\x44\xba\x7e\x7f\xfe')
self.assertEqual(audioop.bias(datas[1], 1, 0x7fffffff),
b'\xff\x11\x44\xba\x7e\x7f\xfe')
self.assertEqual(audioop.bias(datas[1], 1, -0x80000000),
datas[1])
self.assertEqual(audioop.bias(datas[2], 2, 1),
packs[2](1, 0x1235, 0x4568, -0x4566, -0x8000, -0x7fff, 0))
self.assertEqual(audioop.bias(datas[2], 2, -1),
packs[2](-1, 0x1233, 0x4566, -0x4568, 0x7ffe, 0x7fff, -2))
self.assertEqual(audioop.bias(datas[2], 2, 0x7fffffff),
packs[2](-1, 0x1233, 0x4566, -0x4568, 0x7ffe, 0x7fff, -2))
self.assertEqual(audioop.bias(datas[2], 2, -0x80000000),
datas[2])
self.assertEqual(audioop.bias(datas[3], 3, 1),
packs[3](1, 0x123457, 0x45678a, -0x456788,
-0x800000, -0x7fffff, 0))
self.assertEqual(audioop.bias(datas[3], 3, -1),
packs[3](-1, 0x123455, 0x456788, -0x45678a,
0x7ffffe, 0x7fffff, -2))
self.assertEqual(audioop.bias(datas[3], 3, 0x7fffffff),
packs[3](-1, 0x123455, 0x456788, -0x45678a,
0x7ffffe, 0x7fffff, -2))
self.assertEqual(audioop.bias(datas[3], 3, -0x80000000),
datas[3])
self.assertEqual(audioop.bias(datas[4], 4, 1),
packs[4](1, 0x12345679, 0x456789ac, -0x456789aa,
-0x80000000, -0x7fffffff, 0))
self.assertEqual(audioop.bias(datas[4], 4, -1),
packs[4](-1, 0x12345677, 0x456789aa, -0x456789ac,
0x7ffffffe, 0x7fffffff, -2))
self.assertEqual(audioop.bias(datas[4], 4, 0x7fffffff),
packs[4](0x7fffffff, -0x6dcba989, -0x3a987656, 0x3a987654,
-2, -1, 0x7ffffffe))
self.assertEqual(audioop.bias(datas[4], 4, -0x80000000),
packs[4](-0x80000000, -0x6dcba988, -0x3a987655, 0x3a987655,
-1, 0, 0x7fffffff))
def test_lin2lin(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.lin2lin(datas[w], w, w), datas[w])
self.assertEqual(audioop.lin2lin(bytearray(datas[w]), w, w),
datas[w])
self.assertEqual(audioop.lin2lin(memoryview(datas[w]), w, w),
datas[w])
self.assertEqual(audioop.lin2lin(datas[1], 1, 2),
packs[2](0, 0x1200, 0x4500, -0x4500, 0x7f00, -0x8000, -0x100))
self.assertEqual(audioop.lin2lin(datas[1], 1, 3),
packs[3](0, 0x120000, 0x450000, -0x450000,
0x7f0000, -0x800000, -0x10000))
self.assertEqual(audioop.lin2lin(datas[1], 1, 4),
packs[4](0, 0x12000000, 0x45000000, -0x45000000,
0x7f000000, -0x80000000, -0x1000000))
self.assertEqual(audioop.lin2lin(datas[2], 2, 1),
b'\x00\x12\x45\xba\x7f\x80\xff')
self.assertEqual(audioop.lin2lin(datas[2], 2, 3),
packs[3](0, 0x123400, 0x456700, -0x456700,
0x7fff00, -0x800000, -0x100))
self.assertEqual(audioop.lin2lin(datas[2], 2, 4),
packs[4](0, 0x12340000, 0x45670000, -0x45670000,
0x7fff0000, -0x80000000, -0x10000))
self.assertEqual(audioop.lin2lin(datas[3], 3, 1),
b'\x00\x12\x45\xba\x7f\x80\xff')
self.assertEqual(audioop.lin2lin(datas[3], 3, 2),
packs[2](0, 0x1234, 0x4567, -0x4568, 0x7fff, -0x8000, -1))
self.assertEqual(audioop.lin2lin(datas[3], 3, 4),
packs[4](0, 0x12345600, 0x45678900, -0x45678900,
0x7fffff00, -0x80000000, -0x100))
self.assertEqual(audioop.lin2lin(datas[4], 4, 1),
b'\x00\x12\x45\xba\x7f\x80\xff')
self.assertEqual(audioop.lin2lin(datas[4], 4, 2),
packs[2](0, 0x1234, 0x4567, -0x4568, 0x7fff, -0x8000, -1))
self.assertEqual(audioop.lin2lin(datas[4], 4, 3),
packs[3](0, 0x123456, 0x456789, -0x45678a,
0x7fffff, -0x800000, -1))
def test_adpcm2lin(self):
self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 1, None),
(b'\x00\x00\x00\xff\x00\xff', (-179, 40)))
self.assertEqual(audioop.adpcm2lin(bytearray(b'\x07\x7f\x7f'), 1, None),
(b'\x00\x00\x00\xff\x00\xff', (-179, 40)))
self.assertEqual(audioop.adpcm2lin(memoryview(b'\x07\x7f\x7f'), 1, None),
(b'\x00\x00\x00\xff\x00\xff', (-179, 40)))
self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 2, None),
(packs[2](0, 0xb, 0x29, -0x16, 0x72, -0xb3), (-179, 40)))
self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 3, None),
(packs[3](0, 0xb00, 0x2900, -0x1600, 0x7200,
-0xb300), (-179, 40)))
self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 4, None),
(packs[4](0, 0xb0000, 0x290000, -0x160000, 0x720000,
-0xb30000), (-179, 40)))
# Very cursory test
for w in 1, 2, 3, 4:
self.assertEqual(audioop.adpcm2lin(b'\0' * 5, w, None),
(b'\0' * w * 10, (0, 0)))
def test_lin2adpcm(self):
self.assertEqual(audioop.lin2adpcm(datas[1], 1, None),
(b'\x07\x7f\x7f', (-221, 39)))
self.assertEqual(audioop.lin2adpcm(bytearray(datas[1]), 1, None),
(b'\x07\x7f\x7f', (-221, 39)))
self.assertEqual(audioop.lin2adpcm(memoryview(datas[1]), 1, None),
(b'\x07\x7f\x7f', (-221, 39)))
for w in 2, 3, 4:
self.assertEqual(audioop.lin2adpcm(datas[w], w, None),
(b'\x07\x7f\x7f', (31, 39)))
# Very cursory test
for w in 1, 2, 3, 4:
self.assertEqual(audioop.lin2adpcm(b'\0' * w * 10, w, None),
(b'\0' * 5, (0, 0)))
def test_invalid_adpcm_state(self):
# state must be a tuple or None, not an integer
self.assertRaises(TypeError, audioop.adpcm2lin, b'\0', 1, 555)
self.assertRaises(TypeError, audioop.lin2adpcm, b'\0', 1, 555)
# Issues #24456, #24457: index out of range
self.assertRaises(ValueError, audioop.adpcm2lin, b'\0', 1, (0, -1))
self.assertRaises(ValueError, audioop.adpcm2lin, b'\0', 1, (0, 89))
self.assertRaises(ValueError, audioop.lin2adpcm, b'\0', 1, (0, -1))
self.assertRaises(ValueError, audioop.lin2adpcm, b'\0', 1, (0, 89))
# value out of range
self.assertRaises(ValueError, audioop.adpcm2lin, b'\0', 1, (-0x8001, 0))
self.assertRaises(ValueError, audioop.adpcm2lin, b'\0', 1, (0x8000, 0))
self.assertRaises(ValueError, audioop.lin2adpcm, b'\0', 1, (-0x8001, 0))
self.assertRaises(ValueError, audioop.lin2adpcm, b'\0', 1, (0x8000, 0))
def test_lin2alaw(self):
self.assertEqual(audioop.lin2alaw(datas[1], 1),
b'\xd5\x87\xa4\x24\xaa\x2a\x5a')
self.assertEqual(audioop.lin2alaw(bytearray(datas[1]), 1),
b'\xd5\x87\xa4\x24\xaa\x2a\x5a')
self.assertEqual(audioop.lin2alaw(memoryview(datas[1]), 1),
b'\xd5\x87\xa4\x24\xaa\x2a\x5a')
for w in 2, 3, 4:
self.assertEqual(audioop.lin2alaw(datas[w], w),
b'\xd5\x87\xa4\x24\xaa\x2a\x55')
def test_alaw2lin(self):
encoded = b'\x00\x03\x24\x2a\x51\x54\x55\x58\x6b\x71\x7f'\
b'\x80\x83\xa4\xaa\xd1\xd4\xd5\xd8\xeb\xf1\xff'
src = [-688, -720, -2240, -4032, -9, -3, -1, -27, -244, -82, -106,
688, 720, 2240, 4032, 9, 3, 1, 27, 244, 82, 106]
for w in 1, 2, 3, 4:
decoded = packs[w](*(x << (w * 8) >> 13 for x in src))
self.assertEqual(audioop.alaw2lin(encoded, w), decoded)
self.assertEqual(audioop.alaw2lin(bytearray(encoded), w), decoded)
self.assertEqual(audioop.alaw2lin(memoryview(encoded), w), decoded)
encoded = bytes(range(256))
for w in 2, 3, 4:
decoded = audioop.alaw2lin(encoded, w)
self.assertEqual(audioop.lin2alaw(decoded, w), encoded)
def test_lin2ulaw(self):
self.assertEqual(audioop.lin2ulaw(datas[1], 1),
b'\xff\xad\x8e\x0e\x80\x00\x67')
self.assertEqual(audioop.lin2ulaw(bytearray(datas[1]), 1),
b'\xff\xad\x8e\x0e\x80\x00\x67')
self.assertEqual(audioop.lin2ulaw(memoryview(datas[1]), 1),
b'\xff\xad\x8e\x0e\x80\x00\x67')
for w in 2, 3, 4:
# [jart] fixed off-by-one w/ itu primary materials
self.assertEqual(audioop.lin2ulaw(datas[w], w),
b'\xff\xad\x8e\x0e\x80\x00\x7f')
def test_ulaw2lin(self):
encoded = b'\x00\x0e\x28\x3f\x57\x6a\x76\x7c\x7e\x7f'\
b'\x80\x8e\xa8\xbf\xd7\xea\xf6\xfc\xfe\xff'
src = [-8031, -4447, -1471, -495, -163, -53, -18, -6, -2, 0,
8031, 4447, 1471, 495, 163, 53, 18, 6, 2, 0]
for w in 1, 2, 3, 4:
decoded = packs[w](*(x << (w * 8) >> 14 for x in src))
self.assertEqual(audioop.ulaw2lin(encoded, w), decoded)
self.assertEqual(audioop.ulaw2lin(bytearray(encoded), w), decoded)
self.assertEqual(audioop.ulaw2lin(memoryview(encoded), w), decoded)
# Current u-law implementation has two codes fo 0: 0x7f and 0xff.
encoded = bytes(range(127)) + bytes(range(128, 256))
for w in 2, 3, 4:
decoded = audioop.ulaw2lin(encoded, w)
self.assertEqual(audioop.lin2ulaw(decoded, w), encoded)
def test_mul(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.mul(b'', w, 2), b'')
self.assertEqual(audioop.mul(bytearray(), w, 2), b'')
self.assertEqual(audioop.mul(memoryview(b''), w, 2), b'')
self.assertEqual(audioop.mul(datas[w], w, 0),
b'\0' * len(datas[w]))
self.assertEqual(audioop.mul(datas[w], w, 1),
datas[w])
self.assertEqual(audioop.mul(datas[1], 1, 2),
b'\x00\x24\x7f\x80\x7f\x80\xfe')
self.assertEqual(audioop.mul(datas[2], 2, 2),
packs[2](0, 0x2468, 0x7fff, -0x8000, 0x7fff, -0x8000, -2))
self.assertEqual(audioop.mul(datas[3], 3, 2),
packs[3](0, 0x2468ac, 0x7fffff, -0x800000,
0x7fffff, -0x800000, -2))
self.assertEqual(audioop.mul(datas[4], 4, 2),
packs[4](0, 0x2468acf0, 0x7fffffff, -0x80000000,
0x7fffffff, -0x80000000, -2))
def test_ratecv(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.ratecv(b'', w, 1, 8000, 8000, None),
(b'', (-1, ((0, 0),))))
self.assertEqual(audioop.ratecv(bytearray(), w, 1, 8000, 8000, None),
(b'', (-1, ((0, 0),))))
self.assertEqual(audioop.ratecv(memoryview(b''), w, 1, 8000, 8000, None),
(b'', (-1, ((0, 0),))))
self.assertEqual(audioop.ratecv(b'', w, 5, 8000, 8000, None),
(b'', (-1, ((0, 0),) * 5)))
self.assertEqual(audioop.ratecv(b'', w, 1, 8000, 16000, None),
(b'', (-2, ((0, 0),))))
self.assertEqual(audioop.ratecv(datas[w], w, 1, 8000, 8000, None)[0],
datas[w])
self.assertEqual(audioop.ratecv(datas[w], w, 1, 8000, 8000, None, 1, 0)[0],
datas[w])
state = None
d1, state = audioop.ratecv(b'\x00\x01\x02', 1, 1, 8000, 16000, state)
d2, state = audioop.ratecv(b'\x00\x01\x02', 1, 1, 8000, 16000, state)
self.assertEqual(d1 + d2, b'\000\000\001\001\002\001\000\000\001\001\002')
for w in 1, 2, 3, 4:
d0, state0 = audioop.ratecv(datas[w], w, 1, 8000, 16000, None)
d, state = b'', None
for i in range(0, len(datas[w]), w):
d1, state = audioop.ratecv(datas[w][i:i + w], w, 1,
8000, 16000, state)
d += d1
self.assertEqual(d, d0)
self.assertEqual(state, state0)
expected = {
1: packs[1](0, 0x0d, 0x37, -0x26, 0x55, -0x4b, -0x14),
2: packs[2](0, 0x0da7, 0x3777, -0x2630, 0x5673, -0x4a64, -0x129a),
3: packs[3](0, 0x0da740, 0x377776, -0x262fca,
0x56740c, -0x4a62fd, -0x1298c0),
4: packs[4](0, 0x0da740da, 0x37777776, -0x262fc962,
0x56740da6, -0x4a62fc96, -0x1298bf26),
}
for w in 1, 2, 3, 4:
self.assertEqual(audioop.ratecv(datas[w], w, 1, 8000, 8000, None, 3, 1)[0],
expected[w])
self.assertEqual(audioop.ratecv(datas[w], w, 1, 8000, 8000, None, 30, 10)[0],
expected[w])
self.assertRaises(TypeError, audioop.ratecv, b'', 1, 1, 8000, 8000, 42)
self.assertRaises(TypeError, audioop.ratecv,
b'', 1, 1, 8000, 8000, (1, (42,)))
def test_reverse(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.reverse(b'', w), b'')
self.assertEqual(audioop.reverse(bytearray(), w), b'')
self.assertEqual(audioop.reverse(memoryview(b''), w), b'')
self.assertEqual(audioop.reverse(packs[w](0, 1, 2), w),
packs[w](2, 1, 0))
def test_tomono(self):
for w in 1, 2, 3, 4:
data1 = datas[w]
data2 = bytearray(2 * len(data1))
for k in range(w):
data2[k::2*w] = data1[k::w]
self.assertEqual(audioop.tomono(data2, w, 1, 0), data1)
self.assertEqual(audioop.tomono(data2, w, 0, 1), b'\0' * len(data1))
for k in range(w):
data2[k+w::2*w] = data1[k::w]
self.assertEqual(audioop.tomono(data2, w, 0.5, 0.5), data1)
self.assertEqual(audioop.tomono(bytearray(data2), w, 0.5, 0.5),
data1)
self.assertEqual(audioop.tomono(memoryview(data2), w, 0.5, 0.5),
data1)
def test_tostereo(self):
for w in 1, 2, 3, 4:
data1 = datas[w]
data2 = bytearray(2 * len(data1))
for k in range(w):
data2[k::2*w] = data1[k::w]
self.assertEqual(audioop.tostereo(data1, w, 1, 0), data2)
self.assertEqual(audioop.tostereo(data1, w, 0, 0), b'\0' * len(data2))
for k in range(w):
data2[k+w::2*w] = data1[k::w]
self.assertEqual(audioop.tostereo(data1, w, 1, 1), data2)
self.assertEqual(audioop.tostereo(bytearray(data1), w, 1, 1), data2)
self.assertEqual(audioop.tostereo(memoryview(data1), w, 1, 1),
data2)
def test_findfactor(self):
self.assertEqual(audioop.findfactor(datas[2], datas[2]), 1.0)
self.assertEqual(audioop.findfactor(bytearray(datas[2]),
bytearray(datas[2])), 1.0)
self.assertEqual(audioop.findfactor(memoryview(datas[2]),
memoryview(datas[2])), 1.0)
self.assertEqual(audioop.findfactor(b'\0' * len(datas[2]), datas[2]),
0.0)
def test_findfit(self):
self.assertEqual(audioop.findfit(datas[2], datas[2]), (0, 1.0))
self.assertEqual(audioop.findfit(bytearray(datas[2]),
bytearray(datas[2])), (0, 1.0))
self.assertEqual(audioop.findfit(memoryview(datas[2]),
memoryview(datas[2])), (0, 1.0))
self.assertEqual(audioop.findfit(datas[2], packs[2](1, 2, 0)),
(1, 8038.8))
self.assertEqual(audioop.findfit(datas[2][:-2] * 5 + datas[2], datas[2]),
(30, 1.0))
def test_findmax(self):
self.assertEqual(audioop.findmax(datas[2], 1), 5)
self.assertEqual(audioop.findmax(bytearray(datas[2]), 1), 5)
self.assertEqual(audioop.findmax(memoryview(datas[2]), 1), 5)
def test_getsample(self):
for w in 1, 2, 3, 4:
data = packs[w](0, 1, -1, maxvalues[w], minvalues[w])
self.assertEqual(audioop.getsample(data, w, 0), 0)
self.assertEqual(audioop.getsample(bytearray(data), w, 0), 0)
self.assertEqual(audioop.getsample(memoryview(data), w, 0), 0)
self.assertEqual(audioop.getsample(data, w, 1), 1)
self.assertEqual(audioop.getsample(data, w, 2), -1)
self.assertEqual(audioop.getsample(data, w, 3), maxvalues[w])
self.assertEqual(audioop.getsample(data, w, 4), minvalues[w])
def test_byteswap(self):
swapped_datas = {
1: datas[1],
2: packs[2](0, 0x3412, 0x6745, -0x6646, -0x81, 0x80, -1),
3: packs[3](0, 0x563412, -0x7698bb, 0x7798ba, -0x81, 0x80, -1),
4: packs[4](0, 0x78563412, -0x547698bb, 0x557698ba,
-0x81, 0x80, -1),
}
for w in 1, 2, 3, 4:
self.assertEqual(audioop.byteswap(b'', w), b'')
self.assertEqual(audioop.byteswap(datas[w], w), swapped_datas[w])
self.assertEqual(audioop.byteswap(swapped_datas[w], w), datas[w])
self.assertEqual(audioop.byteswap(bytearray(datas[w]), w),
swapped_datas[w])
self.assertEqual(audioop.byteswap(memoryview(datas[w]), w),
swapped_datas[w])
def test_negativelen(self):
# from issue 3306, previously it segfaulted
self.assertRaises(audioop.error,
audioop.findmax, bytes(range(256)), -2392392)
def test_issue7673(self):
state = None
for data, size in INVALID_DATA:
size2 = size
self.assertRaises(audioop.error, audioop.getsample, data, size, 0)
self.assertRaises(audioop.error, audioop.max, data, size)
self.assertRaises(audioop.error, audioop.minmax, data, size)
self.assertRaises(audioop.error, audioop.avg, data, size)
self.assertRaises(audioop.error, audioop.rms, data, size)
self.assertRaises(audioop.error, audioop.avgpp, data, size)
self.assertRaises(audioop.error, audioop.maxpp, data, size)
self.assertRaises(audioop.error, audioop.cross, data, size)
self.assertRaises(audioop.error, audioop.mul, data, size, 1.0)
self.assertRaises(audioop.error, audioop.tomono, data, size, 0.5, 0.5)
self.assertRaises(audioop.error, audioop.tostereo, data, size, 0.5, 0.5)
self.assertRaises(audioop.error, audioop.add, data, data, size)
self.assertRaises(audioop.error, audioop.bias, data, size, 0)
self.assertRaises(audioop.error, audioop.reverse, data, size)
self.assertRaises(audioop.error, audioop.lin2lin, data, size, size2)
self.assertRaises(audioop.error, audioop.ratecv, data, size, 1, 1, 1, state)
self.assertRaises(audioop.error, audioop.lin2ulaw, data, size)
self.assertRaises(audioop.error, audioop.lin2alaw, data, size)
self.assertRaises(audioop.error, audioop.lin2adpcm, data, size, state)
def test_string(self):
data = 'abcd'
size = 2
self.assertRaises(TypeError, audioop.getsample, data, size, 0)
self.assertRaises(TypeError, audioop.max, data, size)
self.assertRaises(TypeError, audioop.minmax, data, size)
self.assertRaises(TypeError, audioop.avg, data, size)
self.assertRaises(TypeError, audioop.rms, data, size)
self.assertRaises(TypeError, audioop.avgpp, data, size)
self.assertRaises(TypeError, audioop.maxpp, data, size)
self.assertRaises(TypeError, audioop.cross, data, size)
self.assertRaises(TypeError, audioop.mul, data, size, 1.0)
self.assertRaises(TypeError, audioop.tomono, data, size, 0.5, 0.5)
self.assertRaises(TypeError, audioop.tostereo, data, size, 0.5, 0.5)
self.assertRaises(TypeError, audioop.add, data, data, size)
self.assertRaises(TypeError, audioop.bias, data, size, 0)
self.assertRaises(TypeError, audioop.reverse, data, size)
self.assertRaises(TypeError, audioop.lin2lin, data, size, size)
self.assertRaises(TypeError, audioop.ratecv, data, size, 1, 1, 1, None)
self.assertRaises(TypeError, audioop.lin2ulaw, data, size)
self.assertRaises(TypeError, audioop.lin2alaw, data, size)
self.assertRaises(TypeError, audioop.lin2adpcm, data, size, None)
def test_wrongsize(self):
data = b'abcdefgh'
state = None
for size in (-1, 0, 5, 1024):
self.assertRaises(audioop.error, audioop.ulaw2lin, data, size)
self.assertRaises(audioop.error, audioop.alaw2lin, data, size)
self.assertRaises(audioop.error, audioop.adpcm2lin, data, size, state)
if __name__ == '__main__':
unittest.main()
| 28,977 | 567 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/EUC-JP.TXT | 00 0000
01 0001
02 0002
03 0003
04 0004
05 0005
06 0006
07 0007
08 0008
09 0009
0A 000A
0B 000B
0C 000C
0D 000D
0E 000E
0F 000F
10 0010
11 0011
12 0012
13 0013
14 0014
15 0015
16 0016
17 0017
18 0018
19 0019
1A 001A
1B 001B
1C 001C
1D 001D
1E 001E
1F 001F
20 0020
21 0021
22 0022
23 0023
24 0024
25 0025
26 0026
27 0027
28 0028
29 0029
2A 002A
2B 002B
2C 002C
2D 002D
2E 002E
2F 002F
30 0030
31 0031
32 0032
33 0033
34 0034
35 0035
36 0036
37 0037
38 0038
39 0039
3A 003A
3B 003B
3C 003C
3D 003D
3E 003E
3F 003F
40 0040
41 0041
42 0042
43 0043
44 0044
45 0045
46 0046
47 0047
48 0048
49 0049
4A 004A
4B 004B
4C 004C
4D 004D
4E 004E
4F 004F
50 0050
51 0051
52 0052
53 0053
54 0054
55 0055
56 0056
57 0057
58 0058
59 0059
5A 005A
5B 005B
5C 005C
5D 005D
5E 005E
5F 005F
60 0060
61 0061
62 0062
63 0063
64 0064
65 0065
66 0066
67 0067
68 0068
69 0069
6A 006A
6B 006B
6C 006C
6D 006D
6E 006E
6F 006F
70 0070
71 0071
72 0072
73 0073
74 0074
75 0075
76 0076
77 0077
78 0078
79 0079
7A 007A
7B 007B
7C 007C
7D 007D
7E 007E
7F 007F
8EA1 FF61
8EA2 FF62
8EA3 FF63
8EA4 FF64
8EA5 FF65
8EA6 FF66
8EA7 FF67
8EA8 FF68
8EA9 FF69
8EAA FF6A
8EAB FF6B
8EAC FF6C
8EAD FF6D
8EAE FF6E
8EAF FF6F
8EB0 FF70
8EB1 FF71
8EB2 FF72
8EB3 FF73
8EB4 FF74
8EB5 FF75
8EB6 FF76
8EB7 FF77
8EB8 FF78
8EB9 FF79
8EBA FF7A
8EBB FF7B
8EBC FF7C
8EBD FF7D
8EBE FF7E
8EBF FF7F
8EC0 FF80
8EC1 FF81
8EC2 FF82
8EC3 FF83
8EC4 FF84
8EC5 FF85
8EC6 FF86
8EC7 FF87
8EC8 FF88
8EC9 FF89
8ECA FF8A
8ECB FF8B
8ECC FF8C
8ECD FF8D
8ECE FF8E
8ECF FF8F
8ED0 FF90
8ED1 FF91
8ED2 FF92
8ED3 FF93
8ED4 FF94
8ED5 FF95
8ED6 FF96
8ED7 FF97
8ED8 FF98
8ED9 FF99
8EDA FF9A
8EDB FF9B
8EDC FF9C
8EDD FF9D
8EDE FF9E
8EDF FF9F
8FA2AF 02D8
8FA2B0 02C7
8FA2B1 00B8
8FA2B2 02D9
8FA2B3 02DD
8FA2B4 00AF
8FA2B5 02DB
8FA2B6 02DA
8FA2B8 0384
8FA2B9 0385
8FA2C2 00A1
8FA2C3 00A6
8FA2C4 00BF
8FA2EB 00BA
8FA2EC 00AA
8FA2ED 00A9
8FA2EE 00AE
8FA2EF 2122
8FA2F0 00A4
8FA2F1 2116
8FA6E1 0386
8FA6E2 0388
8FA6E3 0389
8FA6E4 038A
8FA6E5 03AA
8FA6E7 038C
8FA6E9 038E
8FA6EA 03AB
8FA6EC 038F
8FA6F1 03AC
8FA6F2 03AD
8FA6F3 03AE
8FA6F4 03AF
8FA6F5 03CA
8FA6F6 0390
8FA6F7 03CC
8FA6F8 03C2
8FA6F9 03CD
8FA6FA 03CB
8FA6FB 03B0
8FA6FC 03CE
8FA7C2 0402
8FA7C3 0403
8FA7C4 0404
8FA7C5 0405
8FA7C6 0406
8FA7C7 0407
8FA7C8 0408
8FA7C9 0409
8FA7CA 040A
8FA7CB 040B
8FA7CC 040C
8FA7CD 040E
8FA7CE 040F
8FA7F2 0452
8FA7F3 0453
8FA7F4 0454
8FA7F5 0455
8FA7F6 0456
8FA7F7 0457
8FA7F8 0458
8FA7F9 0459
8FA7FA 045A
8FA7FB 045B
8FA7FC 045C
8FA7FD 045E
8FA7FE 045F
8FA9A1 00C6
8FA9A2 0110
8FA9A4 0126
8FA9A6 0132
8FA9A8 0141
8FA9A9 013F
8FA9AB 014A
8FA9AC 00D8
8FA9AD 0152
8FA9AF 0166
8FA9B0 00DE
8FA9C1 00E6
8FA9C2 0111
8FA9C3 00F0
8FA9C4 0127
8FA9C5 0131
8FA9C6 0133
8FA9C7 0138
8FA9C8 0142
8FA9C9 0140
8FA9CA 0149
8FA9CB 014B
8FA9CC 00F8
8FA9CD 0153
8FA9CE 00DF
8FA9CF 0167
8FA9D0 00FE
8FAAA1 00C1
8FAAA2 00C0
8FAAA3 00C4
8FAAA4 00C2
8FAAA5 0102
8FAAA6 01CD
8FAAA7 0100
8FAAA8 0104
8FAAA9 00C5
8FAAAA 00C3
8FAAAB 0106
8FAAAC 0108
8FAAAD 010C
8FAAAE 00C7
8FAAAF 010A
8FAAB0 010E
8FAAB1 00C9
8FAAB2 00C8
8FAAB3 00CB
8FAAB4 00CA
8FAAB5 011A
8FAAB6 0116
8FAAB7 0112
8FAAB8 0118
8FAABA 011C
8FAABB 011E
8FAABC 0122
8FAABD 0120
8FAABE 0124
8FAABF 00CD
8FAAC0 00CC
8FAAC1 00CF
8FAAC2 00CE
8FAAC3 01CF
8FAAC4 0130
8FAAC5 012A
8FAAC6 012E
8FAAC7 0128
8FAAC8 0134
8FAAC9 0136
8FAACA 0139
8FAACB 013D
8FAACC 013B
8FAACD 0143
8FAACE 0147
8FAACF 0145
8FAAD0 00D1
8FAAD1 00D3
8FAAD2 00D2
8FAAD3 00D6
8FAAD4 00D4
8FAAD5 01D1
8FAAD6 0150
8FAAD7 014C
8FAAD8 00D5
8FAAD9 0154
8FAADA 0158
8FAADB 0156
8FAADC 015A
8FAADD 015C
8FAADE 0160
8FAADF 015E
8FAAE0 0164
8FAAE1 0162
8FAAE2 00DA
8FAAE3 00D9
8FAAE4 00DC
8FAAE5 00DB
8FAAE6 016C
8FAAE7 01D3
8FAAE8 0170
8FAAE9 016A
8FAAEA 0172
8FAAEB 016E
8FAAEC 0168
8FAAED 01D7
8FAAEE 01DB
8FAAEF 01D9
8FAAF0 01D5
8FAAF1 0174
8FAAF2 00DD
8FAAF3 0178
8FAAF4 0176
8FAAF5 0179
8FAAF6 017D
8FAAF7 017B
8FABA1 00E1
8FABA2 00E0
8FABA3 00E4
8FABA4 00E2
8FABA5 0103
8FABA6 01CE
8FABA7 0101
8FABA8 0105
8FABA9 00E5
8FABAA 00E3
8FABAB 0107
8FABAC 0109
8FABAD 010D
8FABAE 00E7
8FABAF 010B
8FABB0 010F
8FABB1 00E9
8FABB2 00E8
8FABB3 00EB
8FABB4 00EA
8FABB5 011B
8FABB6 0117
8FABB7 0113
8FABB8 0119
8FABB9 01F5
8FABBA 011D
8FABBB 011F
8FABBD 0121
8FABBE 0125
8FABBF 00ED
8FABC0 00EC
8FABC1 00EF
8FABC2 00EE
8FABC3 01D0
8FABC5 012B
8FABC6 012F
8FABC7 0129
8FABC8 0135
8FABC9 0137
8FABCA 013A
8FABCB 013E
8FABCC 013C
8FABCD 0144
8FABCE 0148
8FABCF 0146
8FABD0 00F1
8FABD1 00F3
8FABD2 00F2
8FABD3 00F6
8FABD4 00F4
8FABD5 01D2
8FABD6 0151
8FABD7 014D
8FABD8 00F5
8FABD9 0155
8FABDA 0159
8FABDB 0157
8FABDC 015B
8FABDD 015D
8FABDE 0161
8FABDF 015F
8FABE0 0165
8FABE1 0163
8FABE2 00FA
8FABE3 00F9
8FABE4 00FC
8FABE5 00FB
8FABE6 016D
8FABE7 01D4
8FABE8 0171
8FABE9 016B
8FABEA 0173
8FABEB 016F
8FABEC 0169
8FABED 01D8
8FABEE 01DC
8FABEF 01DA
8FABF0 01D6
8FABF1 0175
8FABF2 00FD
8FABF3 00FF
8FABF4 0177
8FABF5 017A
8FABF6 017E
8FABF7 017C
8FB0A1 4E02
8FB0A2 4E04
8FB0A3 4E05
8FB0A4 4E0C
8FB0A5 4E12
8FB0A6 4E1F
8FB0A7 4E23
8FB0A8 4E24
8FB0A9 4E28
8FB0AA 4E2B
8FB0AB 4E2E
8FB0AC 4E2F
8FB0AD 4E30
8FB0AE 4E35
8FB0AF 4E40
8FB0B0 4E41
8FB0B1 4E44
8FB0B2 4E47
8FB0B3 4E51
8FB0B4 4E5A
8FB0B5 4E5C
8FB0B6 4E63
8FB0B7 4E68
8FB0B8 4E69
8FB0B9 4E74
8FB0BA 4E75
8FB0BB 4E79
8FB0BC 4E7F
8FB0BD 4E8D
8FB0BE 4E96
8FB0BF 4E97
8FB0C0 4E9D
8FB0C1 4EAF
8FB0C2 4EB9
8FB0C3 4EC3
8FB0C4 4ED0
8FB0C5 4EDA
8FB0C6 4EDB
8FB0C7 4EE0
8FB0C8 4EE1
8FB0C9 4EE2
8FB0CA 4EE8
8FB0CB 4EEF
8FB0CC 4EF1
8FB0CD 4EF3
8FB0CE 4EF5
8FB0CF 4EFD
8FB0D0 4EFE
8FB0D1 4EFF
8FB0D2 4F00
8FB0D3 4F02
8FB0D4 4F03
8FB0D5 4F08
8FB0D6 4F0B
8FB0D7 4F0C
8FB0D8 4F12
8FB0D9 4F15
8FB0DA 4F16
8FB0DB 4F17
8FB0DC 4F19
8FB0DD 4F2E
8FB0DE 4F31
8FB0DF 4F60
8FB0E0 4F33
8FB0E1 4F35
8FB0E2 4F37
8FB0E3 4F39
8FB0E4 4F3B
8FB0E5 4F3E
8FB0E6 4F40
8FB0E7 4F42
8FB0E8 4F48
8FB0E9 4F49
8FB0EA 4F4B
8FB0EB 4F4C
8FB0EC 4F52
8FB0ED 4F54
8FB0EE 4F56
8FB0EF 4F58
8FB0F0 4F5F
8FB0F1 4F63
8FB0F2 4F6A
8FB0F3 4F6C
8FB0F4 4F6E
8FB0F5 4F71
8FB0F6 4F77
8FB0F7 4F78
8FB0F8 4F79
8FB0F9 4F7A
8FB0FA 4F7D
8FB0FB 4F7E
8FB0FC 4F81
8FB0FD 4F82
8FB0FE 4F84
8FB1A1 4F85
8FB1A2 4F89
8FB1A3 4F8A
8FB1A4 4F8C
8FB1A5 4F8E
8FB1A6 4F90
8FB1A7 4F92
8FB1A8 4F93
8FB1A9 4F94
8FB1AA 4F97
8FB1AB 4F99
8FB1AC 4F9A
8FB1AD 4F9E
8FB1AE 4F9F
8FB1AF 4FB2
8FB1B0 4FB7
8FB1B1 4FB9
8FB1B2 4FBB
8FB1B3 4FBC
8FB1B4 4FBD
8FB1B5 4FBE
8FB1B6 4FC0
8FB1B7 4FC1
8FB1B8 4FC5
8FB1B9 4FC6
8FB1BA 4FC8
8FB1BB 4FC9
8FB1BC 4FCB
8FB1BD 4FCC
8FB1BE 4FCD
8FB1BF 4FCF
8FB1C0 4FD2
8FB1C1 4FDC
8FB1C2 4FE0
8FB1C3 4FE2
8FB1C4 4FF0
8FB1C5 4FF2
8FB1C6 4FFC
8FB1C7 4FFD
8FB1C8 4FFF
8FB1C9 5000
8FB1CA 5001
8FB1CB 5004
8FB1CC 5007
8FB1CD 500A
8FB1CE 500C
8FB1CF 500E
8FB1D0 5010
8FB1D1 5013
8FB1D2 5017
8FB1D3 5018
8FB1D4 501B
8FB1D5 501C
8FB1D6 501D
8FB1D7 501E
8FB1D8 5022
8FB1D9 5027
8FB1DA 502E
8FB1DB 5030
8FB1DC 5032
8FB1DD 5033
8FB1DE 5035
8FB1DF 5040
8FB1E0 5041
8FB1E1 5042
8FB1E2 5045
8FB1E3 5046
8FB1E4 504A
8FB1E5 504C
8FB1E6 504E
8FB1E7 5051
8FB1E8 5052
8FB1E9 5053
8FB1EA 5057
8FB1EB 5059
8FB1EC 505F
8FB1ED 5060
8FB1EE 5062
8FB1EF 5063
8FB1F0 5066
8FB1F1 5067
8FB1F2 506A
8FB1F3 506D
8FB1F4 5070
8FB1F5 5071
8FB1F6 503B
8FB1F7 5081
8FB1F8 5083
8FB1F9 5084
8FB1FA 5086
8FB1FB 508A
8FB1FC 508E
8FB1FD 508F
8FB1FE 5090
8FB2A1 5092
8FB2A2 5093
8FB2A3 5094
8FB2A4 5096
8FB2A5 509B
8FB2A6 509C
8FB2A7 509E
8FB2A8 509F
8FB2A9 50A0
8FB2AA 50A1
8FB2AB 50A2
8FB2AC 50AA
8FB2AD 50AF
8FB2AE 50B0
8FB2AF 50B9
8FB2B0 50BA
8FB2B1 50BD
8FB2B2 50C0
8FB2B3 50C3
8FB2B4 50C4
8FB2B5 50C7
8FB2B6 50CC
8FB2B7 50CE
8FB2B8 50D0
8FB2B9 50D3
8FB2BA 50D4
8FB2BB 50D8
8FB2BC 50DC
8FB2BD 50DD
8FB2BE 50DF
8FB2BF 50E2
8FB2C0 50E4
8FB2C1 50E6
8FB2C2 50E8
8FB2C3 50E9
8FB2C4 50EF
8FB2C5 50F1
8FB2C6 50F6
8FB2C7 50FA
8FB2C8 50FE
8FB2C9 5103
8FB2CA 5106
8FB2CB 5107
8FB2CC 5108
8FB2CD 510B
8FB2CE 510C
8FB2CF 510D
8FB2D0 510E
8FB2D1 50F2
8FB2D2 5110
8FB2D3 5117
8FB2D4 5119
8FB2D5 511B
8FB2D6 511C
8FB2D7 511D
8FB2D8 511E
8FB2D9 5123
8FB2DA 5127
8FB2DB 5128
8FB2DC 512C
8FB2DD 512D
8FB2DE 512F
8FB2DF 5131
8FB2E0 5133
8FB2E1 5134
8FB2E2 5135
8FB2E3 5138
8FB2E4 5139
8FB2E5 5142
8FB2E6 514A
8FB2E7 514F
8FB2E8 5153
8FB2E9 5155
8FB2EA 5157
8FB2EB 5158
8FB2EC 515F
8FB2ED 5164
8FB2EE 5166
8FB2EF 517E
8FB2F0 5183
8FB2F1 5184
8FB2F2 518B
8FB2F3 518E
8FB2F4 5198
8FB2F5 519D
8FB2F6 51A1
8FB2F7 51A3
8FB2F8 51AD
8FB2F9 51B8
8FB2FA 51BA
8FB2FB 51BC
8FB2FC 51BE
8FB2FD 51BF
8FB2FE 51C2
8FB3A1 51C8
8FB3A2 51CF
8FB3A3 51D1
8FB3A4 51D2
8FB3A5 51D3
8FB3A6 51D5
8FB3A7 51D8
8FB3A8 51DE
8FB3A9 51E2
8FB3AA 51E5
8FB3AB 51EE
8FB3AC 51F2
8FB3AD 51F3
8FB3AE 51F4
8FB3AF 51F7
8FB3B0 5201
8FB3B1 5202
8FB3B2 5205
8FB3B3 5212
8FB3B4 5213
8FB3B5 5215
8FB3B6 5216
8FB3B7 5218
8FB3B8 5222
8FB3B9 5228
8FB3BA 5231
8FB3BB 5232
8FB3BC 5235
8FB3BD 523C
8FB3BE 5245
8FB3BF 5249
8FB3C0 5255
8FB3C1 5257
8FB3C2 5258
8FB3C3 525A
8FB3C4 525C
8FB3C5 525F
8FB3C6 5260
8FB3C7 5261
8FB3C8 5266
8FB3C9 526E
8FB3CA 5277
8FB3CB 5278
8FB3CC 5279
8FB3CD 5280
8FB3CE 5282
8FB3CF 5285
8FB3D0 528A
8FB3D1 528C
8FB3D2 5293
8FB3D3 5295
8FB3D4 5296
8FB3D5 5297
8FB3D6 5298
8FB3D7 529A
8FB3D8 529C
8FB3D9 52A4
8FB3DA 52A5
8FB3DB 52A6
8FB3DC 52A7
8FB3DD 52AF
8FB3DE 52B0
8FB3DF 52B6
8FB3E0 52B7
8FB3E1 52B8
8FB3E2 52BA
8FB3E3 52BB
8FB3E4 52BD
8FB3E5 52C0
8FB3E6 52C4
8FB3E7 52C6
8FB3E8 52C8
8FB3E9 52CC
8FB3EA 52CF
8FB3EB 52D1
8FB3EC 52D4
8FB3ED 52D6
8FB3EE 52DB
8FB3EF 52DC
8FB3F0 52E1
8FB3F1 52E5
8FB3F2 52E8
8FB3F3 52E9
8FB3F4 52EA
8FB3F5 52EC
8FB3F6 52F0
8FB3F7 52F1
8FB3F8 52F4
8FB3F9 52F6
8FB3FA 52F7
8FB3FB 5300
8FB3FC 5303
8FB3FD 530A
8FB3FE 530B
8FB4A1 530C
8FB4A2 5311
8FB4A3 5313
8FB4A4 5318
8FB4A5 531B
8FB4A6 531C
8FB4A7 531E
8FB4A8 531F
8FB4A9 5325
8FB4AA 5327
8FB4AB 5328
8FB4AC 5329
8FB4AD 532B
8FB4AE 532C
8FB4AF 532D
8FB4B0 5330
8FB4B1 5332
8FB4B2 5335
8FB4B3 533C
8FB4B4 533D
8FB4B5 533E
8FB4B6 5342
8FB4B7 534C
8FB4B8 534B
8FB4B9 5359
8FB4BA 535B
8FB4BB 5361
8FB4BC 5363
8FB4BD 5365
8FB4BE 536C
8FB4BF 536D
8FB4C0 5372
8FB4C1 5379
8FB4C2 537E
8FB4C3 5383
8FB4C4 5387
8FB4C5 5388
8FB4C6 538E
8FB4C7 5393
8FB4C8 5394
8FB4C9 5399
8FB4CA 539D
8FB4CB 53A1
8FB4CC 53A4
8FB4CD 53AA
8FB4CE 53AB
8FB4CF 53AF
8FB4D0 53B2
8FB4D1 53B4
8FB4D2 53B5
8FB4D3 53B7
8FB4D4 53B8
8FB4D5 53BA
8FB4D6 53BD
8FB4D7 53C0
8FB4D8 53C5
8FB4D9 53CF
8FB4DA 53D2
8FB4DB 53D3
8FB4DC 53D5
8FB4DD 53DA
8FB4DE 53DD
8FB4DF 53DE
8FB4E0 53E0
8FB4E1 53E6
8FB4E2 53E7
8FB4E3 53F5
8FB4E4 5402
8FB4E5 5413
8FB4E6 541A
8FB4E7 5421
8FB4E8 5427
8FB4E9 5428
8FB4EA 542A
8FB4EB 542F
8FB4EC 5431
8FB4ED 5434
8FB4EE 5435
8FB4EF 5443
8FB4F0 5444
8FB4F1 5447
8FB4F2 544D
8FB4F3 544F
8FB4F4 545E
8FB4F5 5462
8FB4F6 5464
8FB4F7 5466
8FB4F8 5467
8FB4F9 5469
8FB4FA 546B
8FB4FB 546D
8FB4FC 546E
8FB4FD 5474
8FB4FE 547F
8FB5A1 5481
8FB5A2 5483
8FB5A3 5485
8FB5A4 5488
8FB5A5 5489
8FB5A6 548D
8FB5A7 5491
8FB5A8 5495
8FB5A9 5496
8FB5AA 549C
8FB5AB 549F
8FB5AC 54A1
8FB5AD 54A6
8FB5AE 54A7
8FB5AF 54A9
8FB5B0 54AA
8FB5B1 54AD
8FB5B2 54AE
8FB5B3 54B1
8FB5B4 54B7
8FB5B5 54B9
8FB5B6 54BA
8FB5B7 54BB
8FB5B8 54BF
8FB5B9 54C6
8FB5BA 54CA
8FB5BB 54CD
8FB5BC 54CE
8FB5BD 54E0
8FB5BE 54EA
8FB5BF 54EC
8FB5C0 54EF
8FB5C1 54F6
8FB5C2 54FC
8FB5C3 54FE
8FB5C4 54FF
8FB5C5 5500
8FB5C6 5501
8FB5C7 5505
8FB5C8 5508
8FB5C9 5509
8FB5CA 550C
8FB5CB 550D
8FB5CC 550E
8FB5CD 5515
8FB5CE 552A
8FB5CF 552B
8FB5D0 5532
8FB5D1 5535
8FB5D2 5536
8FB5D3 553B
8FB5D4 553C
8FB5D5 553D
8FB5D6 5541
8FB5D7 5547
8FB5D8 5549
8FB5D9 554A
8FB5DA 554D
8FB5DB 5550
8FB5DC 5551
8FB5DD 5558
8FB5DE 555A
8FB5DF 555B
8FB5E0 555E
8FB5E1 5560
8FB5E2 5561
8FB5E3 5564
8FB5E4 5566
8FB5E5 557F
8FB5E6 5581
8FB5E7 5582
8FB5E8 5586
8FB5E9 5588
8FB5EA 558E
8FB5EB 558F
8FB5EC 5591
8FB5ED 5592
8FB5EE 5593
8FB5EF 5594
8FB5F0 5597
8FB5F1 55A3
8FB5F2 55A4
8FB5F3 55AD
8FB5F4 55B2
8FB5F5 55BF
8FB5F6 55C1
8FB5F7 55C3
8FB5F8 55C6
8FB5F9 55C9
8FB5FA 55CB
8FB5FB 55CC
8FB5FC 55CE
8FB5FD 55D1
8FB5FE 55D2
8FB6A1 55D3
8FB6A2 55D7
8FB6A3 55D8
8FB6A4 55DB
8FB6A5 55DE
8FB6A6 55E2
8FB6A7 55E9
8FB6A8 55F6
8FB6A9 55FF
8FB6AA 5605
8FB6AB 5608
8FB6AC 560A
8FB6AD 560D
8FB6AE 560E
8FB6AF 560F
8FB6B0 5610
8FB6B1 5611
8FB6B2 5612
8FB6B3 5619
8FB6B4 562C
8FB6B5 5630
8FB6B6 5633
8FB6B7 5635
8FB6B8 5637
8FB6B9 5639
8FB6BA 563B
8FB6BB 563C
8FB6BC 563D
8FB6BD 563F
8FB6BE 5640
8FB6BF 5641
8FB6C0 5643
8FB6C1 5644
8FB6C2 5646
8FB6C3 5649
8FB6C4 564B
8FB6C5 564D
8FB6C6 564F
8FB6C7 5654
8FB6C8 565E
8FB6C9 5660
8FB6CA 5661
8FB6CB 5662
8FB6CC 5663
8FB6CD 5666
8FB6CE 5669
8FB6CF 566D
8FB6D0 566F
8FB6D1 5671
8FB6D2 5672
8FB6D3 5675
8FB6D4 5684
8FB6D5 5685
8FB6D6 5688
8FB6D7 568B
8FB6D8 568C
8FB6D9 5695
8FB6DA 5699
8FB6DB 569A
8FB6DC 569D
8FB6DD 569E
8FB6DE 569F
8FB6DF 56A6
8FB6E0 56A7
8FB6E1 56A8
8FB6E2 56A9
8FB6E3 56AB
8FB6E4 56AC
8FB6E5 56AD
8FB6E6 56B1
8FB6E7 56B3
8FB6E8 56B7
8FB6E9 56BE
8FB6EA 56C5
8FB6EB 56C9
8FB6EC 56CA
8FB6ED 56CB
8FB6EE 56CF
8FB6EF 56D0
8FB6F0 56CC
8FB6F1 56CD
8FB6F2 56D9
8FB6F3 56DC
8FB6F4 56DD
8FB6F5 56DF
8FB6F6 56E1
8FB6F7 56E4
8FB6F8 56E5
8FB6F9 56E6
8FB6FA 56E7
8FB6FB 56E8
8FB6FC 56F1
8FB6FD 56EB
8FB6FE 56ED
8FB7A1 56F6
8FB7A2 56F7
8FB7A3 5701
8FB7A4 5702
8FB7A5 5707
8FB7A6 570A
8FB7A7 570C
8FB7A8 5711
8FB7A9 5715
8FB7AA 571A
8FB7AB 571B
8FB7AC 571D
8FB7AD 5720
8FB7AE 5722
8FB7AF 5723
8FB7B0 5724
8FB7B1 5725
8FB7B2 5729
8FB7B3 572A
8FB7B4 572C
8FB7B5 572E
8FB7B6 572F
8FB7B7 5733
8FB7B8 5734
8FB7B9 573D
8FB7BA 573E
8FB7BB 573F
8FB7BC 5745
8FB7BD 5746
8FB7BE 574C
8FB7BF 574D
8FB7C0 5752
8FB7C1 5762
8FB7C2 5765
8FB7C3 5767
8FB7C4 5768
8FB7C5 576B
8FB7C6 576D
8FB7C7 576E
8FB7C8 576F
8FB7C9 5770
8FB7CA 5771
8FB7CB 5773
8FB7CC 5774
8FB7CD 5775
8FB7CE 5777
8FB7CF 5779
8FB7D0 577A
8FB7D1 577B
8FB7D2 577C
8FB7D3 577E
8FB7D4 5781
8FB7D5 5783
8FB7D6 578C
8FB7D7 5794
8FB7D8 5797
8FB7D9 5799
8FB7DA 579A
8FB7DB 579C
8FB7DC 579D
8FB7DD 579E
8FB7DE 579F
8FB7DF 57A1
8FB7E0 5795
8FB7E1 57A7
8FB7E2 57A8
8FB7E3 57A9
8FB7E4 57AC
8FB7E5 57B8
8FB7E6 57BD
8FB7E7 57C7
8FB7E8 57C8
8FB7E9 57CC
8FB7EA 57CF
8FB7EB 57D5
8FB7EC 57DD
8FB7ED 57DE
8FB7EE 57E4
8FB7EF 57E6
8FB7F0 57E7
8FB7F1 57E9
8FB7F2 57ED
8FB7F3 57F0
8FB7F4 57F5
8FB7F5 57F6
8FB7F6 57F8
8FB7F7 57FD
8FB7F8 57FE
8FB7F9 57FF
8FB7FA 5803
8FB7FB 5804
8FB7FC 5808
8FB7FD 5809
8FB7FE 57E1
8FB8A1 580C
8FB8A2 580D
8FB8A3 581B
8FB8A4 581E
8FB8A5 581F
8FB8A6 5820
8FB8A7 5826
8FB8A8 5827
8FB8A9 582D
8FB8AA 5832
8FB8AB 5839
8FB8AC 583F
8FB8AD 5849
8FB8AE 584C
8FB8AF 584D
8FB8B0 584F
8FB8B1 5850
8FB8B2 5855
8FB8B3 585F
8FB8B4 5861
8FB8B5 5864
8FB8B6 5867
8FB8B7 5868
8FB8B8 5878
8FB8B9 587C
8FB8BA 587F
8FB8BB 5880
8FB8BC 5881
8FB8BD 5887
8FB8BE 5888
8FB8BF 5889
8FB8C0 588A
8FB8C1 588C
8FB8C2 588D
8FB8C3 588F
8FB8C4 5890
8FB8C5 5894
8FB8C6 5896
8FB8C7 589D
8FB8C8 58A0
8FB8C9 58A1
8FB8CA 58A2
8FB8CB 58A6
8FB8CC 58A9
8FB8CD 58B1
8FB8CE 58B2
8FB8CF 58C4
8FB8D0 58BC
8FB8D1 58C2
8FB8D2 58C8
8FB8D3 58CD
8FB8D4 58CE
8FB8D5 58D0
8FB8D6 58D2
8FB8D7 58D4
8FB8D8 58D6
8FB8D9 58DA
8FB8DA 58DD
8FB8DB 58E1
8FB8DC 58E2
8FB8DD 58E9
8FB8DE 58F3
8FB8DF 5905
8FB8E0 5906
8FB8E1 590B
8FB8E2 590C
8FB8E3 5912
8FB8E4 5913
8FB8E5 5914
8FB8E6 8641
8FB8E7 591D
8FB8E8 5921
8FB8E9 5923
8FB8EA 5924
8FB8EB 5928
8FB8EC 592F
8FB8ED 5930
8FB8EE 5933
8FB8EF 5935
8FB8F0 5936
8FB8F1 593F
8FB8F2 5943
8FB8F3 5946
8FB8F4 5952
8FB8F5 5953
8FB8F6 5959
8FB8F7 595B
8FB8F8 595D
8FB8F9 595E
8FB8FA 595F
8FB8FB 5961
8FB8FC 5963
8FB8FD 596B
8FB8FE 596D
8FB9A1 596F
8FB9A2 5972
8FB9A3 5975
8FB9A4 5976
8FB9A5 5979
8FB9A6 597B
8FB9A7 597C
8FB9A8 598B
8FB9A9 598C
8FB9AA 598E
8FB9AB 5992
8FB9AC 5995
8FB9AD 5997
8FB9AE 599F
8FB9AF 59A4
8FB9B0 59A7
8FB9B1 59AD
8FB9B2 59AE
8FB9B3 59AF
8FB9B4 59B0
8FB9B5 59B3
8FB9B6 59B7
8FB9B7 59BA
8FB9B8 59BC
8FB9B9 59C1
8FB9BA 59C3
8FB9BB 59C4
8FB9BC 59C8
8FB9BD 59CA
8FB9BE 59CD
8FB9BF 59D2
8FB9C0 59DD
8FB9C1 59DE
8FB9C2 59DF
8FB9C3 59E3
8FB9C4 59E4
8FB9C5 59E7
8FB9C6 59EE
8FB9C7 59EF
8FB9C8 59F1
8FB9C9 59F2
8FB9CA 59F4
8FB9CB 59F7
8FB9CC 5A00
8FB9CD 5A04
8FB9CE 5A0C
8FB9CF 5A0D
8FB9D0 5A0E
8FB9D1 5A12
8FB9D2 5A13
8FB9D3 5A1E
8FB9D4 5A23
8FB9D5 5A24
8FB9D6 5A27
8FB9D7 5A28
8FB9D8 5A2A
8FB9D9 5A2D
8FB9DA 5A30
8FB9DB 5A44
8FB9DC 5A45
8FB9DD 5A47
8FB9DE 5A48
8FB9DF 5A4C
8FB9E0 5A50
8FB9E1 5A55
8FB9E2 5A5E
8FB9E3 5A63
8FB9E4 5A65
8FB9E5 5A67
8FB9E6 5A6D
8FB9E7 5A77
8FB9E8 5A7A
8FB9E9 5A7B
8FB9EA 5A7E
8FB9EB 5A8B
8FB9EC 5A90
8FB9ED 5A93
8FB9EE 5A96
8FB9EF 5A99
8FB9F0 5A9C
8FB9F1 5A9E
8FB9F2 5A9F
8FB9F3 5AA0
8FB9F4 5AA2
8FB9F5 5AA7
8FB9F6 5AAC
8FB9F7 5AB1
8FB9F8 5AB2
8FB9F9 5AB3
8FB9FA 5AB5
8FB9FB 5AB8
8FB9FC 5ABA
8FB9FD 5ABB
8FB9FE 5ABF
8FBAA1 5AC4
8FBAA2 5AC6
8FBAA3 5AC8
8FBAA4 5ACF
8FBAA5 5ADA
8FBAA6 5ADC
8FBAA7 5AE0
8FBAA8 5AE5
8FBAA9 5AEA
8FBAAA 5AEE
8FBAAB 5AF5
8FBAAC 5AF6
8FBAAD 5AFD
8FBAAE 5B00
8FBAAF 5B01
8FBAB0 5B08
8FBAB1 5B17
8FBAB2 5B34
8FBAB3 5B19
8FBAB4 5B1B
8FBAB5 5B1D
8FBAB6 5B21
8FBAB7 5B25
8FBAB8 5B2D
8FBAB9 5B38
8FBABA 5B41
8FBABB 5B4B
8FBABC 5B4C
8FBABD 5B52
8FBABE 5B56
8FBABF 5B5E
8FBAC0 5B68
8FBAC1 5B6E
8FBAC2 5B6F
8FBAC3 5B7C
8FBAC4 5B7D
8FBAC5 5B7E
8FBAC6 5B7F
8FBAC7 5B81
8FBAC8 5B84
8FBAC9 5B86
8FBACA 5B8A
8FBACB 5B8E
8FBACC 5B90
8FBACD 5B91
8FBACE 5B93
8FBACF 5B94
8FBAD0 5B96
8FBAD1 5BA8
8FBAD2 5BA9
8FBAD3 5BAC
8FBAD4 5BAD
8FBAD5 5BAF
8FBAD6 5BB1
8FBAD7 5BB2
8FBAD8 5BB7
8FBAD9 5BBA
8FBADA 5BBC
8FBADB 5BC0
8FBADC 5BC1
8FBADD 5BCD
8FBADE 5BCF
8FBADF 5BD6
8FBAE0 5BD7
8FBAE1 5BD8
8FBAE2 5BD9
8FBAE3 5BDA
8FBAE4 5BE0
8FBAE5 5BEF
8FBAE6 5BF1
8FBAE7 5BF4
8FBAE8 5BFD
8FBAE9 5C0C
8FBAEA 5C17
8FBAEB 5C1E
8FBAEC 5C1F
8FBAED 5C23
8FBAEE 5C26
8FBAEF 5C29
8FBAF0 5C2B
8FBAF1 5C2C
8FBAF2 5C2E
8FBAF3 5C30
8FBAF4 5C32
8FBAF5 5C35
8FBAF6 5C36
8FBAF7 5C59
8FBAF8 5C5A
8FBAF9 5C5C
8FBAFA 5C62
8FBAFB 5C63
8FBAFC 5C67
8FBAFD 5C68
8FBAFE 5C69
8FBBA1 5C6D
8FBBA2 5C70
8FBBA3 5C74
8FBBA4 5C75
8FBBA5 5C7A
8FBBA6 5C7B
8FBBA7 5C7C
8FBBA8 5C7D
8FBBA9 5C87
8FBBAA 5C88
8FBBAB 5C8A
8FBBAC 5C8F
8FBBAD 5C92
8FBBAE 5C9D
8FBBAF 5C9F
8FBBB0 5CA0
8FBBB1 5CA2
8FBBB2 5CA3
8FBBB3 5CA6
8FBBB4 5CAA
8FBBB5 5CB2
8FBBB6 5CB4
8FBBB7 5CB5
8FBBB8 5CBA
8FBBB9 5CC9
8FBBBA 5CCB
8FBBBB 5CD2
8FBBBC 5CDD
8FBBBD 5CD7
8FBBBE 5CEE
8FBBBF 5CF1
8FBBC0 5CF2
8FBBC1 5CF4
8FBBC2 5D01
8FBBC3 5D06
8FBBC4 5D0D
8FBBC5 5D12
8FBBC6 5D2B
8FBBC7 5D23
8FBBC8 5D24
8FBBC9 5D26
8FBBCA 5D27
8FBBCB 5D31
8FBBCC 5D34
8FBBCD 5D39
8FBBCE 5D3D
8FBBCF 5D3F
8FBBD0 5D42
8FBBD1 5D43
8FBBD2 5D46
8FBBD3 5D48
8FBBD4 5D55
8FBBD5 5D51
8FBBD6 5D59
8FBBD7 5D4A
8FBBD8 5D5F
8FBBD9 5D60
8FBBDA 5D61
8FBBDB 5D62
8FBBDC 5D64
8FBBDD 5D6A
8FBBDE 5D6D
8FBBDF 5D70
8FBBE0 5D79
8FBBE1 5D7A
8FBBE2 5D7E
8FBBE3 5D7F
8FBBE4 5D81
8FBBE5 5D83
8FBBE6 5D88
8FBBE7 5D8A
8FBBE8 5D92
8FBBE9 5D93
8FBBEA 5D94
8FBBEB 5D95
8FBBEC 5D99
8FBBED 5D9B
8FBBEE 5D9F
8FBBEF 5DA0
8FBBF0 5DA7
8FBBF1 5DAB
8FBBF2 5DB0
8FBBF3 5DB4
8FBBF4 5DB8
8FBBF5 5DB9
8FBBF6 5DC3
8FBBF7 5DC7
8FBBF8 5DCB
8FBBF9 5DD0
8FBBFA 5DCE
8FBBFB 5DD8
8FBBFC 5DD9
8FBBFD 5DE0
8FBBFE 5DE4
8FBCA1 5DE9
8FBCA2 5DF8
8FBCA3 5DF9
8FBCA4 5E00
8FBCA5 5E07
8FBCA6 5E0D
8FBCA7 5E12
8FBCA8 5E14
8FBCA9 5E15
8FBCAA 5E18
8FBCAB 5E1F
8FBCAC 5E20
8FBCAD 5E2E
8FBCAE 5E28
8FBCAF 5E32
8FBCB0 5E35
8FBCB1 5E3E
8FBCB2 5E4B
8FBCB3 5E50
8FBCB4 5E49
8FBCB5 5E51
8FBCB6 5E56
8FBCB7 5E58
8FBCB8 5E5B
8FBCB9 5E5C
8FBCBA 5E5E
8FBCBB 5E68
8FBCBC 5E6A
8FBCBD 5E6B
8FBCBE 5E6C
8FBCBF 5E6D
8FBCC0 5E6E
8FBCC1 5E70
8FBCC2 5E80
8FBCC3 5E8B
8FBCC4 5E8E
8FBCC5 5EA2
8FBCC6 5EA4
8FBCC7 5EA5
8FBCC8 5EA8
8FBCC9 5EAA
8FBCCA 5EAC
8FBCCB 5EB1
8FBCCC 5EB3
8FBCCD 5EBD
8FBCCE 5EBE
8FBCCF 5EBF
8FBCD0 5EC6
8FBCD1 5ECC
8FBCD2 5ECB
8FBCD3 5ECE
8FBCD4 5ED1
8FBCD5 5ED2
8FBCD6 5ED4
8FBCD7 5ED5
8FBCD8 5EDC
8FBCD9 5EDE
8FBCDA 5EE5
8FBCDB 5EEB
8FBCDC 5F02
8FBCDD 5F06
8FBCDE 5F07
8FBCDF 5F08
8FBCE0 5F0E
8FBCE1 5F19
8FBCE2 5F1C
8FBCE3 5F1D
8FBCE4 5F21
8FBCE5 5F22
8FBCE6 5F23
8FBCE7 5F24
8FBCE8 5F28
8FBCE9 5F2B
8FBCEA 5F2C
8FBCEB 5F2E
8FBCEC 5F30
8FBCED 5F34
8FBCEE 5F36
8FBCEF 5F3B
8FBCF0 5F3D
8FBCF1 5F3F
8FBCF2 5F40
8FBCF3 5F44
8FBCF4 5F45
8FBCF5 5F47
8FBCF6 5F4D
8FBCF7 5F50
8FBCF8 5F54
8FBCF9 5F58
8FBCFA 5F5B
8FBCFB 5F60
8FBCFC 5F63
8FBCFD 5F64
8FBCFE 5F67
8FBDA1 5F6F
8FBDA2 5F72
8FBDA3 5F74
8FBDA4 5F75
8FBDA5 5F78
8FBDA6 5F7A
8FBDA7 5F7D
8FBDA8 5F7E
8FBDA9 5F89
8FBDAA 5F8D
8FBDAB 5F8F
8FBDAC 5F96
8FBDAD 5F9C
8FBDAE 5F9D
8FBDAF 5FA2
8FBDB0 5FA7
8FBDB1 5FAB
8FBDB2 5FA4
8FBDB3 5FAC
8FBDB4 5FAF
8FBDB5 5FB0
8FBDB6 5FB1
8FBDB7 5FB8
8FBDB8 5FC4
8FBDB9 5FC7
8FBDBA 5FC8
8FBDBB 5FC9
8FBDBC 5FCB
8FBDBD 5FD0
8FBDBE 5FD1
8FBDBF 5FD2
8FBDC0 5FD3
8FBDC1 5FD4
8FBDC2 5FDE
8FBDC3 5FE1
8FBDC4 5FE2
8FBDC5 5FE8
8FBDC6 5FE9
8FBDC7 5FEA
8FBDC8 5FEC
8FBDC9 5FED
8FBDCA 5FEE
8FBDCB 5FEF
8FBDCC 5FF2
8FBDCD 5FF3
8FBDCE 5FF6
8FBDCF 5FFA
8FBDD0 5FFC
8FBDD1 6007
8FBDD2 600A
8FBDD3 600D
8FBDD4 6013
8FBDD5 6014
8FBDD6 6017
8FBDD7 6018
8FBDD8 601A
8FBDD9 601F
8FBDDA 6024
8FBDDB 602D
8FBDDC 6033
8FBDDD 6035
8FBDDE 6040
8FBDDF 6047
8FBDE0 6048
8FBDE1 6049
8FBDE2 604C
8FBDE3 6051
8FBDE4 6054
8FBDE5 6056
8FBDE6 6057
8FBDE7 605D
8FBDE8 6061
8FBDE9 6067
8FBDEA 6071
8FBDEB 607E
8FBDEC 607F
8FBDED 6082
8FBDEE 6086
8FBDEF 6088
8FBDF0 608A
8FBDF1 608E
8FBDF2 6091
8FBDF3 6093
8FBDF4 6095
8FBDF5 6098
8FBDF6 609D
8FBDF7 609E
8FBDF8 60A2
8FBDF9 60A4
8FBDFA 60A5
8FBDFB 60A8
8FBDFC 60B0
8FBDFD 60B1
8FBDFE 60B7
8FBEA1 60BB
8FBEA2 60BE
8FBEA3 60C2
8FBEA4 60C4
8FBEA5 60C8
8FBEA6 60C9
8FBEA7 60CA
8FBEA8 60CB
8FBEA9 60CE
8FBEAA 60CF
8FBEAB 60D4
8FBEAC 60D5
8FBEAD 60D9
8FBEAE 60DB
8FBEAF 60DD
8FBEB0 60DE
8FBEB1 60E2
8FBEB2 60E5
8FBEB3 60F2
8FBEB4 60F5
8FBEB5 60F8
8FBEB6 60FC
8FBEB7 60FD
8FBEB8 6102
8FBEB9 6107
8FBEBA 610A
8FBEBB 610C
8FBEBC 6110
8FBEBD 6111
8FBEBE 6112
8FBEBF 6113
8FBEC0 6114
8FBEC1 6116
8FBEC2 6117
8FBEC3 6119
8FBEC4 611C
8FBEC5 611E
8FBEC6 6122
8FBEC7 612A
8FBEC8 612B
8FBEC9 6130
8FBECA 6131
8FBECB 6135
8FBECC 6136
8FBECD 6137
8FBECE 6139
8FBECF 6141
8FBED0 6145
8FBED1 6146
8FBED2 6149
8FBED3 615E
8FBED4 6160
8FBED5 616C
8FBED6 6172
8FBED7 6178
8FBED8 617B
8FBED9 617C
8FBEDA 617F
8FBEDB 6180
8FBEDC 6181
8FBEDD 6183
8FBEDE 6184
8FBEDF 618B
8FBEE0 618D
8FBEE1 6192
8FBEE2 6193
8FBEE3 6197
8FBEE4 6198
8FBEE5 619C
8FBEE6 619D
8FBEE7 619F
8FBEE8 61A0
8FBEE9 61A5
8FBEEA 61A8
8FBEEB 61AA
8FBEEC 61AD
8FBEED 61B8
8FBEEE 61B9
8FBEEF 61BC
8FBEF0 61C0
8FBEF1 61C1
8FBEF2 61C2
8FBEF3 61CE
8FBEF4 61CF
8FBEF5 61D5
8FBEF6 61DC
8FBEF7 61DD
8FBEF8 61DE
8FBEF9 61DF
8FBEFA 61E1
8FBEFB 61E2
8FBEFC 61E7
8FBEFD 61E9
8FBEFE 61E5
8FBFA1 61EC
8FBFA2 61ED
8FBFA3 61EF
8FBFA4 6201
8FBFA5 6203
8FBFA6 6204
8FBFA7 6207
8FBFA8 6213
8FBFA9 6215
8FBFAA 621C
8FBFAB 6220
8FBFAC 6222
8FBFAD 6223
8FBFAE 6227
8FBFAF 6229
8FBFB0 622B
8FBFB1 6239
8FBFB2 623D
8FBFB3 6242
8FBFB4 6243
8FBFB5 6244
8FBFB6 6246
8FBFB7 624C
8FBFB8 6250
8FBFB9 6251
8FBFBA 6252
8FBFBB 6254
8FBFBC 6256
8FBFBD 625A
8FBFBE 625C
8FBFBF 6264
8FBFC0 626D
8FBFC1 626F
8FBFC2 6273
8FBFC3 627A
8FBFC4 627D
8FBFC5 628D
8FBFC6 628E
8FBFC7 628F
8FBFC8 6290
8FBFC9 62A6
8FBFCA 62A8
8FBFCB 62B3
8FBFCC 62B6
8FBFCD 62B7
8FBFCE 62BA
8FBFCF 62BE
8FBFD0 62BF
8FBFD1 62C4
8FBFD2 62CE
8FBFD3 62D5
8FBFD4 62D6
8FBFD5 62DA
8FBFD6 62EA
8FBFD7 62F2
8FBFD8 62F4
8FBFD9 62FC
8FBFDA 62FD
8FBFDB 6303
8FBFDC 6304
8FBFDD 630A
8FBFDE 630B
8FBFDF 630D
8FBFE0 6310
8FBFE1 6313
8FBFE2 6316
8FBFE3 6318
8FBFE4 6329
8FBFE5 632A
8FBFE6 632D
8FBFE7 6335
8FBFE8 6336
8FBFE9 6339
8FBFEA 633C
8FBFEB 6341
8FBFEC 6342
8FBFED 6343
8FBFEE 6344
8FBFEF 6346
8FBFF0 634A
8FBFF1 634B
8FBFF2 634E
8FBFF3 6352
8FBFF4 6353
8FBFF5 6354
8FBFF6 6358
8FBFF7 635B
8FBFF8 6365
8FBFF9 6366
8FBFFA 636C
8FBFFB 636D
8FBFFC 6371
8FBFFD 6374
8FBFFE 6375
8FC0A1 6378
8FC0A2 637C
8FC0A3 637D
8FC0A4 637F
8FC0A5 6382
8FC0A6 6384
8FC0A7 6387
8FC0A8 638A
8FC0A9 6390
8FC0AA 6394
8FC0AB 6395
8FC0AC 6399
8FC0AD 639A
8FC0AE 639E
8FC0AF 63A4
8FC0B0 63A6
8FC0B1 63AD
8FC0B2 63AE
8FC0B3 63AF
8FC0B4 63BD
8FC0B5 63C1
8FC0B6 63C5
8FC0B7 63C8
8FC0B8 63CE
8FC0B9 63D1
8FC0BA 63D3
8FC0BB 63D4
8FC0BC 63D5
8FC0BD 63DC
8FC0BE 63E0
8FC0BF 63E5
8FC0C0 63EA
8FC0C1 63EC
8FC0C2 63F2
8FC0C3 63F3
8FC0C4 63F5
8FC0C5 63F8
8FC0C6 63F9
8FC0C7 6409
8FC0C8 640A
8FC0C9 6410
8FC0CA 6412
8FC0CB 6414
8FC0CC 6418
8FC0CD 641E
8FC0CE 6420
8FC0CF 6422
8FC0D0 6424
8FC0D1 6425
8FC0D2 6429
8FC0D3 642A
8FC0D4 642F
8FC0D5 6430
8FC0D6 6435
8FC0D7 643D
8FC0D8 643F
8FC0D9 644B
8FC0DA 644F
8FC0DB 6451
8FC0DC 6452
8FC0DD 6453
8FC0DE 6454
8FC0DF 645A
8FC0E0 645B
8FC0E1 645C
8FC0E2 645D
8FC0E3 645F
8FC0E4 6460
8FC0E5 6461
8FC0E6 6463
8FC0E7 646D
8FC0E8 6473
8FC0E9 6474
8FC0EA 647B
8FC0EB 647D
8FC0EC 6485
8FC0ED 6487
8FC0EE 648F
8FC0EF 6490
8FC0F0 6491
8FC0F1 6498
8FC0F2 6499
8FC0F3 649B
8FC0F4 649D
8FC0F5 649F
8FC0F6 64A1
8FC0F7 64A3
8FC0F8 64A6
8FC0F9 64A8
8FC0FA 64AC
8FC0FB 64B3
8FC0FC 64BD
8FC0FD 64BE
8FC0FE 64BF
8FC1A1 64C4
8FC1A2 64C9
8FC1A3 64CA
8FC1A4 64CB
8FC1A5 64CC
8FC1A6 64CE
8FC1A7 64D0
8FC1A8 64D1
8FC1A9 64D5
8FC1AA 64D7
8FC1AB 64E4
8FC1AC 64E5
8FC1AD 64E9
8FC1AE 64EA
8FC1AF 64ED
8FC1B0 64F0
8FC1B1 64F5
8FC1B2 64F7
8FC1B3 64FB
8FC1B4 64FF
8FC1B5 6501
8FC1B6 6504
8FC1B7 6508
8FC1B8 6509
8FC1B9 650A
8FC1BA 650F
8FC1BB 6513
8FC1BC 6514
8FC1BD 6516
8FC1BE 6519
8FC1BF 651B
8FC1C0 651E
8FC1C1 651F
8FC1C2 6522
8FC1C3 6526
8FC1C4 6529
8FC1C5 652E
8FC1C6 6531
8FC1C7 653A
8FC1C8 653C
8FC1C9 653D
8FC1CA 6543
8FC1CB 6547
8FC1CC 6549
8FC1CD 6550
8FC1CE 6552
8FC1CF 6554
8FC1D0 655F
8FC1D1 6560
8FC1D2 6567
8FC1D3 656B
8FC1D4 657A
8FC1D5 657D
8FC1D6 6581
8FC1D7 6585
8FC1D8 658A
8FC1D9 6592
8FC1DA 6595
8FC1DB 6598
8FC1DC 659D
8FC1DD 65A0
8FC1DE 65A3
8FC1DF 65A6
8FC1E0 65AE
8FC1E1 65B2
8FC1E2 65B3
8FC1E3 65B4
8FC1E4 65BF
8FC1E5 65C2
8FC1E6 65C8
8FC1E7 65C9
8FC1E8 65CE
8FC1E9 65D0
8FC1EA 65D4
8FC1EB 65D6
8FC1EC 65D8
8FC1ED 65DF
8FC1EE 65F0
8FC1EF 65F2
8FC1F0 65F4
8FC1F1 65F5
8FC1F2 65F9
8FC1F3 65FE
8FC1F4 65FF
8FC1F5 6600
8FC1F6 6604
8FC1F7 6608
8FC1F8 6609
8FC1F9 660D
8FC1FA 6611
8FC1FB 6612
8FC1FC 6615
8FC1FD 6616
8FC1FE 661D
8FC2A1 661E
8FC2A2 6621
8FC2A3 6622
8FC2A4 6623
8FC2A5 6624
8FC2A6 6626
8FC2A7 6629
8FC2A8 662A
8FC2A9 662B
8FC2AA 662C
8FC2AB 662E
8FC2AC 6630
8FC2AD 6631
8FC2AE 6633
8FC2AF 6639
8FC2B0 6637
8FC2B1 6640
8FC2B2 6645
8FC2B3 6646
8FC2B4 664A
8FC2B5 664C
8FC2B6 6651
8FC2B7 664E
8FC2B8 6657
8FC2B9 6658
8FC2BA 6659
8FC2BB 665B
8FC2BC 665C
8FC2BD 6660
8FC2BE 6661
8FC2BF 66FB
8FC2C0 666A
8FC2C1 666B
8FC2C2 666C
8FC2C3 667E
8FC2C4 6673
8FC2C5 6675
8FC2C6 667F
8FC2C7 6677
8FC2C8 6678
8FC2C9 6679
8FC2CA 667B
8FC2CB 6680
8FC2CC 667C
8FC2CD 668B
8FC2CE 668C
8FC2CF 668D
8FC2D0 6690
8FC2D1 6692
8FC2D2 6699
8FC2D3 669A
8FC2D4 669B
8FC2D5 669C
8FC2D6 669F
8FC2D7 66A0
8FC2D8 66A4
8FC2D9 66AD
8FC2DA 66B1
8FC2DB 66B2
8FC2DC 66B5
8FC2DD 66BB
8FC2DE 66BF
8FC2DF 66C0
8FC2E0 66C2
8FC2E1 66C3
8FC2E2 66C8
8FC2E3 66CC
8FC2E4 66CE
8FC2E5 66CF
8FC2E6 66D4
8FC2E7 66DB
8FC2E8 66DF
8FC2E9 66E8
8FC2EA 66EB
8FC2EB 66EC
8FC2EC 66EE
8FC2ED 66FA
8FC2EE 6705
8FC2EF 6707
8FC2F0 670E
8FC2F1 6713
8FC2F2 6719
8FC2F3 671C
8FC2F4 6720
8FC2F5 6722
8FC2F6 6733
8FC2F7 673E
8FC2F8 6745
8FC2F9 6747
8FC2FA 6748
8FC2FB 674C
8FC2FC 6754
8FC2FD 6755
8FC2FE 675D
8FC3A1 6766
8FC3A2 676C
8FC3A3 676E
8FC3A4 6774
8FC3A5 6776
8FC3A6 677B
8FC3A7 6781
8FC3A8 6784
8FC3A9 678E
8FC3AA 678F
8FC3AB 6791
8FC3AC 6793
8FC3AD 6796
8FC3AE 6798
8FC3AF 6799
8FC3B0 679B
8FC3B1 67B0
8FC3B2 67B1
8FC3B3 67B2
8FC3B4 67B5
8FC3B5 67BB
8FC3B6 67BC
8FC3B7 67BD
8FC3B8 67F9
8FC3B9 67C0
8FC3BA 67C2
8FC3BB 67C3
8FC3BC 67C5
8FC3BD 67C8
8FC3BE 67C9
8FC3BF 67D2
8FC3C0 67D7
8FC3C1 67D9
8FC3C2 67DC
8FC3C3 67E1
8FC3C4 67E6
8FC3C5 67F0
8FC3C6 67F2
8FC3C7 67F6
8FC3C8 67F7
8FC3C9 6852
8FC3CA 6814
8FC3CB 6819
8FC3CC 681D
8FC3CD 681F
8FC3CE 6828
8FC3CF 6827
8FC3D0 682C
8FC3D1 682D
8FC3D2 682F
8FC3D3 6830
8FC3D4 6831
8FC3D5 6833
8FC3D6 683B
8FC3D7 683F
8FC3D8 6844
8FC3D9 6845
8FC3DA 684A
8FC3DB 684C
8FC3DC 6855
8FC3DD 6857
8FC3DE 6858
8FC3DF 685B
8FC3E0 686B
8FC3E1 686E
8FC3E2 686F
8FC3E3 6870
8FC3E4 6871
8FC3E5 6872
8FC3E6 6875
8FC3E7 6879
8FC3E8 687A
8FC3E9 687B
8FC3EA 687C
8FC3EB 6882
8FC3EC 6884
8FC3ED 6886
8FC3EE 6888
8FC3EF 6896
8FC3F0 6898
8FC3F1 689A
8FC3F2 689C
8FC3F3 68A1
8FC3F4 68A3
8FC3F5 68A5
8FC3F6 68A9
8FC3F7 68AA
8FC3F8 68AE
8FC3F9 68B2
8FC3FA 68BB
8FC3FB 68C5
8FC3FC 68C8
8FC3FD 68CC
8FC3FE 68CF
8FC4A1 68D0
8FC4A2 68D1
8FC4A3 68D3
8FC4A4 68D6
8FC4A5 68D9
8FC4A6 68DC
8FC4A7 68DD
8FC4A8 68E5
8FC4A9 68E8
8FC4AA 68EA
8FC4AB 68EB
8FC4AC 68EC
8FC4AD 68ED
8FC4AE 68F0
8FC4AF 68F1
8FC4B0 68F5
8FC4B1 68F6
8FC4B2 68FB
8FC4B3 68FC
8FC4B4 68FD
8FC4B5 6906
8FC4B6 6909
8FC4B7 690A
8FC4B8 6910
8FC4B9 6911
8FC4BA 6913
8FC4BB 6916
8FC4BC 6917
8FC4BD 6931
8FC4BE 6933
8FC4BF 6935
8FC4C0 6938
8FC4C1 693B
8FC4C2 6942
8FC4C3 6945
8FC4C4 6949
8FC4C5 694E
8FC4C6 6957
8FC4C7 695B
8FC4C8 6963
8FC4C9 6964
8FC4CA 6965
8FC4CB 6966
8FC4CC 6968
8FC4CD 6969
8FC4CE 696C
8FC4CF 6970
8FC4D0 6971
8FC4D1 6972
8FC4D2 697A
8FC4D3 697B
8FC4D4 697F
8FC4D5 6980
8FC4D6 698D
8FC4D7 6992
8FC4D8 6996
8FC4D9 6998
8FC4DA 69A1
8FC4DB 69A5
8FC4DC 69A6
8FC4DD 69A8
8FC4DE 69AB
8FC4DF 69AD
8FC4E0 69AF
8FC4E1 69B7
8FC4E2 69B8
8FC4E3 69BA
8FC4E4 69BC
8FC4E5 69C5
8FC4E6 69C8
8FC4E7 69D1
8FC4E8 69D6
8FC4E9 69D7
8FC4EA 69E2
8FC4EB 69E5
8FC4EC 69EE
8FC4ED 69EF
8FC4EE 69F1
8FC4EF 69F3
8FC4F0 69F5
8FC4F1 69FE
8FC4F2 6A00
8FC4F3 6A01
8FC4F4 6A03
8FC4F5 6A0F
8FC4F6 6A11
8FC4F7 6A15
8FC4F8 6A1A
8FC4F9 6A1D
8FC4FA 6A20
8FC4FB 6A24
8FC4FC 6A28
8FC4FD 6A30
8FC4FE 6A32
8FC5A1 6A34
8FC5A2 6A37
8FC5A3 6A3B
8FC5A4 6A3E
8FC5A5 6A3F
8FC5A6 6A45
8FC5A7 6A46
8FC5A8 6A49
8FC5A9 6A4A
8FC5AA 6A4E
8FC5AB 6A50
8FC5AC 6A51
8FC5AD 6A52
8FC5AE 6A55
8FC5AF 6A56
8FC5B0 6A5B
8FC5B1 6A64
8FC5B2 6A67
8FC5B3 6A6A
8FC5B4 6A71
8FC5B5 6A73
8FC5B6 6A7E
8FC5B7 6A81
8FC5B8 6A83
8FC5B9 6A86
8FC5BA 6A87
8FC5BB 6A89
8FC5BC 6A8B
8FC5BD 6A91
8FC5BE 6A9B
8FC5BF 6A9D
8FC5C0 6A9E
8FC5C1 6A9F
8FC5C2 6AA5
8FC5C3 6AAB
8FC5C4 6AAF
8FC5C5 6AB0
8FC5C6 6AB1
8FC5C7 6AB4
8FC5C8 6ABD
8FC5C9 6ABE
8FC5CA 6ABF
8FC5CB 6AC6
8FC5CC 6AC9
8FC5CD 6AC8
8FC5CE 6ACC
8FC5CF 6AD0
8FC5D0 6AD4
8FC5D1 6AD5
8FC5D2 6AD6
8FC5D3 6ADC
8FC5D4 6ADD
8FC5D5 6AE4
8FC5D6 6AE7
8FC5D7 6AEC
8FC5D8 6AF0
8FC5D9 6AF1
8FC5DA 6AF2
8FC5DB 6AFC
8FC5DC 6AFD
8FC5DD 6B02
8FC5DE 6B03
8FC5DF 6B06
8FC5E0 6B07
8FC5E1 6B09
8FC5E2 6B0F
8FC5E3 6B10
8FC5E4 6B11
8FC5E5 6B17
8FC5E6 6B1B
8FC5E7 6B1E
8FC5E8 6B24
8FC5E9 6B28
8FC5EA 6B2B
8FC5EB 6B2C
8FC5EC 6B2F
8FC5ED 6B35
8FC5EE 6B36
8FC5EF 6B3B
8FC5F0 6B3F
8FC5F1 6B46
8FC5F2 6B4A
8FC5F3 6B4D
8FC5F4 6B52
8FC5F5 6B56
8FC5F6 6B58
8FC5F7 6B5D
8FC5F8 6B60
8FC5F9 6B67
8FC5FA 6B6B
8FC5FB 6B6E
8FC5FC 6B70
8FC5FD 6B75
8FC5FE 6B7D
8FC6A1 6B7E
8FC6A2 6B82
8FC6A3 6B85
8FC6A4 6B97
8FC6A5 6B9B
8FC6A6 6B9F
8FC6A7 6BA0
8FC6A8 6BA2
8FC6A9 6BA3
8FC6AA 6BA8
8FC6AB 6BA9
8FC6AC 6BAC
8FC6AD 6BAD
8FC6AE 6BAE
8FC6AF 6BB0
8FC6B0 6BB8
8FC6B1 6BB9
8FC6B2 6BBD
8FC6B3 6BBE
8FC6B4 6BC3
8FC6B5 6BC4
8FC6B6 6BC9
8FC6B7 6BCC
8FC6B8 6BD6
8FC6B9 6BDA
8FC6BA 6BE1
8FC6BB 6BE3
8FC6BC 6BE6
8FC6BD 6BE7
8FC6BE 6BEE
8FC6BF 6BF1
8FC6C0 6BF7
8FC6C1 6BF9
8FC6C2 6BFF
8FC6C3 6C02
8FC6C4 6C04
8FC6C5 6C05
8FC6C6 6C09
8FC6C7 6C0D
8FC6C8 6C0E
8FC6C9 6C10
8FC6CA 6C12
8FC6CB 6C19
8FC6CC 6C1F
8FC6CD 6C26
8FC6CE 6C27
8FC6CF 6C28
8FC6D0 6C2C
8FC6D1 6C2E
8FC6D2 6C33
8FC6D3 6C35
8FC6D4 6C36
8FC6D5 6C3A
8FC6D6 6C3B
8FC6D7 6C3F
8FC6D8 6C4A
8FC6D9 6C4B
8FC6DA 6C4D
8FC6DB 6C4F
8FC6DC 6C52
8FC6DD 6C54
8FC6DE 6C59
8FC6DF 6C5B
8FC6E0 6C5C
8FC6E1 6C6B
8FC6E2 6C6D
8FC6E3 6C6F
8FC6E4 6C74
8FC6E5 6C76
8FC6E6 6C78
8FC6E7 6C79
8FC6E8 6C7B
8FC6E9 6C85
8FC6EA 6C86
8FC6EB 6C87
8FC6EC 6C89
8FC6ED 6C94
8FC6EE 6C95
8FC6EF 6C97
8FC6F0 6C98
8FC6F1 6C9C
8FC6F2 6C9F
8FC6F3 6CB0
8FC6F4 6CB2
8FC6F5 6CB4
8FC6F6 6CC2
8FC6F7 6CC6
8FC6F8 6CCD
8FC6F9 6CCF
8FC6FA 6CD0
8FC6FB 6CD1
8FC6FC 6CD2
8FC6FD 6CD4
8FC6FE 6CD6
8FC7A1 6CDA
8FC7A2 6CDC
8FC7A3 6CE0
8FC7A4 6CE7
8FC7A5 6CE9
8FC7A6 6CEB
8FC7A7 6CEC
8FC7A8 6CEE
8FC7A9 6CF2
8FC7AA 6CF4
8FC7AB 6D04
8FC7AC 6D07
8FC7AD 6D0A
8FC7AE 6D0E
8FC7AF 6D0F
8FC7B0 6D11
8FC7B1 6D13
8FC7B2 6D1A
8FC7B3 6D26
8FC7B4 6D27
8FC7B5 6D28
8FC7B6 6C67
8FC7B7 6D2E
8FC7B8 6D2F
8FC7B9 6D31
8FC7BA 6D39
8FC7BB 6D3C
8FC7BC 6D3F
8FC7BD 6D57
8FC7BE 6D5E
8FC7BF 6D5F
8FC7C0 6D61
8FC7C1 6D65
8FC7C2 6D67
8FC7C3 6D6F
8FC7C4 6D70
8FC7C5 6D7C
8FC7C6 6D82
8FC7C7 6D87
8FC7C8 6D91
8FC7C9 6D92
8FC7CA 6D94
8FC7CB 6D96
8FC7CC 6D97
8FC7CD 6D98
8FC7CE 6DAA
8FC7CF 6DAC
8FC7D0 6DB4
8FC7D1 6DB7
8FC7D2 6DB9
8FC7D3 6DBD
8FC7D4 6DBF
8FC7D5 6DC4
8FC7D6 6DC8
8FC7D7 6DCA
8FC7D8 6DCE
8FC7D9 6DCF
8FC7DA 6DD6
8FC7DB 6DDB
8FC7DC 6DDD
8FC7DD 6DDF
8FC7DE 6DE0
8FC7DF 6DE2
8FC7E0 6DE5
8FC7E1 6DE9
8FC7E2 6DEF
8FC7E3 6DF0
8FC7E4 6DF4
8FC7E5 6DF6
8FC7E6 6DFC
8FC7E7 6E00
8FC7E8 6E04
8FC7E9 6E1E
8FC7EA 6E22
8FC7EB 6E27
8FC7EC 6E32
8FC7ED 6E36
8FC7EE 6E39
8FC7EF 6E3B
8FC7F0 6E3C
8FC7F1 6E44
8FC7F2 6E45
8FC7F3 6E48
8FC7F4 6E49
8FC7F5 6E4B
8FC7F6 6E4F
8FC7F7 6E51
8FC7F8 6E52
8FC7F9 6E53
8FC7FA 6E54
8FC7FB 6E57
8FC7FC 6E5C
8FC7FD 6E5D
8FC7FE 6E5E
8FC8A1 6E62
8FC8A2 6E63
8FC8A3 6E68
8FC8A4 6E73
8FC8A5 6E7B
8FC8A6 6E7D
8FC8A7 6E8D
8FC8A8 6E93
8FC8A9 6E99
8FC8AA 6EA0
8FC8AB 6EA7
8FC8AC 6EAD
8FC8AD 6EAE
8FC8AE 6EB1
8FC8AF 6EB3
8FC8B0 6EBB
8FC8B1 6EBF
8FC8B2 6EC0
8FC8B3 6EC1
8FC8B4 6EC3
8FC8B5 6EC7
8FC8B6 6EC8
8FC8B7 6ECA
8FC8B8 6ECD
8FC8B9 6ECE
8FC8BA 6ECF
8FC8BB 6EEB
8FC8BC 6EED
8FC8BD 6EEE
8FC8BE 6EF9
8FC8BF 6EFB
8FC8C0 6EFD
8FC8C1 6F04
8FC8C2 6F08
8FC8C3 6F0A
8FC8C4 6F0C
8FC8C5 6F0D
8FC8C6 6F16
8FC8C7 6F18
8FC8C8 6F1A
8FC8C9 6F1B
8FC8CA 6F26
8FC8CB 6F29
8FC8CC 6F2A
8FC8CD 6F2F
8FC8CE 6F30
8FC8CF 6F33
8FC8D0 6F36
8FC8D1 6F3B
8FC8D2 6F3C
8FC8D3 6F2D
8FC8D4 6F4F
8FC8D5 6F51
8FC8D6 6F52
8FC8D7 6F53
8FC8D8 6F57
8FC8D9 6F59
8FC8DA 6F5A
8FC8DB 6F5D
8FC8DC 6F5E
8FC8DD 6F61
8FC8DE 6F62
8FC8DF 6F68
8FC8E0 6F6C
8FC8E1 6F7D
8FC8E2 6F7E
8FC8E3 6F83
8FC8E4 6F87
8FC8E5 6F88
8FC8E6 6F8B
8FC8E7 6F8C
8FC8E8 6F8D
8FC8E9 6F90
8FC8EA 6F92
8FC8EB 6F93
8FC8EC 6F94
8FC8ED 6F96
8FC8EE 6F9A
8FC8EF 6F9F
8FC8F0 6FA0
8FC8F1 6FA5
8FC8F2 6FA6
8FC8F3 6FA7
8FC8F4 6FA8
8FC8F5 6FAE
8FC8F6 6FAF
8FC8F7 6FB0
8FC8F8 6FB5
8FC8F9 6FB6
8FC8FA 6FBC
8FC8FB 6FC5
8FC8FC 6FC7
8FC8FD 6FC8
8FC8FE 6FCA
8FC9A1 6FDA
8FC9A2 6FDE
8FC9A3 6FE8
8FC9A4 6FE9
8FC9A5 6FF0
8FC9A6 6FF5
8FC9A7 6FF9
8FC9A8 6FFC
8FC9A9 6FFD
8FC9AA 7000
8FC9AB 7005
8FC9AC 7006
8FC9AD 7007
8FC9AE 700D
8FC9AF 7017
8FC9B0 7020
8FC9B1 7023
8FC9B2 702F
8FC9B3 7034
8FC9B4 7037
8FC9B5 7039
8FC9B6 703C
8FC9B7 7043
8FC9B8 7044
8FC9B9 7048
8FC9BA 7049
8FC9BB 704A
8FC9BC 704B
8FC9BD 7054
8FC9BE 7055
8FC9BF 705D
8FC9C0 705E
8FC9C1 704E
8FC9C2 7064
8FC9C3 7065
8FC9C4 706C
8FC9C5 706E
8FC9C6 7075
8FC9C7 7076
8FC9C8 707E
8FC9C9 7081
8FC9CA 7085
8FC9CB 7086
8FC9CC 7094
8FC9CD 7095
8FC9CE 7096
8FC9CF 7097
8FC9D0 7098
8FC9D1 709B
8FC9D2 70A4
8FC9D3 70AB
8FC9D4 70B0
8FC9D5 70B1
8FC9D6 70B4
8FC9D7 70B7
8FC9D8 70CA
8FC9D9 70D1
8FC9DA 70D3
8FC9DB 70D4
8FC9DC 70D5
8FC9DD 70D6
8FC9DE 70D8
8FC9DF 70DC
8FC9E0 70E4
8FC9E1 70FA
8FC9E2 7103
8FC9E3 7104
8FC9E4 7105
8FC9E5 7106
8FC9E6 7107
8FC9E7 710B
8FC9E8 710C
8FC9E9 710F
8FC9EA 711E
8FC9EB 7120
8FC9EC 712B
8FC9ED 712D
8FC9EE 712F
8FC9EF 7130
8FC9F0 7131
8FC9F1 7138
8FC9F2 7141
8FC9F3 7145
8FC9F4 7146
8FC9F5 7147
8FC9F6 714A
8FC9F7 714B
8FC9F8 7150
8FC9F9 7152
8FC9FA 7157
8FC9FB 715A
8FC9FC 715C
8FC9FD 715E
8FC9FE 7160
8FCAA1 7168
8FCAA2 7179
8FCAA3 7180
8FCAA4 7185
8FCAA5 7187
8FCAA6 718C
8FCAA7 7192
8FCAA8 719A
8FCAA9 719B
8FCAAA 71A0
8FCAAB 71A2
8FCAAC 71AF
8FCAAD 71B0
8FCAAE 71B2
8FCAAF 71B3
8FCAB0 71BA
8FCAB1 71BF
8FCAB2 71C0
8FCAB3 71C1
8FCAB4 71C4
8FCAB5 71CB
8FCAB6 71CC
8FCAB7 71D3
8FCAB8 71D6
8FCAB9 71D9
8FCABA 71DA
8FCABB 71DC
8FCABC 71F8
8FCABD 71FE
8FCABE 7200
8FCABF 7207
8FCAC0 7208
8FCAC1 7209
8FCAC2 7213
8FCAC3 7217
8FCAC4 721A
8FCAC5 721D
8FCAC6 721F
8FCAC7 7224
8FCAC8 722B
8FCAC9 722F
8FCACA 7234
8FCACB 7238
8FCACC 7239
8FCACD 7241
8FCACE 7242
8FCACF 7243
8FCAD0 7245
8FCAD1 724E
8FCAD2 724F
8FCAD3 7250
8FCAD4 7253
8FCAD5 7255
8FCAD6 7256
8FCAD7 725A
8FCAD8 725C
8FCAD9 725E
8FCADA 7260
8FCADB 7263
8FCADC 7268
8FCADD 726B
8FCADE 726E
8FCADF 726F
8FCAE0 7271
8FCAE1 7277
8FCAE2 7278
8FCAE3 727B
8FCAE4 727C
8FCAE5 727F
8FCAE6 7284
8FCAE7 7289
8FCAE8 728D
8FCAE9 728E
8FCAEA 7293
8FCAEB 729B
8FCAEC 72A8
8FCAED 72AD
8FCAEE 72AE
8FCAEF 72B1
8FCAF0 72B4
8FCAF1 72BE
8FCAF2 72C1
8FCAF3 72C7
8FCAF4 72C9
8FCAF5 72CC
8FCAF6 72D5
8FCAF7 72D6
8FCAF8 72D8
8FCAF9 72DF
8FCAFA 72E5
8FCAFB 72F3
8FCAFC 72F4
8FCAFD 72FA
8FCAFE 72FB
8FCBA1 72FE
8FCBA2 7302
8FCBA3 7304
8FCBA4 7305
8FCBA5 7307
8FCBA6 730B
8FCBA7 730D
8FCBA8 7312
8FCBA9 7313
8FCBAA 7318
8FCBAB 7319
8FCBAC 731E
8FCBAD 7322
8FCBAE 7324
8FCBAF 7327
8FCBB0 7328
8FCBB1 732C
8FCBB2 7331
8FCBB3 7332
8FCBB4 7335
8FCBB5 733A
8FCBB6 733B
8FCBB7 733D
8FCBB8 7343
8FCBB9 734D
8FCBBA 7350
8FCBBB 7352
8FCBBC 7356
8FCBBD 7358
8FCBBE 735D
8FCBBF 735E
8FCBC0 735F
8FCBC1 7360
8FCBC2 7366
8FCBC3 7367
8FCBC4 7369
8FCBC5 736B
8FCBC6 736C
8FCBC7 736E
8FCBC8 736F
8FCBC9 7371
8FCBCA 7377
8FCBCB 7379
8FCBCC 737C
8FCBCD 7380
8FCBCE 7381
8FCBCF 7383
8FCBD0 7385
8FCBD1 7386
8FCBD2 738E
8FCBD3 7390
8FCBD4 7393
8FCBD5 7395
8FCBD6 7397
8FCBD7 7398
8FCBD8 739C
8FCBD9 739E
8FCBDA 739F
8FCBDB 73A0
8FCBDC 73A2
8FCBDD 73A5
8FCBDE 73A6
8FCBDF 73AA
8FCBE0 73AB
8FCBE1 73AD
8FCBE2 73B5
8FCBE3 73B7
8FCBE4 73B9
8FCBE5 73BC
8FCBE6 73BD
8FCBE7 73BF
8FCBE8 73C5
8FCBE9 73C6
8FCBEA 73C9
8FCBEB 73CB
8FCBEC 73CC
8FCBED 73CF
8FCBEE 73D2
8FCBEF 73D3
8FCBF0 73D6
8FCBF1 73D9
8FCBF2 73DD
8FCBF3 73E1
8FCBF4 73E3
8FCBF5 73E6
8FCBF6 73E7
8FCBF7 73E9
8FCBF8 73F4
8FCBF9 73F5
8FCBFA 73F7
8FCBFB 73F9
8FCBFC 73FA
8FCBFD 73FB
8FCBFE 73FD
8FCCA1 73FF
8FCCA2 7400
8FCCA3 7401
8FCCA4 7404
8FCCA5 7407
8FCCA6 740A
8FCCA7 7411
8FCCA8 741A
8FCCA9 741B
8FCCAA 7424
8FCCAB 7426
8FCCAC 7428
8FCCAD 7429
8FCCAE 742A
8FCCAF 742B
8FCCB0 742C
8FCCB1 742D
8FCCB2 742E
8FCCB3 742F
8FCCB4 7430
8FCCB5 7431
8FCCB6 7439
8FCCB7 7440
8FCCB8 7443
8FCCB9 7444
8FCCBA 7446
8FCCBB 7447
8FCCBC 744B
8FCCBD 744D
8FCCBE 7451
8FCCBF 7452
8FCCC0 7457
8FCCC1 745D
8FCCC2 7462
8FCCC3 7466
8FCCC4 7467
8FCCC5 7468
8FCCC6 746B
8FCCC7 746D
8FCCC8 746E
8FCCC9 7471
8FCCCA 7472
8FCCCB 7480
8FCCCC 7481
8FCCCD 7485
8FCCCE 7486
8FCCCF 7487
8FCCD0 7489
8FCCD1 748F
8FCCD2 7490
8FCCD3 7491
8FCCD4 7492
8FCCD5 7498
8FCCD6 7499
8FCCD7 749A
8FCCD8 749C
8FCCD9 749F
8FCCDA 74A0
8FCCDB 74A1
8FCCDC 74A3
8FCCDD 74A6
8FCCDE 74A8
8FCCDF 74A9
8FCCE0 74AA
8FCCE1 74AB
8FCCE2 74AE
8FCCE3 74AF
8FCCE4 74B1
8FCCE5 74B2
8FCCE6 74B5
8FCCE7 74B9
8FCCE8 74BB
8FCCE9 74BF
8FCCEA 74C8
8FCCEB 74C9
8FCCEC 74CC
8FCCED 74D0
8FCCEE 74D3
8FCCEF 74D8
8FCCF0 74DA
8FCCF1 74DB
8FCCF2 74DE
8FCCF3 74DF
8FCCF4 74E4
8FCCF5 74E8
8FCCF6 74EA
8FCCF7 74EB
8FCCF8 74EF
8FCCF9 74F4
8FCCFA 74FA
8FCCFB 74FB
8FCCFC 74FC
8FCCFD 74FF
8FCCFE 7506
8FCDA1 7512
8FCDA2 7516
8FCDA3 7517
8FCDA4 7520
8FCDA5 7521
8FCDA6 7524
8FCDA7 7527
8FCDA8 7529
8FCDA9 752A
8FCDAA 752F
8FCDAB 7536
8FCDAC 7539
8FCDAD 753D
8FCDAE 753E
8FCDAF 753F
8FCDB0 7540
8FCDB1 7543
8FCDB2 7547
8FCDB3 7548
8FCDB4 754E
8FCDB5 7550
8FCDB6 7552
8FCDB7 7557
8FCDB8 755E
8FCDB9 755F
8FCDBA 7561
8FCDBB 756F
8FCDBC 7571
8FCDBD 7579
8FCDBE 757A
8FCDBF 757B
8FCDC0 757C
8FCDC1 757D
8FCDC2 757E
8FCDC3 7581
8FCDC4 7585
8FCDC5 7590
8FCDC6 7592
8FCDC7 7593
8FCDC8 7595
8FCDC9 7599
8FCDCA 759C
8FCDCB 75A2
8FCDCC 75A4
8FCDCD 75B4
8FCDCE 75BA
8FCDCF 75BF
8FCDD0 75C0
8FCDD1 75C1
8FCDD2 75C4
8FCDD3 75C6
8FCDD4 75CC
8FCDD5 75CE
8FCDD6 75CF
8FCDD7 75D7
8FCDD8 75DC
8FCDD9 75DF
8FCDDA 75E0
8FCDDB 75E1
8FCDDC 75E4
8FCDDD 75E7
8FCDDE 75EC
8FCDDF 75EE
8FCDE0 75EF
8FCDE1 75F1
8FCDE2 75F9
8FCDE3 7600
8FCDE4 7602
8FCDE5 7603
8FCDE6 7604
8FCDE7 7607
8FCDE8 7608
8FCDE9 760A
8FCDEA 760C
8FCDEB 760F
8FCDEC 7612
8FCDED 7613
8FCDEE 7615
8FCDEF 7616
8FCDF0 7619
8FCDF1 761B
8FCDF2 761C
8FCDF3 761D
8FCDF4 761E
8FCDF5 7623
8FCDF6 7625
8FCDF7 7626
8FCDF8 7629
8FCDF9 762D
8FCDFA 7632
8FCDFB 7633
8FCDFC 7635
8FCDFD 7638
8FCDFE 7639
8FCEA1 763A
8FCEA2 763C
8FCEA3 764A
8FCEA4 7640
8FCEA5 7641
8FCEA6 7643
8FCEA7 7644
8FCEA8 7645
8FCEA9 7649
8FCEAA 764B
8FCEAB 7655
8FCEAC 7659
8FCEAD 765F
8FCEAE 7664
8FCEAF 7665
8FCEB0 766D
8FCEB1 766E
8FCEB2 766F
8FCEB3 7671
8FCEB4 7674
8FCEB5 7681
8FCEB6 7685
8FCEB7 768C
8FCEB8 768D
8FCEB9 7695
8FCEBA 769B
8FCEBB 769C
8FCEBC 769D
8FCEBD 769F
8FCEBE 76A0
8FCEBF 76A2
8FCEC0 76A3
8FCEC1 76A4
8FCEC2 76A5
8FCEC3 76A6
8FCEC4 76A7
8FCEC5 76A8
8FCEC6 76AA
8FCEC7 76AD
8FCEC8 76BD
8FCEC9 76C1
8FCECA 76C5
8FCECB 76C9
8FCECC 76CB
8FCECD 76CC
8FCECE 76CE
8FCECF 76D4
8FCED0 76D9
8FCED1 76E0
8FCED2 76E6
8FCED3 76E8
8FCED4 76EC
8FCED5 76F0
8FCED6 76F1
8FCED7 76F6
8FCED8 76F9
8FCED9 76FC
8FCEDA 7700
8FCEDB 7706
8FCEDC 770A
8FCEDD 770E
8FCEDE 7712
8FCEDF 7714
8FCEE0 7715
8FCEE1 7717
8FCEE2 7719
8FCEE3 771A
8FCEE4 771C
8FCEE5 7722
8FCEE6 7728
8FCEE7 772D
8FCEE8 772E
8FCEE9 772F
8FCEEA 7734
8FCEEB 7735
8FCEEC 7736
8FCEED 7739
8FCEEE 773D
8FCEEF 773E
8FCEF0 7742
8FCEF1 7745
8FCEF2 7746
8FCEF3 774A
8FCEF4 774D
8FCEF5 774E
8FCEF6 774F
8FCEF7 7752
8FCEF8 7756
8FCEF9 7757
8FCEFA 775C
8FCEFB 775E
8FCEFC 775F
8FCEFD 7760
8FCEFE 7762
8FCFA1 7764
8FCFA2 7767
8FCFA3 776A
8FCFA4 776C
8FCFA5 7770
8FCFA6 7772
8FCFA7 7773
8FCFA8 7774
8FCFA9 777A
8FCFAA 777D
8FCFAB 7780
8FCFAC 7784
8FCFAD 778C
8FCFAE 778D
8FCFAF 7794
8FCFB0 7795
8FCFB1 7796
8FCFB2 779A
8FCFB3 779F
8FCFB4 77A2
8FCFB5 77A7
8FCFB6 77AA
8FCFB7 77AE
8FCFB8 77AF
8FCFB9 77B1
8FCFBA 77B5
8FCFBB 77BE
8FCFBC 77C3
8FCFBD 77C9
8FCFBE 77D1
8FCFBF 77D2
8FCFC0 77D5
8FCFC1 77D9
8FCFC2 77DE
8FCFC3 77DF
8FCFC4 77E0
8FCFC5 77E4
8FCFC6 77E6
8FCFC7 77EA
8FCFC8 77EC
8FCFC9 77F0
8FCFCA 77F1
8FCFCB 77F4
8FCFCC 77F8
8FCFCD 77FB
8FCFCE 7805
8FCFCF 7806
8FCFD0 7809
8FCFD1 780D
8FCFD2 780E
8FCFD3 7811
8FCFD4 781D
8FCFD5 7821
8FCFD6 7822
8FCFD7 7823
8FCFD8 782D
8FCFD9 782E
8FCFDA 7830
8FCFDB 7835
8FCFDC 7837
8FCFDD 7843
8FCFDE 7844
8FCFDF 7847
8FCFE0 7848
8FCFE1 784C
8FCFE2 784E
8FCFE3 7852
8FCFE4 785C
8FCFE5 785E
8FCFE6 7860
8FCFE7 7861
8FCFE8 7863
8FCFE9 7864
8FCFEA 7868
8FCFEB 786A
8FCFEC 786E
8FCFED 787A
8FCFEE 787E
8FCFEF 788A
8FCFF0 788F
8FCFF1 7894
8FCFF2 7898
8FCFF3 78A1
8FCFF4 789D
8FCFF5 789E
8FCFF6 789F
8FCFF7 78A4
8FCFF8 78A8
8FCFF9 78AC
8FCFFA 78AD
8FCFFB 78B0
8FCFFC 78B1
8FCFFD 78B2
8FCFFE 78B3
8FD0A1 78BB
8FD0A2 78BD
8FD0A3 78BF
8FD0A4 78C7
8FD0A5 78C8
8FD0A6 78C9
8FD0A7 78CC
8FD0A8 78CE
8FD0A9 78D2
8FD0AA 78D3
8FD0AB 78D5
8FD0AC 78D6
8FD0AD 78E4
8FD0AE 78DB
8FD0AF 78DF
8FD0B0 78E0
8FD0B1 78E1
8FD0B2 78E6
8FD0B3 78EA
8FD0B4 78F2
8FD0B5 78F3
8FD0B6 7900
8FD0B7 78F6
8FD0B8 78F7
8FD0B9 78FA
8FD0BA 78FB
8FD0BB 78FF
8FD0BC 7906
8FD0BD 790C
8FD0BE 7910
8FD0BF 791A
8FD0C0 791C
8FD0C1 791E
8FD0C2 791F
8FD0C3 7920
8FD0C4 7925
8FD0C5 7927
8FD0C6 7929
8FD0C7 792D
8FD0C8 7931
8FD0C9 7934
8FD0CA 7935
8FD0CB 793B
8FD0CC 793D
8FD0CD 793F
8FD0CE 7944
8FD0CF 7945
8FD0D0 7946
8FD0D1 794A
8FD0D2 794B
8FD0D3 794F
8FD0D4 7951
8FD0D5 7954
8FD0D6 7958
8FD0D7 795B
8FD0D8 795C
8FD0D9 7967
8FD0DA 7969
8FD0DB 796B
8FD0DC 7972
8FD0DD 7979
8FD0DE 797B
8FD0DF 797C
8FD0E0 797E
8FD0E1 798B
8FD0E2 798C
8FD0E3 7991
8FD0E4 7993
8FD0E5 7994
8FD0E6 7995
8FD0E7 7996
8FD0E8 7998
8FD0E9 799B
8FD0EA 799C
8FD0EB 79A1
8FD0EC 79A8
8FD0ED 79A9
8FD0EE 79AB
8FD0EF 79AF
8FD0F0 79B1
8FD0F1 79B4
8FD0F2 79B8
8FD0F3 79BB
8FD0F4 79C2
8FD0F5 79C4
8FD0F6 79C7
8FD0F7 79C8
8FD0F8 79CA
8FD0F9 79CF
8FD0FA 79D4
8FD0FB 79D6
8FD0FC 79DA
8FD0FD 79DD
8FD0FE 79DE
8FD1A1 79E0
8FD1A2 79E2
8FD1A3 79E5
8FD1A4 79EA
8FD1A5 79EB
8FD1A6 79ED
8FD1A7 79F1
8FD1A8 79F8
8FD1A9 79FC
8FD1AA 7A02
8FD1AB 7A03
8FD1AC 7A07
8FD1AD 7A09
8FD1AE 7A0A
8FD1AF 7A0C
8FD1B0 7A11
8FD1B1 7A15
8FD1B2 7A1B
8FD1B3 7A1E
8FD1B4 7A21
8FD1B5 7A27
8FD1B6 7A2B
8FD1B7 7A2D
8FD1B8 7A2F
8FD1B9 7A30
8FD1BA 7A34
8FD1BB 7A35
8FD1BC 7A38
8FD1BD 7A39
8FD1BE 7A3A
8FD1BF 7A44
8FD1C0 7A45
8FD1C1 7A47
8FD1C2 7A48
8FD1C3 7A4C
8FD1C4 7A55
8FD1C5 7A56
8FD1C6 7A59
8FD1C7 7A5C
8FD1C8 7A5D
8FD1C9 7A5F
8FD1CA 7A60
8FD1CB 7A65
8FD1CC 7A67
8FD1CD 7A6A
8FD1CE 7A6D
8FD1CF 7A75
8FD1D0 7A78
8FD1D1 7A7E
8FD1D2 7A80
8FD1D3 7A82
8FD1D4 7A85
8FD1D5 7A86
8FD1D6 7A8A
8FD1D7 7A8B
8FD1D8 7A90
8FD1D9 7A91
8FD1DA 7A94
8FD1DB 7A9E
8FD1DC 7AA0
8FD1DD 7AA3
8FD1DE 7AAC
8FD1DF 7AB3
8FD1E0 7AB5
8FD1E1 7AB9
8FD1E2 7ABB
8FD1E3 7ABC
8FD1E4 7AC6
8FD1E5 7AC9
8FD1E6 7ACC
8FD1E7 7ACE
8FD1E8 7AD1
8FD1E9 7ADB
8FD1EA 7AE8
8FD1EB 7AE9
8FD1EC 7AEB
8FD1ED 7AEC
8FD1EE 7AF1
8FD1EF 7AF4
8FD1F0 7AFB
8FD1F1 7AFD
8FD1F2 7AFE
8FD1F3 7B07
8FD1F4 7B14
8FD1F5 7B1F
8FD1F6 7B23
8FD1F7 7B27
8FD1F8 7B29
8FD1F9 7B2A
8FD1FA 7B2B
8FD1FB 7B2D
8FD1FC 7B2E
8FD1FD 7B2F
8FD1FE 7B30
8FD2A1 7B31
8FD2A2 7B34
8FD2A3 7B3D
8FD2A4 7B3F
8FD2A5 7B40
8FD2A6 7B41
8FD2A7 7B47
8FD2A8 7B4E
8FD2A9 7B55
8FD2AA 7B60
8FD2AB 7B64
8FD2AC 7B66
8FD2AD 7B69
8FD2AE 7B6A
8FD2AF 7B6D
8FD2B0 7B6F
8FD2B1 7B72
8FD2B2 7B73
8FD2B3 7B77
8FD2B4 7B84
8FD2B5 7B89
8FD2B6 7B8E
8FD2B7 7B90
8FD2B8 7B91
8FD2B9 7B96
8FD2BA 7B9B
8FD2BB 7B9E
8FD2BC 7BA0
8FD2BD 7BA5
8FD2BE 7BAC
8FD2BF 7BAF
8FD2C0 7BB0
8FD2C1 7BB2
8FD2C2 7BB5
8FD2C3 7BB6
8FD2C4 7BBA
8FD2C5 7BBB
8FD2C6 7BBC
8FD2C7 7BBD
8FD2C8 7BC2
8FD2C9 7BC5
8FD2CA 7BC8
8FD2CB 7BCA
8FD2CC 7BD4
8FD2CD 7BD6
8FD2CE 7BD7
8FD2CF 7BD9
8FD2D0 7BDA
8FD2D1 7BDB
8FD2D2 7BE8
8FD2D3 7BEA
8FD2D4 7BF2
8FD2D5 7BF4
8FD2D6 7BF5
8FD2D7 7BF8
8FD2D8 7BF9
8FD2D9 7BFA
8FD2DA 7BFC
8FD2DB 7BFE
8FD2DC 7C01
8FD2DD 7C02
8FD2DE 7C03
8FD2DF 7C04
8FD2E0 7C06
8FD2E1 7C09
8FD2E2 7C0B
8FD2E3 7C0C
8FD2E4 7C0E
8FD2E5 7C0F
8FD2E6 7C19
8FD2E7 7C1B
8FD2E8 7C20
8FD2E9 7C25
8FD2EA 7C26
8FD2EB 7C28
8FD2EC 7C2C
8FD2ED 7C31
8FD2EE 7C33
8FD2EF 7C34
8FD2F0 7C36
8FD2F1 7C39
8FD2F2 7C3A
8FD2F3 7C46
8FD2F4 7C4A
8FD2F5 7C55
8FD2F6 7C51
8FD2F7 7C52
8FD2F8 7C53
8FD2F9 7C59
8FD2FA 7C5A
8FD2FB 7C5B
8FD2FC 7C5C
8FD2FD 7C5D
8FD2FE 7C5E
8FD3A1 7C61
8FD3A2 7C63
8FD3A3 7C67
8FD3A4 7C69
8FD3A5 7C6D
8FD3A6 7C6E
8FD3A7 7C70
8FD3A8 7C72
8FD3A9 7C79
8FD3AA 7C7C
8FD3AB 7C7D
8FD3AC 7C86
8FD3AD 7C87
8FD3AE 7C8F
8FD3AF 7C94
8FD3B0 7C9E
8FD3B1 7CA0
8FD3B2 7CA6
8FD3B3 7CB0
8FD3B4 7CB6
8FD3B5 7CB7
8FD3B6 7CBA
8FD3B7 7CBB
8FD3B8 7CBC
8FD3B9 7CBF
8FD3BA 7CC4
8FD3BB 7CC7
8FD3BC 7CC8
8FD3BD 7CC9
8FD3BE 7CCD
8FD3BF 7CCF
8FD3C0 7CD3
8FD3C1 7CD4
8FD3C2 7CD5
8FD3C3 7CD7
8FD3C4 7CD9
8FD3C5 7CDA
8FD3C6 7CDD
8FD3C7 7CE6
8FD3C8 7CE9
8FD3C9 7CEB
8FD3CA 7CF5
8FD3CB 7D03
8FD3CC 7D07
8FD3CD 7D08
8FD3CE 7D09
8FD3CF 7D0F
8FD3D0 7D11
8FD3D1 7D12
8FD3D2 7D13
8FD3D3 7D16
8FD3D4 7D1D
8FD3D5 7D1E
8FD3D6 7D23
8FD3D7 7D26
8FD3D8 7D2A
8FD3D9 7D2D
8FD3DA 7D31
8FD3DB 7D3C
8FD3DC 7D3D
8FD3DD 7D3E
8FD3DE 7D40
8FD3DF 7D41
8FD3E0 7D47
8FD3E1 7D48
8FD3E2 7D4D
8FD3E3 7D51
8FD3E4 7D53
8FD3E5 7D57
8FD3E6 7D59
8FD3E7 7D5A
8FD3E8 7D5C
8FD3E9 7D5D
8FD3EA 7D65
8FD3EB 7D67
8FD3EC 7D6A
8FD3ED 7D70
8FD3EE 7D78
8FD3EF 7D7A
8FD3F0 7D7B
8FD3F1 7D7F
8FD3F2 7D81
8FD3F3 7D82
8FD3F4 7D83
8FD3F5 7D85
8FD3F6 7D86
8FD3F7 7D88
8FD3F8 7D8B
8FD3F9 7D8C
8FD3FA 7D8D
8FD3FB 7D91
8FD3FC 7D96
8FD3FD 7D97
8FD3FE 7D9D
8FD4A1 7D9E
8FD4A2 7DA6
8FD4A3 7DA7
8FD4A4 7DAA
8FD4A5 7DB3
8FD4A6 7DB6
8FD4A7 7DB7
8FD4A8 7DB9
8FD4A9 7DC2
8FD4AA 7DC3
8FD4AB 7DC4
8FD4AC 7DC5
8FD4AD 7DC6
8FD4AE 7DCC
8FD4AF 7DCD
8FD4B0 7DCE
8FD4B1 7DD7
8FD4B2 7DD9
8FD4B3 7E00
8FD4B4 7DE2
8FD4B5 7DE5
8FD4B6 7DE6
8FD4B7 7DEA
8FD4B8 7DEB
8FD4B9 7DED
8FD4BA 7DF1
8FD4BB 7DF5
8FD4BC 7DF6
8FD4BD 7DF9
8FD4BE 7DFA
8FD4BF 7E08
8FD4C0 7E10
8FD4C1 7E11
8FD4C2 7E15
8FD4C3 7E17
8FD4C4 7E1C
8FD4C5 7E1D
8FD4C6 7E20
8FD4C7 7E27
8FD4C8 7E28
8FD4C9 7E2C
8FD4CA 7E2D
8FD4CB 7E2F
8FD4CC 7E33
8FD4CD 7E36
8FD4CE 7E3F
8FD4CF 7E44
8FD4D0 7E45
8FD4D1 7E47
8FD4D2 7E4E
8FD4D3 7E50
8FD4D4 7E52
8FD4D5 7E58
8FD4D6 7E5F
8FD4D7 7E61
8FD4D8 7E62
8FD4D9 7E65
8FD4DA 7E6B
8FD4DB 7E6E
8FD4DC 7E6F
8FD4DD 7E73
8FD4DE 7E78
8FD4DF 7E7E
8FD4E0 7E81
8FD4E1 7E86
8FD4E2 7E87
8FD4E3 7E8A
8FD4E4 7E8D
8FD4E5 7E91
8FD4E6 7E95
8FD4E7 7E98
8FD4E8 7E9A
8FD4E9 7E9D
8FD4EA 7E9E
8FD4EB 7F3C
8FD4EC 7F3B
8FD4ED 7F3D
8FD4EE 7F3E
8FD4EF 7F3F
8FD4F0 7F43
8FD4F1 7F44
8FD4F2 7F47
8FD4F3 7F4F
8FD4F4 7F52
8FD4F5 7F53
8FD4F6 7F5B
8FD4F7 7F5C
8FD4F8 7F5D
8FD4F9 7F61
8FD4FA 7F63
8FD4FB 7F64
8FD4FC 7F65
8FD4FD 7F66
8FD4FE 7F6D
8FD5A1 7F71
8FD5A2 7F7D
8FD5A3 7F7E
8FD5A4 7F7F
8FD5A5 7F80
8FD5A6 7F8B
8FD5A7 7F8D
8FD5A8 7F8F
8FD5A9 7F90
8FD5AA 7F91
8FD5AB 7F96
8FD5AC 7F97
8FD5AD 7F9C
8FD5AE 7FA1
8FD5AF 7FA2
8FD5B0 7FA6
8FD5B1 7FAA
8FD5B2 7FAD
8FD5B3 7FB4
8FD5B4 7FBC
8FD5B5 7FBF
8FD5B6 7FC0
8FD5B7 7FC3
8FD5B8 7FC8
8FD5B9 7FCE
8FD5BA 7FCF
8FD5BB 7FDB
8FD5BC 7FDF
8FD5BD 7FE3
8FD5BE 7FE5
8FD5BF 7FE8
8FD5C0 7FEC
8FD5C1 7FEE
8FD5C2 7FEF
8FD5C3 7FF2
8FD5C4 7FFA
8FD5C5 7FFD
8FD5C6 7FFE
8FD5C7 7FFF
8FD5C8 8007
8FD5C9 8008
8FD5CA 800A
8FD5CB 800D
8FD5CC 800E
8FD5CD 800F
8FD5CE 8011
8FD5CF 8013
8FD5D0 8014
8FD5D1 8016
8FD5D2 801D
8FD5D3 801E
8FD5D4 801F
8FD5D5 8020
8FD5D6 8024
8FD5D7 8026
8FD5D8 802C
8FD5D9 802E
8FD5DA 8030
8FD5DB 8034
8FD5DC 8035
8FD5DD 8037
8FD5DE 8039
8FD5DF 803A
8FD5E0 803C
8FD5E1 803E
8FD5E2 8040
8FD5E3 8044
8FD5E4 8060
8FD5E5 8064
8FD5E6 8066
8FD5E7 806D
8FD5E8 8071
8FD5E9 8075
8FD5EA 8081
8FD5EB 8088
8FD5EC 808E
8FD5ED 809C
8FD5EE 809E
8FD5EF 80A6
8FD5F0 80A7
8FD5F1 80AB
8FD5F2 80B8
8FD5F3 80B9
8FD5F4 80C8
8FD5F5 80CD
8FD5F6 80CF
8FD5F7 80D2
8FD5F8 80D4
8FD5F9 80D5
8FD5FA 80D7
8FD5FB 80D8
8FD5FC 80E0
8FD5FD 80ED
8FD5FE 80EE
8FD6A1 80F0
8FD6A2 80F2
8FD6A3 80F3
8FD6A4 80F6
8FD6A5 80F9
8FD6A6 80FA
8FD6A7 80FE
8FD6A8 8103
8FD6A9 810B
8FD6AA 8116
8FD6AB 8117
8FD6AC 8118
8FD6AD 811C
8FD6AE 811E
8FD6AF 8120
8FD6B0 8124
8FD6B1 8127
8FD6B2 812C
8FD6B3 8130
8FD6B4 8135
8FD6B5 813A
8FD6B6 813C
8FD6B7 8145
8FD6B8 8147
8FD6B9 814A
8FD6BA 814C
8FD6BB 8152
8FD6BC 8157
8FD6BD 8160
8FD6BE 8161
8FD6BF 8167
8FD6C0 8168
8FD6C1 8169
8FD6C2 816D
8FD6C3 816F
8FD6C4 8177
8FD6C5 8181
8FD6C6 8190
8FD6C7 8184
8FD6C8 8185
8FD6C9 8186
8FD6CA 818B
8FD6CB 818E
8FD6CC 8196
8FD6CD 8198
8FD6CE 819B
8FD6CF 819E
8FD6D0 81A2
8FD6D1 81AE
8FD6D2 81B2
8FD6D3 81B4
8FD6D4 81BB
8FD6D5 81CB
8FD6D6 81C3
8FD6D7 81C5
8FD6D8 81CA
8FD6D9 81CE
8FD6DA 81CF
8FD6DB 81D5
8FD6DC 81D7
8FD6DD 81DB
8FD6DE 81DD
8FD6DF 81DE
8FD6E0 81E1
8FD6E1 81E4
8FD6E2 81EB
8FD6E3 81EC
8FD6E4 81F0
8FD6E5 81F1
8FD6E6 81F2
8FD6E7 81F5
8FD6E8 81F6
8FD6E9 81F8
8FD6EA 81F9
8FD6EB 81FD
8FD6EC 81FF
8FD6ED 8200
8FD6EE 8203
8FD6EF 820F
8FD6F0 8213
8FD6F1 8214
8FD6F2 8219
8FD6F3 821A
8FD6F4 821D
8FD6F5 8221
8FD6F6 8222
8FD6F7 8228
8FD6F8 8232
8FD6F9 8234
8FD6FA 823A
8FD6FB 8243
8FD6FC 8244
8FD6FD 8245
8FD6FE 8246
8FD7A1 824B
8FD7A2 824E
8FD7A3 824F
8FD7A4 8251
8FD7A5 8256
8FD7A6 825C
8FD7A7 8260
8FD7A8 8263
8FD7A9 8267
8FD7AA 826D
8FD7AB 8274
8FD7AC 827B
8FD7AD 827D
8FD7AE 827F
8FD7AF 8280
8FD7B0 8281
8FD7B1 8283
8FD7B2 8284
8FD7B3 8287
8FD7B4 8289
8FD7B5 828A
8FD7B6 828E
8FD7B7 8291
8FD7B8 8294
8FD7B9 8296
8FD7BA 8298
8FD7BB 829A
8FD7BC 829B
8FD7BD 82A0
8FD7BE 82A1
8FD7BF 82A3
8FD7C0 82A4
8FD7C1 82A7
8FD7C2 82A8
8FD7C3 82A9
8FD7C4 82AA
8FD7C5 82AE
8FD7C6 82B0
8FD7C7 82B2
8FD7C8 82B4
8FD7C9 82B7
8FD7CA 82BA
8FD7CB 82BC
8FD7CC 82BE
8FD7CD 82BF
8FD7CE 82C6
8FD7CF 82D0
8FD7D0 82D5
8FD7D1 82DA
8FD7D2 82E0
8FD7D3 82E2
8FD7D4 82E4
8FD7D5 82E8
8FD7D6 82EA
8FD7D7 82ED
8FD7D8 82EF
8FD7D9 82F6
8FD7DA 82F7
8FD7DB 82FD
8FD7DC 82FE
8FD7DD 8300
8FD7DE 8301
8FD7DF 8307
8FD7E0 8308
8FD7E1 830A
8FD7E2 830B
8FD7E3 8354
8FD7E4 831B
8FD7E5 831D
8FD7E6 831E
8FD7E7 831F
8FD7E8 8321
8FD7E9 8322
8FD7EA 832C
8FD7EB 832D
8FD7EC 832E
8FD7ED 8330
8FD7EE 8333
8FD7EF 8337
8FD7F0 833A
8FD7F1 833C
8FD7F2 833D
8FD7F3 8342
8FD7F4 8343
8FD7F5 8344
8FD7F6 8347
8FD7F7 834D
8FD7F8 834E
8FD7F9 8351
8FD7FA 8355
8FD7FB 8356
8FD7FC 8357
8FD7FD 8370
8FD7FE 8378
8FD8A1 837D
8FD8A2 837F
8FD8A3 8380
8FD8A4 8382
8FD8A5 8384
8FD8A6 8386
8FD8A7 838D
8FD8A8 8392
8FD8A9 8394
8FD8AA 8395
8FD8AB 8398
8FD8AC 8399
8FD8AD 839B
8FD8AE 839C
8FD8AF 839D
8FD8B0 83A6
8FD8B1 83A7
8FD8B2 83A9
8FD8B3 83AC
8FD8B4 83BE
8FD8B5 83BF
8FD8B6 83C0
8FD8B7 83C7
8FD8B8 83C9
8FD8B9 83CF
8FD8BA 83D0
8FD8BB 83D1
8FD8BC 83D4
8FD8BD 83DD
8FD8BE 8353
8FD8BF 83E8
8FD8C0 83EA
8FD8C1 83F6
8FD8C2 83F8
8FD8C3 83F9
8FD8C4 83FC
8FD8C5 8401
8FD8C6 8406
8FD8C7 840A
8FD8C8 840F
8FD8C9 8411
8FD8CA 8415
8FD8CB 8419
8FD8CC 83AD
8FD8CD 842F
8FD8CE 8439
8FD8CF 8445
8FD8D0 8447
8FD8D1 8448
8FD8D2 844A
8FD8D3 844D
8FD8D4 844F
8FD8D5 8451
8FD8D6 8452
8FD8D7 8456
8FD8D8 8458
8FD8D9 8459
8FD8DA 845A
8FD8DB 845C
8FD8DC 8460
8FD8DD 8464
8FD8DE 8465
8FD8DF 8467
8FD8E0 846A
8FD8E1 8470
8FD8E2 8473
8FD8E3 8474
8FD8E4 8476
8FD8E5 8478
8FD8E6 847C
8FD8E7 847D
8FD8E8 8481
8FD8E9 8485
8FD8EA 8492
8FD8EB 8493
8FD8EC 8495
8FD8ED 849E
8FD8EE 84A6
8FD8EF 84A8
8FD8F0 84A9
8FD8F1 84AA
8FD8F2 84AF
8FD8F3 84B1
8FD8F4 84B4
8FD8F5 84BA
8FD8F6 84BD
8FD8F7 84BE
8FD8F8 84C0
8FD8F9 84C2
8FD8FA 84C7
8FD8FB 84C8
8FD8FC 84CC
8FD8FD 84CF
8FD8FE 84D3
8FD9A1 84DC
8FD9A2 84E7
8FD9A3 84EA
8FD9A4 84EF
8FD9A5 84F0
8FD9A6 84F1
8FD9A7 84F2
8FD9A8 84F7
8FD9A9 8532
8FD9AA 84FA
8FD9AB 84FB
8FD9AC 84FD
8FD9AD 8502
8FD9AE 8503
8FD9AF 8507
8FD9B0 850C
8FD9B1 850E
8FD9B2 8510
8FD9B3 851C
8FD9B4 851E
8FD9B5 8522
8FD9B6 8523
8FD9B7 8524
8FD9B8 8525
8FD9B9 8527
8FD9BA 852A
8FD9BB 852B
8FD9BC 852F
8FD9BD 8533
8FD9BE 8534
8FD9BF 8536
8FD9C0 853F
8FD9C1 8546
8FD9C2 854F
8FD9C3 8550
8FD9C4 8551
8FD9C5 8552
8FD9C6 8553
8FD9C7 8556
8FD9C8 8559
8FD9C9 855C
8FD9CA 855D
8FD9CB 855E
8FD9CC 855F
8FD9CD 8560
8FD9CE 8561
8FD9CF 8562
8FD9D0 8564
8FD9D1 856B
8FD9D2 856F
8FD9D3 8579
8FD9D4 857A
8FD9D5 857B
8FD9D6 857D
8FD9D7 857F
8FD9D8 8581
8FD9D9 8585
8FD9DA 8586
8FD9DB 8589
8FD9DC 858B
8FD9DD 858C
8FD9DE 858F
8FD9DF 8593
8FD9E0 8598
8FD9E1 859D
8FD9E2 859F
8FD9E3 85A0
8FD9E4 85A2
8FD9E5 85A5
8FD9E6 85A7
8FD9E7 85B4
8FD9E8 85B6
8FD9E9 85B7
8FD9EA 85B8
8FD9EB 85BC
8FD9EC 85BD
8FD9ED 85BE
8FD9EE 85BF
8FD9EF 85C2
8FD9F0 85C7
8FD9F1 85CA
8FD9F2 85CB
8FD9F3 85CE
8FD9F4 85AD
8FD9F5 85D8
8FD9F6 85DA
8FD9F7 85DF
8FD9F8 85E0
8FD9F9 85E6
8FD9FA 85E8
8FD9FB 85ED
8FD9FC 85F3
8FD9FD 85F6
8FD9FE 85FC
8FDAA1 85FF
8FDAA2 8600
8FDAA3 8604
8FDAA4 8605
8FDAA5 860D
8FDAA6 860E
8FDAA7 8610
8FDAA8 8611
8FDAA9 8612
8FDAAA 8618
8FDAAB 8619
8FDAAC 861B
8FDAAD 861E
8FDAAE 8621
8FDAAF 8627
8FDAB0 8629
8FDAB1 8636
8FDAB2 8638
8FDAB3 863A
8FDAB4 863C
8FDAB5 863D
8FDAB6 8640
8FDAB7 8642
8FDAB8 8646
8FDAB9 8652
8FDABA 8653
8FDABB 8656
8FDABC 8657
8FDABD 8658
8FDABE 8659
8FDABF 865D
8FDAC0 8660
8FDAC1 8661
8FDAC2 8662
8FDAC3 8663
8FDAC4 8664
8FDAC5 8669
8FDAC6 866C
8FDAC7 866F
8FDAC8 8675
8FDAC9 8676
8FDACA 8677
8FDACB 867A
8FDACC 868D
8FDACD 8691
8FDACE 8696
8FDACF 8698
8FDAD0 869A
8FDAD1 869C
8FDAD2 86A1
8FDAD3 86A6
8FDAD4 86A7
8FDAD5 86A8
8FDAD6 86AD
8FDAD7 86B1
8FDAD8 86B3
8FDAD9 86B4
8FDADA 86B5
8FDADB 86B7
8FDADC 86B8
8FDADD 86B9
8FDADE 86BF
8FDADF 86C0
8FDAE0 86C1
8FDAE1 86C3
8FDAE2 86C5
8FDAE3 86D1
8FDAE4 86D2
8FDAE5 86D5
8FDAE6 86D7
8FDAE7 86DA
8FDAE8 86DC
8FDAE9 86E0
8FDAEA 86E3
8FDAEB 86E5
8FDAEC 86E7
8FDAED 8688
8FDAEE 86FA
8FDAEF 86FC
8FDAF0 86FD
8FDAF1 8704
8FDAF2 8705
8FDAF3 8707
8FDAF4 870B
8FDAF5 870E
8FDAF6 870F
8FDAF7 8710
8FDAF8 8713
8FDAF9 8714
8FDAFA 8719
8FDAFB 871E
8FDAFC 871F
8FDAFD 8721
8FDAFE 8723
8FDBA1 8728
8FDBA2 872E
8FDBA3 872F
8FDBA4 8731
8FDBA5 8732
8FDBA6 8739
8FDBA7 873A
8FDBA8 873C
8FDBA9 873D
8FDBAA 873E
8FDBAB 8740
8FDBAC 8743
8FDBAD 8745
8FDBAE 874D
8FDBAF 8758
8FDBB0 875D
8FDBB1 8761
8FDBB2 8764
8FDBB3 8765
8FDBB4 876F
8FDBB5 8771
8FDBB6 8772
8FDBB7 877B
8FDBB8 8783
8FDBB9 8784
8FDBBA 8785
8FDBBB 8786
8FDBBC 8787
8FDBBD 8788
8FDBBE 8789
8FDBBF 878B
8FDBC0 878C
8FDBC1 8790
8FDBC2 8793
8FDBC3 8795
8FDBC4 8797
8FDBC5 8798
8FDBC6 8799
8FDBC7 879E
8FDBC8 87A0
8FDBC9 87A3
8FDBCA 87A7
8FDBCB 87AC
8FDBCC 87AD
8FDBCD 87AE
8FDBCE 87B1
8FDBCF 87B5
8FDBD0 87BE
8FDBD1 87BF
8FDBD2 87C1
8FDBD3 87C8
8FDBD4 87C9
8FDBD5 87CA
8FDBD6 87CE
8FDBD7 87D5
8FDBD8 87D6
8FDBD9 87D9
8FDBDA 87DA
8FDBDB 87DC
8FDBDC 87DF
8FDBDD 87E2
8FDBDE 87E3
8FDBDF 87E4
8FDBE0 87EA
8FDBE1 87EB
8FDBE2 87ED
8FDBE3 87F1
8FDBE4 87F3
8FDBE5 87F8
8FDBE6 87FA
8FDBE7 87FF
8FDBE8 8801
8FDBE9 8803
8FDBEA 8806
8FDBEB 8809
8FDBEC 880A
8FDBED 880B
8FDBEE 8810
8FDBEF 8819
8FDBF0 8812
8FDBF1 8813
8FDBF2 8814
8FDBF3 8818
8FDBF4 881A
8FDBF5 881B
8FDBF6 881C
8FDBF7 881E
8FDBF8 881F
8FDBF9 8828
8FDBFA 882D
8FDBFB 882E
8FDBFC 8830
8FDBFD 8832
8FDBFE 8835
8FDCA1 883A
8FDCA2 883C
8FDCA3 8841
8FDCA4 8843
8FDCA5 8845
8FDCA6 8848
8FDCA7 8849
8FDCA8 884A
8FDCA9 884B
8FDCAA 884E
8FDCAB 8851
8FDCAC 8855
8FDCAD 8856
8FDCAE 8858
8FDCAF 885A
8FDCB0 885C
8FDCB1 885F
8FDCB2 8860
8FDCB3 8864
8FDCB4 8869
8FDCB5 8871
8FDCB6 8879
8FDCB7 887B
8FDCB8 8880
8FDCB9 8898
8FDCBA 889A
8FDCBB 889B
8FDCBC 889C
8FDCBD 889F
8FDCBE 88A0
8FDCBF 88A8
8FDCC0 88AA
8FDCC1 88BA
8FDCC2 88BD
8FDCC3 88BE
8FDCC4 88C0
8FDCC5 88CA
8FDCC6 88CB
8FDCC7 88CC
8FDCC8 88CD
8FDCC9 88CE
8FDCCA 88D1
8FDCCB 88D2
8FDCCC 88D3
8FDCCD 88DB
8FDCCE 88DE
8FDCCF 88E7
8FDCD0 88EF
8FDCD1 88F0
8FDCD2 88F1
8FDCD3 88F5
8FDCD4 88F7
8FDCD5 8901
8FDCD6 8906
8FDCD7 890D
8FDCD8 890E
8FDCD9 890F
8FDCDA 8915
8FDCDB 8916
8FDCDC 8918
8FDCDD 8919
8FDCDE 891A
8FDCDF 891C
8FDCE0 8920
8FDCE1 8926
8FDCE2 8927
8FDCE3 8928
8FDCE4 8930
8FDCE5 8931
8FDCE6 8932
8FDCE7 8935
8FDCE8 8939
8FDCE9 893A
8FDCEA 893E
8FDCEB 8940
8FDCEC 8942
8FDCED 8945
8FDCEE 8946
8FDCEF 8949
8FDCF0 894F
8FDCF1 8952
8FDCF2 8957
8FDCF3 895A
8FDCF4 895B
8FDCF5 895C
8FDCF6 8961
8FDCF7 8962
8FDCF8 8963
8FDCF9 896B
8FDCFA 896E
8FDCFB 8970
8FDCFC 8973
8FDCFD 8975
8FDCFE 897A
8FDDA1 897B
8FDDA2 897C
8FDDA3 897D
8FDDA4 8989
8FDDA5 898D
8FDDA6 8990
8FDDA7 8994
8FDDA8 8995
8FDDA9 899B
8FDDAA 899C
8FDDAB 899F
8FDDAC 89A0
8FDDAD 89A5
8FDDAE 89B0
8FDDAF 89B4
8FDDB0 89B5
8FDDB1 89B6
8FDDB2 89B7
8FDDB3 89BC
8FDDB4 89D4
8FDDB5 89D5
8FDDB6 89D6
8FDDB7 89D7
8FDDB8 89D8
8FDDB9 89E5
8FDDBA 89E9
8FDDBB 89EB
8FDDBC 89ED
8FDDBD 89F1
8FDDBE 89F3
8FDDBF 89F6
8FDDC0 89F9
8FDDC1 89FD
8FDDC2 89FF
8FDDC3 8A04
8FDDC4 8A05
8FDDC5 8A07
8FDDC6 8A0F
8FDDC7 8A11
8FDDC8 8A12
8FDDC9 8A14
8FDDCA 8A15
8FDDCB 8A1E
8FDDCC 8A20
8FDDCD 8A22
8FDDCE 8A24
8FDDCF 8A26
8FDDD0 8A2B
8FDDD1 8A2C
8FDDD2 8A2F
8FDDD3 8A35
8FDDD4 8A37
8FDDD5 8A3D
8FDDD6 8A3E
8FDDD7 8A40
8FDDD8 8A43
8FDDD9 8A45
8FDDDA 8A47
8FDDDB 8A49
8FDDDC 8A4D
8FDDDD 8A4E
8FDDDE 8A53
8FDDDF 8A56
8FDDE0 8A57
8FDDE1 8A58
8FDDE2 8A5C
8FDDE3 8A5D
8FDDE4 8A61
8FDDE5 8A65
8FDDE6 8A67
8FDDE7 8A75
8FDDE8 8A76
8FDDE9 8A77
8FDDEA 8A79
8FDDEB 8A7A
8FDDEC 8A7B
8FDDED 8A7E
8FDDEE 8A7F
8FDDEF 8A80
8FDDF0 8A83
8FDDF1 8A86
8FDDF2 8A8B
8FDDF3 8A8F
8FDDF4 8A90
8FDDF5 8A92
8FDDF6 8A96
8FDDF7 8A97
8FDDF8 8A99
8FDDF9 8A9F
8FDDFA 8AA7
8FDDFB 8AA9
8FDDFC 8AAE
8FDDFD 8AAF
8FDDFE 8AB3
8FDEA1 8AB6
8FDEA2 8AB7
8FDEA3 8ABB
8FDEA4 8ABE
8FDEA5 8AC3
8FDEA6 8AC6
8FDEA7 8AC8
8FDEA8 8AC9
8FDEA9 8ACA
8FDEAA 8AD1
8FDEAB 8AD3
8FDEAC 8AD4
8FDEAD 8AD5
8FDEAE 8AD7
8FDEAF 8ADD
8FDEB0 8ADF
8FDEB1 8AEC
8FDEB2 8AF0
8FDEB3 8AF4
8FDEB4 8AF5
8FDEB5 8AF6
8FDEB6 8AFC
8FDEB7 8AFF
8FDEB8 8B05
8FDEB9 8B06
8FDEBA 8B0B
8FDEBB 8B11
8FDEBC 8B1C
8FDEBD 8B1E
8FDEBE 8B1F
8FDEBF 8B0A
8FDEC0 8B2D
8FDEC1 8B30
8FDEC2 8B37
8FDEC3 8B3C
8FDEC4 8B42
8FDEC5 8B43
8FDEC6 8B44
8FDEC7 8B45
8FDEC8 8B46
8FDEC9 8B48
8FDECA 8B52
8FDECB 8B53
8FDECC 8B54
8FDECD 8B59
8FDECE 8B4D
8FDECF 8B5E
8FDED0 8B63
8FDED1 8B6D
8FDED2 8B76
8FDED3 8B78
8FDED4 8B79
8FDED5 8B7C
8FDED6 8B7E
8FDED7 8B81
8FDED8 8B84
8FDED9 8B85
8FDEDA 8B8B
8FDEDB 8B8D
8FDEDC 8B8F
8FDEDD 8B94
8FDEDE 8B95
8FDEDF 8B9C
8FDEE0 8B9E
8FDEE1 8B9F
8FDEE2 8C38
8FDEE3 8C39
8FDEE4 8C3D
8FDEE5 8C3E
8FDEE6 8C45
8FDEE7 8C47
8FDEE8 8C49
8FDEE9 8C4B
8FDEEA 8C4F
8FDEEB 8C51
8FDEEC 8C53
8FDEED 8C54
8FDEEE 8C57
8FDEEF 8C58
8FDEF0 8C5B
8FDEF1 8C5D
8FDEF2 8C59
8FDEF3 8C63
8FDEF4 8C64
8FDEF5 8C66
8FDEF6 8C68
8FDEF7 8C69
8FDEF8 8C6D
8FDEF9 8C73
8FDEFA 8C75
8FDEFB 8C76
8FDEFC 8C7B
8FDEFD 8C7E
8FDEFE 8C86
8FDFA1 8C87
8FDFA2 8C8B
8FDFA3 8C90
8FDFA4 8C92
8FDFA5 8C93
8FDFA6 8C99
8FDFA7 8C9B
8FDFA8 8C9C
8FDFA9 8CA4
8FDFAA 8CB9
8FDFAB 8CBA
8FDFAC 8CC5
8FDFAD 8CC6
8FDFAE 8CC9
8FDFAF 8CCB
8FDFB0 8CCF
8FDFB1 8CD6
8FDFB2 8CD5
8FDFB3 8CD9
8FDFB4 8CDD
8FDFB5 8CE1
8FDFB6 8CE8
8FDFB7 8CEC
8FDFB8 8CEF
8FDFB9 8CF0
8FDFBA 8CF2
8FDFBB 8CF5
8FDFBC 8CF7
8FDFBD 8CF8
8FDFBE 8CFE
8FDFBF 8CFF
8FDFC0 8D01
8FDFC1 8D03
8FDFC2 8D09
8FDFC3 8D12
8FDFC4 8D17
8FDFC5 8D1B
8FDFC6 8D65
8FDFC7 8D69
8FDFC8 8D6C
8FDFC9 8D6E
8FDFCA 8D7F
8FDFCB 8D82
8FDFCC 8D84
8FDFCD 8D88
8FDFCE 8D8D
8FDFCF 8D90
8FDFD0 8D91
8FDFD1 8D95
8FDFD2 8D9E
8FDFD3 8D9F
8FDFD4 8DA0
8FDFD5 8DA6
8FDFD6 8DAB
8FDFD7 8DAC
8FDFD8 8DAF
8FDFD9 8DB2
8FDFDA 8DB5
8FDFDB 8DB7
8FDFDC 8DB9
8FDFDD 8DBB
8FDFDE 8DC0
8FDFDF 8DC5
8FDFE0 8DC6
8FDFE1 8DC7
8FDFE2 8DC8
8FDFE3 8DCA
8FDFE4 8DCE
8FDFE5 8DD1
8FDFE6 8DD4
8FDFE7 8DD5
8FDFE8 8DD7
8FDFE9 8DD9
8FDFEA 8DE4
8FDFEB 8DE5
8FDFEC 8DE7
8FDFED 8DEC
8FDFEE 8DF0
8FDFEF 8DBC
8FDFF0 8DF1
8FDFF1 8DF2
8FDFF2 8DF4
8FDFF3 8DFD
8FDFF4 8E01
8FDFF5 8E04
8FDFF6 8E05
8FDFF7 8E06
8FDFF8 8E0B
8FDFF9 8E11
8FDFFA 8E14
8FDFFB 8E16
8FDFFC 8E20
8FDFFD 8E21
8FDFFE 8E22
8FE0A1 8E23
8FE0A2 8E26
8FE0A3 8E27
8FE0A4 8E31
8FE0A5 8E33
8FE0A6 8E36
8FE0A7 8E37
8FE0A8 8E38
8FE0A9 8E39
8FE0AA 8E3D
8FE0AB 8E40
8FE0AC 8E41
8FE0AD 8E4B
8FE0AE 8E4D
8FE0AF 8E4E
8FE0B0 8E4F
8FE0B1 8E54
8FE0B2 8E5B
8FE0B3 8E5C
8FE0B4 8E5D
8FE0B5 8E5E
8FE0B6 8E61
8FE0B7 8E62
8FE0B8 8E69
8FE0B9 8E6C
8FE0BA 8E6D
8FE0BB 8E6F
8FE0BC 8E70
8FE0BD 8E71
8FE0BE 8E79
8FE0BF 8E7A
8FE0C0 8E7B
8FE0C1 8E82
8FE0C2 8E83
8FE0C3 8E89
8FE0C4 8E90
8FE0C5 8E92
8FE0C6 8E95
8FE0C7 8E9A
8FE0C8 8E9B
8FE0C9 8E9D
8FE0CA 8E9E
8FE0CB 8EA2
8FE0CC 8EA7
8FE0CD 8EA9
8FE0CE 8EAD
8FE0CF 8EAE
8FE0D0 8EB3
8FE0D1 8EB5
8FE0D2 8EBA
8FE0D3 8EBB
8FE0D4 8EC0
8FE0D5 8EC1
8FE0D6 8EC3
8FE0D7 8EC4
8FE0D8 8EC7
8FE0D9 8ECF
8FE0DA 8ED1
8FE0DB 8ED4
8FE0DC 8EDC
8FE0DD 8EE8
8FE0DE 8EEE
8FE0DF 8EF0
8FE0E0 8EF1
8FE0E1 8EF7
8FE0E2 8EF9
8FE0E3 8EFA
8FE0E4 8EED
8FE0E5 8F00
8FE0E6 8F02
8FE0E7 8F07
8FE0E8 8F08
8FE0E9 8F0F
8FE0EA 8F10
8FE0EB 8F16
8FE0EC 8F17
8FE0ED 8F18
8FE0EE 8F1E
8FE0EF 8F20
8FE0F0 8F21
8FE0F1 8F23
8FE0F2 8F25
8FE0F3 8F27
8FE0F4 8F28
8FE0F5 8F2C
8FE0F6 8F2D
8FE0F7 8F2E
8FE0F8 8F34
8FE0F9 8F35
8FE0FA 8F36
8FE0FB 8F37
8FE0FC 8F3A
8FE0FD 8F40
8FE0FE 8F41
8FE1A1 8F43
8FE1A2 8F47
8FE1A3 8F4F
8FE1A4 8F51
8FE1A5 8F52
8FE1A6 8F53
8FE1A7 8F54
8FE1A8 8F55
8FE1A9 8F58
8FE1AA 8F5D
8FE1AB 8F5E
8FE1AC 8F65
8FE1AD 8F9D
8FE1AE 8FA0
8FE1AF 8FA1
8FE1B0 8FA4
8FE1B1 8FA5
8FE1B2 8FA6
8FE1B3 8FB5
8FE1B4 8FB6
8FE1B5 8FB8
8FE1B6 8FBE
8FE1B7 8FC0
8FE1B8 8FC1
8FE1B9 8FC6
8FE1BA 8FCA
8FE1BB 8FCB
8FE1BC 8FCD
8FE1BD 8FD0
8FE1BE 8FD2
8FE1BF 8FD3
8FE1C0 8FD5
8FE1C1 8FE0
8FE1C2 8FE3
8FE1C3 8FE4
8FE1C4 8FE8
8FE1C5 8FEE
8FE1C6 8FF1
8FE1C7 8FF5
8FE1C8 8FF6
8FE1C9 8FFB
8FE1CA 8FFE
8FE1CB 9002
8FE1CC 9004
8FE1CD 9008
8FE1CE 900C
8FE1CF 9018
8FE1D0 901B
8FE1D1 9028
8FE1D2 9029
8FE1D3 902F
8FE1D4 902A
8FE1D5 902C
8FE1D6 902D
8FE1D7 9033
8FE1D8 9034
8FE1D9 9037
8FE1DA 903F
8FE1DB 9043
8FE1DC 9044
8FE1DD 904C
8FE1DE 905B
8FE1DF 905D
8FE1E0 9062
8FE1E1 9066
8FE1E2 9067
8FE1E3 906C
8FE1E4 9070
8FE1E5 9074
8FE1E6 9079
8FE1E7 9085
8FE1E8 9088
8FE1E9 908B
8FE1EA 908C
8FE1EB 908E
8FE1EC 9090
8FE1ED 9095
8FE1EE 9097
8FE1EF 9098
8FE1F0 9099
8FE1F1 909B
8FE1F2 90A0
8FE1F3 90A1
8FE1F4 90A2
8FE1F5 90A5
8FE1F6 90B0
8FE1F7 90B2
8FE1F8 90B3
8FE1F9 90B4
8FE1FA 90B6
8FE1FB 90BD
8FE1FC 90CC
8FE1FD 90BE
8FE1FE 90C3
8FE2A1 90C4
8FE2A2 90C5
8FE2A3 90C7
8FE2A4 90C8
8FE2A5 90D5
8FE2A6 90D7
8FE2A7 90D8
8FE2A8 90D9
8FE2A9 90DC
8FE2AA 90DD
8FE2AB 90DF
8FE2AC 90E5
8FE2AD 90D2
8FE2AE 90F6
8FE2AF 90EB
8FE2B0 90EF
8FE2B1 90F0
8FE2B2 90F4
8FE2B3 90FE
8FE2B4 90FF
8FE2B5 9100
8FE2B6 9104
8FE2B7 9105
8FE2B8 9106
8FE2B9 9108
8FE2BA 910D
8FE2BB 9110
8FE2BC 9114
8FE2BD 9116
8FE2BE 9117
8FE2BF 9118
8FE2C0 911A
8FE2C1 911C
8FE2C2 911E
8FE2C3 9120
8FE2C4 9125
8FE2C5 9122
8FE2C6 9123
8FE2C7 9127
8FE2C8 9129
8FE2C9 912E
8FE2CA 912F
8FE2CB 9131
8FE2CC 9134
8FE2CD 9136
8FE2CE 9137
8FE2CF 9139
8FE2D0 913A
8FE2D1 913C
8FE2D2 913D
8FE2D3 9143
8FE2D4 9147
8FE2D5 9148
8FE2D6 914F
8FE2D7 9153
8FE2D8 9157
8FE2D9 9159
8FE2DA 915A
8FE2DB 915B
8FE2DC 9161
8FE2DD 9164
8FE2DE 9167
8FE2DF 916D
8FE2E0 9174
8FE2E1 9179
8FE2E2 917A
8FE2E3 917B
8FE2E4 9181
8FE2E5 9183
8FE2E6 9185
8FE2E7 9186
8FE2E8 918A
8FE2E9 918E
8FE2EA 9191
8FE2EB 9193
8FE2EC 9194
8FE2ED 9195
8FE2EE 9198
8FE2EF 919E
8FE2F0 91A1
8FE2F1 91A6
8FE2F2 91A8
8FE2F3 91AC
8FE2F4 91AD
8FE2F5 91AE
8FE2F6 91B0
8FE2F7 91B1
8FE2F8 91B2
8FE2F9 91B3
8FE2FA 91B6
8FE2FB 91BB
8FE2FC 91BC
8FE2FD 91BD
8FE2FE 91BF
8FE3A1 91C2
8FE3A2 91C3
8FE3A3 91C5
8FE3A4 91D3
8FE3A5 91D4
8FE3A6 91D7
8FE3A7 91D9
8FE3A8 91DA
8FE3A9 91DE
8FE3AA 91E4
8FE3AB 91E5
8FE3AC 91E9
8FE3AD 91EA
8FE3AE 91EC
8FE3AF 91ED
8FE3B0 91EE
8FE3B1 91EF
8FE3B2 91F0
8FE3B3 91F1
8FE3B4 91F7
8FE3B5 91F9
8FE3B6 91FB
8FE3B7 91FD
8FE3B8 9200
8FE3B9 9201
8FE3BA 9204
8FE3BB 9205
8FE3BC 9206
8FE3BD 9207
8FE3BE 9209
8FE3BF 920A
8FE3C0 920C
8FE3C1 9210
8FE3C2 9212
8FE3C3 9213
8FE3C4 9216
8FE3C5 9218
8FE3C6 921C
8FE3C7 921D
8FE3C8 9223
8FE3C9 9224
8FE3CA 9225
8FE3CB 9226
8FE3CC 9228
8FE3CD 922E
8FE3CE 922F
8FE3CF 9230
8FE3D0 9233
8FE3D1 9235
8FE3D2 9236
8FE3D3 9238
8FE3D4 9239
8FE3D5 923A
8FE3D6 923C
8FE3D7 923E
8FE3D8 9240
8FE3D9 9242
8FE3DA 9243
8FE3DB 9246
8FE3DC 9247
8FE3DD 924A
8FE3DE 924D
8FE3DF 924E
8FE3E0 924F
8FE3E1 9251
8FE3E2 9258
8FE3E3 9259
8FE3E4 925C
8FE3E5 925D
8FE3E6 9260
8FE3E7 9261
8FE3E8 9265
8FE3E9 9267
8FE3EA 9268
8FE3EB 9269
8FE3EC 926E
8FE3ED 926F
8FE3EE 9270
8FE3EF 9275
8FE3F0 9276
8FE3F1 9277
8FE3F2 9278
8FE3F3 9279
8FE3F4 927B
8FE3F5 927C
8FE3F6 927D
8FE3F7 927F
8FE3F8 9288
8FE3F9 9289
8FE3FA 928A
8FE3FB 928D
8FE3FC 928E
8FE3FD 9292
8FE3FE 9297
8FE4A1 9299
8FE4A2 929F
8FE4A3 92A0
8FE4A4 92A4
8FE4A5 92A5
8FE4A6 92A7
8FE4A7 92A8
8FE4A8 92AB
8FE4A9 92AF
8FE4AA 92B2
8FE4AB 92B6
8FE4AC 92B8
8FE4AD 92BA
8FE4AE 92BB
8FE4AF 92BC
8FE4B0 92BD
8FE4B1 92BF
8FE4B2 92C0
8FE4B3 92C1
8FE4B4 92C2
8FE4B5 92C3
8FE4B6 92C5
8FE4B7 92C6
8FE4B8 92C7
8FE4B9 92C8
8FE4BA 92CB
8FE4BB 92CC
8FE4BC 92CD
8FE4BD 92CE
8FE4BE 92D0
8FE4BF 92D3
8FE4C0 92D5
8FE4C1 92D7
8FE4C2 92D8
8FE4C3 92D9
8FE4C4 92DC
8FE4C5 92DD
8FE4C6 92DF
8FE4C7 92E0
8FE4C8 92E1
8FE4C9 92E3
8FE4CA 92E5
8FE4CB 92E7
8FE4CC 92E8
8FE4CD 92EC
8FE4CE 92EE
8FE4CF 92F0
8FE4D0 92F9
8FE4D1 92FB
8FE4D2 92FF
8FE4D3 9300
8FE4D4 9302
8FE4D5 9308
8FE4D6 930D
8FE4D7 9311
8FE4D8 9314
8FE4D9 9315
8FE4DA 931C
8FE4DB 931D
8FE4DC 931E
8FE4DD 931F
8FE4DE 9321
8FE4DF 9324
8FE4E0 9325
8FE4E1 9327
8FE4E2 9329
8FE4E3 932A
8FE4E4 9333
8FE4E5 9334
8FE4E6 9336
8FE4E7 9337
8FE4E8 9347
8FE4E9 9348
8FE4EA 9349
8FE4EB 9350
8FE4EC 9351
8FE4ED 9352
8FE4EE 9355
8FE4EF 9357
8FE4F0 9358
8FE4F1 935A
8FE4F2 935E
8FE4F3 9364
8FE4F4 9365
8FE4F5 9367
8FE4F6 9369
8FE4F7 936A
8FE4F8 936D
8FE4F9 936F
8FE4FA 9370
8FE4FB 9371
8FE4FC 9373
8FE4FD 9374
8FE4FE 9376
8FE5A1 937A
8FE5A2 937D
8FE5A3 937F
8FE5A4 9380
8FE5A5 9381
8FE5A6 9382
8FE5A7 9388
8FE5A8 938A
8FE5A9 938B
8FE5AA 938D
8FE5AB 938F
8FE5AC 9392
8FE5AD 9395
8FE5AE 9398
8FE5AF 939B
8FE5B0 939E
8FE5B1 93A1
8FE5B2 93A3
8FE5B3 93A4
8FE5B4 93A6
8FE5B5 93A8
8FE5B6 93AB
8FE5B7 93B4
8FE5B8 93B5
8FE5B9 93B6
8FE5BA 93BA
8FE5BB 93A9
8FE5BC 93C1
8FE5BD 93C4
8FE5BE 93C5
8FE5BF 93C6
8FE5C0 93C7
8FE5C1 93C9
8FE5C2 93CA
8FE5C3 93CB
8FE5C4 93CC
8FE5C5 93CD
8FE5C6 93D3
8FE5C7 93D9
8FE5C8 93DC
8FE5C9 93DE
8FE5CA 93DF
8FE5CB 93E2
8FE5CC 93E6
8FE5CD 93E7
8FE5CE 93F9
8FE5CF 93F7
8FE5D0 93F8
8FE5D1 93FA
8FE5D2 93FB
8FE5D3 93FD
8FE5D4 9401
8FE5D5 9402
8FE5D6 9404
8FE5D7 9408
8FE5D8 9409
8FE5D9 940D
8FE5DA 940E
8FE5DB 940F
8FE5DC 9415
8FE5DD 9416
8FE5DE 9417
8FE5DF 941F
8FE5E0 942E
8FE5E1 942F
8FE5E2 9431
8FE5E3 9432
8FE5E4 9433
8FE5E5 9434
8FE5E6 943B
8FE5E7 943F
8FE5E8 943D
8FE5E9 9443
8FE5EA 9445
8FE5EB 9448
8FE5EC 944A
8FE5ED 944C
8FE5EE 9455
8FE5EF 9459
8FE5F0 945C
8FE5F1 945F
8FE5F2 9461
8FE5F3 9463
8FE5F4 9468
8FE5F5 946B
8FE5F6 946D
8FE5F7 946E
8FE5F8 946F
8FE5F9 9471
8FE5FA 9472
8FE5FB 9484
8FE5FC 9483
8FE5FD 9578
8FE5FE 9579
8FE6A1 957E
8FE6A2 9584
8FE6A3 9588
8FE6A4 958C
8FE6A5 958D
8FE6A6 958E
8FE6A7 959D
8FE6A8 959E
8FE6A9 959F
8FE6AA 95A1
8FE6AB 95A6
8FE6AC 95A9
8FE6AD 95AB
8FE6AE 95AC
8FE6AF 95B4
8FE6B0 95B6
8FE6B1 95BA
8FE6B2 95BD
8FE6B3 95BF
8FE6B4 95C6
8FE6B5 95C8
8FE6B6 95C9
8FE6B7 95CB
8FE6B8 95D0
8FE6B9 95D1
8FE6BA 95D2
8FE6BB 95D3
8FE6BC 95D9
8FE6BD 95DA
8FE6BE 95DD
8FE6BF 95DE
8FE6C0 95DF
8FE6C1 95E0
8FE6C2 95E4
8FE6C3 95E6
8FE6C4 961D
8FE6C5 961E
8FE6C6 9622
8FE6C7 9624
8FE6C8 9625
8FE6C9 9626
8FE6CA 962C
8FE6CB 9631
8FE6CC 9633
8FE6CD 9637
8FE6CE 9638
8FE6CF 9639
8FE6D0 963A
8FE6D1 963C
8FE6D2 963D
8FE6D3 9641
8FE6D4 9652
8FE6D5 9654
8FE6D6 9656
8FE6D7 9657
8FE6D8 9658
8FE6D9 9661
8FE6DA 966E
8FE6DB 9674
8FE6DC 967B
8FE6DD 967C
8FE6DE 967E
8FE6DF 967F
8FE6E0 9681
8FE6E1 9682
8FE6E2 9683
8FE6E3 9684
8FE6E4 9689
8FE6E5 9691
8FE6E6 9696
8FE6E7 969A
8FE6E8 969D
8FE6E9 969F
8FE6EA 96A4
8FE6EB 96A5
8FE6EC 96A6
8FE6ED 96A9
8FE6EE 96AE
8FE6EF 96AF
8FE6F0 96B3
8FE6F1 96BA
8FE6F2 96CA
8FE6F3 96D2
8FE6F4 5DB2
8FE6F5 96D8
8FE6F6 96DA
8FE6F7 96DD
8FE6F8 96DE
8FE6F9 96DF
8FE6FA 96E9
8FE6FB 96EF
8FE6FC 96F1
8FE6FD 96FA
8FE6FE 9702
8FE7A1 9703
8FE7A2 9705
8FE7A3 9709
8FE7A4 971A
8FE7A5 971B
8FE7A6 971D
8FE7A7 9721
8FE7A8 9722
8FE7A9 9723
8FE7AA 9728
8FE7AB 9731
8FE7AC 9733
8FE7AD 9741
8FE7AE 9743
8FE7AF 974A
8FE7B0 974E
8FE7B1 974F
8FE7B2 9755
8FE7B3 9757
8FE7B4 9758
8FE7B5 975A
8FE7B6 975B
8FE7B7 9763
8FE7B8 9767
8FE7B9 976A
8FE7BA 976E
8FE7BB 9773
8FE7BC 9776
8FE7BD 9777
8FE7BE 9778
8FE7BF 977B
8FE7C0 977D
8FE7C1 977F
8FE7C2 9780
8FE7C3 9789
8FE7C4 9795
8FE7C5 9796
8FE7C6 9797
8FE7C7 9799
8FE7C8 979A
8FE7C9 979E
8FE7CA 979F
8FE7CB 97A2
8FE7CC 97AC
8FE7CD 97AE
8FE7CE 97B1
8FE7CF 97B2
8FE7D0 97B5
8FE7D1 97B6
8FE7D2 97B8
8FE7D3 97B9
8FE7D4 97BA
8FE7D5 97BC
8FE7D6 97BE
8FE7D7 97BF
8FE7D8 97C1
8FE7D9 97C4
8FE7DA 97C5
8FE7DB 97C7
8FE7DC 97C9
8FE7DD 97CA
8FE7DE 97CC
8FE7DF 97CD
8FE7E0 97CE
8FE7E1 97D0
8FE7E2 97D1
8FE7E3 97D4
8FE7E4 97D7
8FE7E5 97D8
8FE7E6 97D9
8FE7E7 97DD
8FE7E8 97DE
8FE7E9 97E0
8FE7EA 97DB
8FE7EB 97E1
8FE7EC 97E4
8FE7ED 97EF
8FE7EE 97F1
8FE7EF 97F4
8FE7F0 97F7
8FE7F1 97F8
8FE7F2 97FA
8FE7F3 9807
8FE7F4 980A
8FE7F5 9819
8FE7F6 980D
8FE7F7 980E
8FE7F8 9814
8FE7F9 9816
8FE7FA 981C
8FE7FB 981E
8FE7FC 9820
8FE7FD 9823
8FE7FE 9826
8FE8A1 982B
8FE8A2 982E
8FE8A3 982F
8FE8A4 9830
8FE8A5 9832
8FE8A6 9833
8FE8A7 9835
8FE8A8 9825
8FE8A9 983E
8FE8AA 9844
8FE8AB 9847
8FE8AC 984A
8FE8AD 9851
8FE8AE 9852
8FE8AF 9853
8FE8B0 9856
8FE8B1 9857
8FE8B2 9859
8FE8B3 985A
8FE8B4 9862
8FE8B5 9863
8FE8B6 9865
8FE8B7 9866
8FE8B8 986A
8FE8B9 986C
8FE8BA 98AB
8FE8BB 98AD
8FE8BC 98AE
8FE8BD 98B0
8FE8BE 98B4
8FE8BF 98B7
8FE8C0 98B8
8FE8C1 98BA
8FE8C2 98BB
8FE8C3 98BF
8FE8C4 98C2
8FE8C5 98C5
8FE8C6 98C8
8FE8C7 98CC
8FE8C8 98E1
8FE8C9 98E3
8FE8CA 98E5
8FE8CB 98E6
8FE8CC 98E7
8FE8CD 98EA
8FE8CE 98F3
8FE8CF 98F6
8FE8D0 9902
8FE8D1 9907
8FE8D2 9908
8FE8D3 9911
8FE8D4 9915
8FE8D5 9916
8FE8D6 9917
8FE8D7 991A
8FE8D8 991B
8FE8D9 991C
8FE8DA 991F
8FE8DB 9922
8FE8DC 9926
8FE8DD 9927
8FE8DE 992B
8FE8DF 9931
8FE8E0 9932
8FE8E1 9933
8FE8E2 9934
8FE8E3 9935
8FE8E4 9939
8FE8E5 993A
8FE8E6 993B
8FE8E7 993C
8FE8E8 9940
8FE8E9 9941
8FE8EA 9946
8FE8EB 9947
8FE8EC 9948
8FE8ED 994D
8FE8EE 994E
8FE8EF 9954
8FE8F0 9958
8FE8F1 9959
8FE8F2 995B
8FE8F3 995C
8FE8F4 995E
8FE8F5 995F
8FE8F6 9960
8FE8F7 999B
8FE8F8 999D
8FE8F9 999F
8FE8FA 99A6
8FE8FB 99B0
8FE8FC 99B1
8FE8FD 99B2
8FE8FE 99B5
8FE9A1 99B9
8FE9A2 99BA
8FE9A3 99BD
8FE9A4 99BF
8FE9A5 99C3
8FE9A6 99C9
8FE9A7 99D3
8FE9A8 99D4
8FE9A9 99D9
8FE9AA 99DA
8FE9AB 99DC
8FE9AC 99DE
8FE9AD 99E7
8FE9AE 99EA
8FE9AF 99EB
8FE9B0 99EC
8FE9B1 99F0
8FE9B2 99F4
8FE9B3 99F5
8FE9B4 99F9
8FE9B5 99FD
8FE9B6 99FE
8FE9B7 9A02
8FE9B8 9A03
8FE9B9 9A04
8FE9BA 9A0B
8FE9BB 9A0C
8FE9BC 9A10
8FE9BD 9A11
8FE9BE 9A16
8FE9BF 9A1E
8FE9C0 9A20
8FE9C1 9A22
8FE9C2 9A23
8FE9C3 9A24
8FE9C4 9A27
8FE9C5 9A2D
8FE9C6 9A2E
8FE9C7 9A33
8FE9C8 9A35
8FE9C9 9A36
8FE9CA 9A38
8FE9CB 9A47
8FE9CC 9A41
8FE9CD 9A44
8FE9CE 9A4A
8FE9CF 9A4B
8FE9D0 9A4C
8FE9D1 9A4E
8FE9D2 9A51
8FE9D3 9A54
8FE9D4 9A56
8FE9D5 9A5D
8FE9D6 9AAA
8FE9D7 9AAC
8FE9D8 9AAE
8FE9D9 9AAF
8FE9DA 9AB2
8FE9DB 9AB4
8FE9DC 9AB5
8FE9DD 9AB6
8FE9DE 9AB9
8FE9DF 9ABB
8FE9E0 9ABE
8FE9E1 9ABF
8FE9E2 9AC1
8FE9E3 9AC3
8FE9E4 9AC6
8FE9E5 9AC8
8FE9E6 9ACE
8FE9E7 9AD0
8FE9E8 9AD2
8FE9E9 9AD5
8FE9EA 9AD6
8FE9EB 9AD7
8FE9EC 9ADB
8FE9ED 9ADC
8FE9EE 9AE0
8FE9EF 9AE4
8FE9F0 9AE5
8FE9F1 9AE7
8FE9F2 9AE9
8FE9F3 9AEC
8FE9F4 9AF2
8FE9F5 9AF3
8FE9F6 9AF5
8FE9F7 9AF9
8FE9F8 9AFA
8FE9F9 9AFD
8FE9FA 9AFF
8FE9FB 9B00
8FE9FC 9B01
8FE9FD 9B02
8FE9FE 9B03
8FEAA1 9B04
8FEAA2 9B05
8FEAA3 9B08
8FEAA4 9B09
8FEAA5 9B0B
8FEAA6 9B0C
8FEAA7 9B0D
8FEAA8 9B0E
8FEAA9 9B10
8FEAAA 9B12
8FEAAB 9B16
8FEAAC 9B19
8FEAAD 9B1B
8FEAAE 9B1C
8FEAAF 9B20
8FEAB0 9B26
8FEAB1 9B2B
8FEAB2 9B2D
8FEAB3 9B33
8FEAB4 9B34
8FEAB5 9B35
8FEAB6 9B37
8FEAB7 9B39
8FEAB8 9B3A
8FEAB9 9B3D
8FEABA 9B48
8FEABB 9B4B
8FEABC 9B4C
8FEABD 9B55
8FEABE 9B56
8FEABF 9B57
8FEAC0 9B5B
8FEAC1 9B5E
8FEAC2 9B61
8FEAC3 9B63
8FEAC4 9B65
8FEAC5 9B66
8FEAC6 9B68
8FEAC7 9B6A
8FEAC8 9B6B
8FEAC9 9B6C
8FEACA 9B6D
8FEACB 9B6E
8FEACC 9B73
8FEACD 9B75
8FEACE 9B77
8FEACF 9B78
8FEAD0 9B79
8FEAD1 9B7F
8FEAD2 9B80
8FEAD3 9B84
8FEAD4 9B85
8FEAD5 9B86
8FEAD6 9B87
8FEAD7 9B89
8FEAD8 9B8A
8FEAD9 9B8B
8FEADA 9B8D
8FEADB 9B8F
8FEADC 9B90
8FEADD 9B94
8FEADE 9B9A
8FEADF 9B9D
8FEAE0 9B9E
8FEAE1 9BA6
8FEAE2 9BA7
8FEAE3 9BA9
8FEAE4 9BAC
8FEAE5 9BB0
8FEAE6 9BB1
8FEAE7 9BB2
8FEAE8 9BB7
8FEAE9 9BB8
8FEAEA 9BBB
8FEAEB 9BBC
8FEAEC 9BBE
8FEAED 9BBF
8FEAEE 9BC1
8FEAEF 9BC7
8FEAF0 9BC8
8FEAF1 9BCE
8FEAF2 9BD0
8FEAF3 9BD7
8FEAF4 9BD8
8FEAF5 9BDD
8FEAF6 9BDF
8FEAF7 9BE5
8FEAF8 9BE7
8FEAF9 9BEA
8FEAFA 9BEB
8FEAFB 9BEF
8FEAFC 9BF3
8FEAFD 9BF7
8FEAFE 9BF8
8FEBA1 9BF9
8FEBA2 9BFA
8FEBA3 9BFD
8FEBA4 9BFF
8FEBA5 9C00
8FEBA6 9C02
8FEBA7 9C0B
8FEBA8 9C0F
8FEBA9 9C11
8FEBAA 9C16
8FEBAB 9C18
8FEBAC 9C19
8FEBAD 9C1A
8FEBAE 9C1C
8FEBAF 9C1E
8FEBB0 9C22
8FEBB1 9C23
8FEBB2 9C26
8FEBB3 9C27
8FEBB4 9C28
8FEBB5 9C29
8FEBB6 9C2A
8FEBB7 9C31
8FEBB8 9C35
8FEBB9 9C36
8FEBBA 9C37
8FEBBB 9C3D
8FEBBC 9C41
8FEBBD 9C43
8FEBBE 9C44
8FEBBF 9C45
8FEBC0 9C49
8FEBC1 9C4A
8FEBC2 9C4E
8FEBC3 9C4F
8FEBC4 9C50
8FEBC5 9C53
8FEBC6 9C54
8FEBC7 9C56
8FEBC8 9C58
8FEBC9 9C5B
8FEBCA 9C5D
8FEBCB 9C5E
8FEBCC 9C5F
8FEBCD 9C63
8FEBCE 9C69
8FEBCF 9C6A
8FEBD0 9C5C
8FEBD1 9C6B
8FEBD2 9C68
8FEBD3 9C6E
8FEBD4 9C70
8FEBD5 9C72
8FEBD6 9C75
8FEBD7 9C77
8FEBD8 9C7B
8FEBD9 9CE6
8FEBDA 9CF2
8FEBDB 9CF7
8FEBDC 9CF9
8FEBDD 9D0B
8FEBDE 9D02
8FEBDF 9D11
8FEBE0 9D17
8FEBE1 9D18
8FEBE2 9D1C
8FEBE3 9D1D
8FEBE4 9D1E
8FEBE5 9D2F
8FEBE6 9D30
8FEBE7 9D32
8FEBE8 9D33
8FEBE9 9D34
8FEBEA 9D3A
8FEBEB 9D3C
8FEBEC 9D45
8FEBED 9D3D
8FEBEE 9D42
8FEBEF 9D43
8FEBF0 9D47
8FEBF1 9D4A
8FEBF2 9D53
8FEBF3 9D54
8FEBF4 9D5F
8FEBF5 9D63
8FEBF6 9D62
8FEBF7 9D65
8FEBF8 9D69
8FEBF9 9D6A
8FEBFA 9D6B
8FEBFB 9D70
8FEBFC 9D76
8FEBFD 9D77
8FEBFE 9D7B
8FECA1 9D7C
8FECA2 9D7E
8FECA3 9D83
8FECA4 9D84
8FECA5 9D86
8FECA6 9D8A
8FECA7 9D8D
8FECA8 9D8E
8FECA9 9D92
8FECAA 9D93
8FECAB 9D95
8FECAC 9D96
8FECAD 9D97
8FECAE 9D98
8FECAF 9DA1
8FECB0 9DAA
8FECB1 9DAC
8FECB2 9DAE
8FECB3 9DB1
8FECB4 9DB5
8FECB5 9DB9
8FECB6 9DBC
8FECB7 9DBF
8FECB8 9DC3
8FECB9 9DC7
8FECBA 9DC9
8FECBB 9DCA
8FECBC 9DD4
8FECBD 9DD5
8FECBE 9DD6
8FECBF 9DD7
8FECC0 9DDA
8FECC1 9DDE
8FECC2 9DDF
8FECC3 9DE0
8FECC4 9DE5
8FECC5 9DE7
8FECC6 9DE9
8FECC7 9DEB
8FECC8 9DEE
8FECC9 9DF0
8FECCA 9DF3
8FECCB 9DF4
8FECCC 9DFE
8FECCD 9E0A
8FECCE 9E02
8FECCF 9E07
8FECD0 9E0E
8FECD1 9E10
8FECD2 9E11
8FECD3 9E12
8FECD4 9E15
8FECD5 9E16
8FECD6 9E19
8FECD7 9E1C
8FECD8 9E1D
8FECD9 9E7A
8FECDA 9E7B
8FECDB 9E7C
8FECDC 9E80
8FECDD 9E82
8FECDE 9E83
8FECDF 9E84
8FECE0 9E85
8FECE1 9E87
8FECE2 9E8E
8FECE3 9E8F
8FECE4 9E96
8FECE5 9E98
8FECE6 9E9B
8FECE7 9E9E
8FECE8 9EA4
8FECE9 9EA8
8FECEA 9EAC
8FECEB 9EAE
8FECEC 9EAF
8FECED 9EB0
8FECEE 9EB3
8FECEF 9EB4
8FECF0 9EB5
8FECF1 9EC6
8FECF2 9EC8
8FECF3 9ECB
8FECF4 9ED5
8FECF5 9EDF
8FECF6 9EE4
8FECF7 9EE7
8FECF8 9EEC
8FECF9 9EED
8FECFA 9EEE
8FECFB 9EF0
8FECFC 9EF1
8FECFD 9EF2
8FECFE 9EF5
8FEDA1 9EF8
8FEDA2 9EFF
8FEDA3 9F02
8FEDA4 9F03
8FEDA5 9F09
8FEDA6 9F0F
8FEDA7 9F10
8FEDA8 9F11
8FEDA9 9F12
8FEDAA 9F14
8FEDAB 9F16
8FEDAC 9F17
8FEDAD 9F19
8FEDAE 9F1A
8FEDAF 9F1B
8FEDB0 9F1F
8FEDB1 9F22
8FEDB2 9F26
8FEDB3 9F2A
8FEDB4 9F2B
8FEDB5 9F2F
8FEDB6 9F31
8FEDB7 9F32
8FEDB8 9F34
8FEDB9 9F37
8FEDBA 9F39
8FEDBB 9F3A
8FEDBC 9F3C
8FEDBD 9F3D
8FEDBE 9F3F
8FEDBF 9F41
8FEDC0 9F43
8FEDC1 9F44
8FEDC2 9F45
8FEDC3 9F46
8FEDC4 9F47
8FEDC5 9F53
8FEDC6 9F55
8FEDC7 9F56
8FEDC8 9F57
8FEDC9 9F58
8FEDCA 9F5A
8FEDCB 9F5D
8FEDCC 9F5E
8FEDCD 9F68
8FEDCE 9F69
8FEDCF 9F6D
8FEDD0 9F6E
8FEDD1 9F6F
8FEDD2 9F70
8FEDD3 9F71
8FEDD4 9F73
8FEDD5 9F75
8FEDD6 9F7A
8FEDD7 9F7D
8FEDD8 9F8F
8FEDD9 9F90
8FEDDA 9F91
8FEDDB 9F92
8FEDDC 9F94
8FEDDD 9F96
8FEDDE 9F97
8FEDDF 9F9E
8FEDE0 9FA1
8FEDE1 9FA2
8FEDE2 9FA3
8FEDE3 9FA5
A1A1 3000
A1A2 3001
A1A3 3002
A1A4 FF0C
A1A5 FF0E
A1A6 30FB
A1A7 FF1A
A1A8 FF1B
A1A9 FF1F
A1AA FF01
A1AB 309B
A1AC 309C
A1AD 00B4
A1AE FF40
A1AF 00A8
A1B0 FF3E
A1B1 FFE3
A1B2 FF3F
A1B3 30FD
A1B4 30FE
A1B5 309D
A1B6 309E
A1B7 3003
A1B8 4EDD
A1B9 3005
A1BA 3006
A1BB 3007
A1BC 30FC
A1BD 2015
A1BE 2010
A1BF FF0F
A1C0 005C
A1C1 301C
A1C2 2016
A1C3 FF5C
A1C4 2026
A1C5 2025
A1C6 2018
A1C7 2019
A1C8 201C
A1C9 201D
A1CA FF08
A1CB FF09
A1CC 3014
A1CD 3015
A1CE FF3B
A1CF FF3D
A1D0 FF5B
A1D1 FF5D
A1D2 3008
A1D3 3009
A1D4 300A
A1D5 300B
A1D6 300C
A1D7 300D
A1D8 300E
A1D9 300F
A1DA 3010
A1DB 3011
A1DC FF0B
A1DD 2212
A1DE 00B1
A1DF 00D7
A1E0 00F7
A1E1 FF1D
A1E2 2260
A1E3 FF1C
A1E4 FF1E
A1E5 2266
A1E6 2267
A1E7 221E
A1E8 2234
A1E9 2642
A1EA 2640
A1EB 00B0
A1EC 2032
A1ED 2033
A1EE 2103
A1EF FFE5
A1F0 FF04
A1F1 00A2
A1F2 00A3
A1F3 FF05
A1F4 FF03
A1F5 FF06
A1F6 FF0A
A1F7 FF20
A1F8 00A7
A1F9 2606
A1FA 2605
A1FB 25CB
A1FC 25CF
A1FD 25CE
A1FE 25C7
A2A1 25C6
A2A2 25A1
A2A3 25A0
A2A4 25B3
A2A5 25B2
A2A6 25BD
A2A7 25BC
A2A8 203B
A2A9 3012
A2AA 2192
A2AB 2190
A2AC 2191
A2AD 2193
A2AE 3013
A2BA 2208
A2BB 220B
A2BC 2286
A2BD 2287
A2BE 2282
A2BF 2283
A2C0 222A
A2C1 2229
A2CA 2227
A2CB 2228
A2CC 00AC
A2CD 21D2
A2CE 21D4
A2CF 2200
A2D0 2203
A2DC 2220
A2DD 22A5
A2DE 2312
A2DF 2202
A2E0 2207
A2E1 2261
A2E2 2252
A2E3 226A
A2E4 226B
A2E5 221A
A2E6 223D
A2E7 221D
A2E8 2235
A2E9 222B
A2EA 222C
A2F2 212B
A2F3 2030
A2F4 266F
A2F5 266D
A2F6 266A
A2F7 2020
A2F8 2021
A2F9 00B6
A2FE 25EF
A3B0 FF10
A3B1 FF11
A3B2 FF12
A3B3 FF13
A3B4 FF14
A3B5 FF15
A3B6 FF16
A3B7 FF17
A3B8 FF18
A3B9 FF19
A3C1 FF21
A3C2 FF22
A3C3 FF23
A3C4 FF24
A3C5 FF25
A3C6 FF26
A3C7 FF27
A3C8 FF28
A3C9 FF29
A3CA FF2A
A3CB FF2B
A3CC FF2C
A3CD FF2D
A3CE FF2E
A3CF FF2F
A3D0 FF30
A3D1 FF31
A3D2 FF32
A3D3 FF33
A3D4 FF34
A3D5 FF35
A3D6 FF36
A3D7 FF37
A3D8 FF38
A3D9 FF39
A3DA FF3A
A3E1 FF41
A3E2 FF42
A3E3 FF43
A3E4 FF44
A3E5 FF45
A3E6 FF46
A3E7 FF47
A3E8 FF48
A3E9 FF49
A3EA FF4A
A3EB FF4B
A3EC FF4C
A3ED FF4D
A3EE FF4E
A3EF FF4F
A3F0 FF50
A3F1 FF51
A3F2 FF52
A3F3 FF53
A3F4 FF54
A3F5 FF55
A3F6 FF56
A3F7 FF57
A3F8 FF58
A3F9 FF59
A3FA FF5A
A4A1 3041
A4A2 3042
A4A3 3043
A4A4 3044
A4A5 3045
A4A6 3046
A4A7 3047
A4A8 3048
A4A9 3049
A4AA 304A
A4AB 304B
A4AC 304C
A4AD 304D
A4AE 304E
A4AF 304F
A4B0 3050
A4B1 3051
A4B2 3052
A4B3 3053
A4B4 3054
A4B5 3055
A4B6 3056
A4B7 3057
A4B8 3058
A4B9 3059
A4BA 305A
A4BB 305B
A4BC 305C
A4BD 305D
A4BE 305E
A4BF 305F
A4C0 3060
A4C1 3061
A4C2 3062
A4C3 3063
A4C4 3064
A4C5 3065
A4C6 3066
A4C7 3067
A4C8 3068
A4C9 3069
A4CA 306A
A4CB 306B
A4CC 306C
A4CD 306D
A4CE 306E
A4CF 306F
A4D0 3070
A4D1 3071
A4D2 3072
A4D3 3073
A4D4 3074
A4D5 3075
A4D6 3076
A4D7 3077
A4D8 3078
A4D9 3079
A4DA 307A
A4DB 307B
A4DC 307C
A4DD 307D
A4DE 307E
A4DF 307F
A4E0 3080
A4E1 3081
A4E2 3082
A4E3 3083
A4E4 3084
A4E5 3085
A4E6 3086
A4E7 3087
A4E8 3088
A4E9 3089
A4EA 308A
A4EB 308B
A4EC 308C
A4ED 308D
A4EE 308E
A4EF 308F
A4F0 3090
A4F1 3091
A4F2 3092
A4F3 3093
A5A1 30A1
A5A2 30A2
A5A3 30A3
A5A4 30A4
A5A5 30A5
A5A6 30A6
A5A7 30A7
A5A8 30A8
A5A9 30A9
A5AA 30AA
A5AB 30AB
A5AC 30AC
A5AD 30AD
A5AE 30AE
A5AF 30AF
A5B0 30B0
A5B1 30B1
A5B2 30B2
A5B3 30B3
A5B4 30B4
A5B5 30B5
A5B6 30B6
A5B7 30B7
A5B8 30B8
A5B9 30B9
A5BA 30BA
A5BB 30BB
A5BC 30BC
A5BD 30BD
A5BE 30BE
A5BF 30BF
A5C0 30C0
A5C1 30C1
A5C2 30C2
A5C3 30C3
A5C4 30C4
A5C5 30C5
A5C6 30C6
A5C7 30C7
A5C8 30C8
A5C9 30C9
A5CA 30CA
A5CB 30CB
A5CC 30CC
A5CD 30CD
A5CE 30CE
A5CF 30CF
A5D0 30D0
A5D1 30D1
A5D2 30D2
A5D3 30D3
A5D4 30D4
A5D5 30D5
A5D6 30D6
A5D7 30D7
A5D8 30D8
A5D9 30D9
A5DA 30DA
A5DB 30DB
A5DC 30DC
A5DD 30DD
A5DE 30DE
A5DF 30DF
A5E0 30E0
A5E1 30E1
A5E2 30E2
A5E3 30E3
A5E4 30E4
A5E5 30E5
A5E6 30E6
A5E7 30E7
A5E8 30E8
A5E9 30E9
A5EA 30EA
A5EB 30EB
A5EC 30EC
A5ED 30ED
A5EE 30EE
A5EF 30EF
A5F0 30F0
A5F1 30F1
A5F2 30F2
A5F3 30F3
A5F4 30F4
A5F5 30F5
A5F6 30F6
A6A1 0391
A6A2 0392
A6A3 0393
A6A4 0394
A6A5 0395
A6A6 0396
A6A7 0397
A6A8 0398
A6A9 0399
A6AA 039A
A6AB 039B
A6AC 039C
A6AD 039D
A6AE 039E
A6AF 039F
A6B0 03A0
A6B1 03A1
A6B2 03A3
A6B3 03A4
A6B4 03A5
A6B5 03A6
A6B6 03A7
A6B7 03A8
A6B8 03A9
A6C1 03B1
A6C2 03B2
A6C3 03B3
A6C4 03B4
A6C5 03B5
A6C6 03B6
A6C7 03B7
A6C8 03B8
A6C9 03B9
A6CA 03BA
A6CB 03BB
A6CC 03BC
A6CD 03BD
A6CE 03BE
A6CF 03BF
A6D0 03C0
A6D1 03C1
A6D2 03C3
A6D3 03C4
A6D4 03C5
A6D5 03C6
A6D6 03C7
A6D7 03C8
A6D8 03C9
A7A1 0410
A7A2 0411
A7A3 0412
A7A4 0413
A7A5 0414
A7A6 0415
A7A7 0401
A7A8 0416
A7A9 0417
A7AA 0418
A7AB 0419
A7AC 041A
A7AD 041B
A7AE 041C
A7AF 041D
A7B0 041E
A7B1 041F
A7B2 0420
A7B3 0421
A7B4 0422
A7B5 0423
A7B6 0424
A7B7 0425
A7B8 0426
A7B9 0427
A7BA 0428
A7BB 0429
A7BC 042A
A7BD 042B
A7BE 042C
A7BF 042D
A7C0 042E
A7C1 042F
A7D1 0430
A7D2 0431
A7D3 0432
A7D4 0433
A7D5 0434
A7D6 0435
A7D7 0451
A7D8 0436
A7D9 0437
A7DA 0438
A7DB 0439
A7DC 043A
A7DD 043B
A7DE 043C
A7DF 043D
A7E0 043E
A7E1 043F
A7E2 0440
A7E3 0441
A7E4 0442
A7E5 0443
A7E6 0444
A7E7 0445
A7E8 0446
A7E9 0447
A7EA 0448
A7EB 0449
A7EC 044A
A7ED 044B
A7EE 044C
A7EF 044D
A7F0 044E
A7F1 044F
A8A1 2500
A8A2 2502
A8A3 250C
A8A4 2510
A8A5 2518
A8A6 2514
A8A7 251C
A8A8 252C
A8A9 2524
A8AA 2534
A8AB 253C
A8AC 2501
A8AD 2503
A8AE 250F
A8AF 2513
A8B0 251B
A8B1 2517
A8B2 2523
A8B3 2533
A8B4 252B
A8B5 253B
A8B6 254B
A8B7 2520
A8B8 252F
A8B9 2528
A8BA 2537
A8BB 253F
A8BC 251D
A8BD 2530
A8BE 2525
A8BF 2538
A8C0 2542
B0A1 4E9C
B0A2 5516
B0A3 5A03
B0A4 963F
B0A5 54C0
B0A6 611B
B0A7 6328
B0A8 59F6
B0A9 9022
B0AA 8475
B0AB 831C
B0AC 7A50
B0AD 60AA
B0AE 63E1
B0AF 6E25
B0B0 65ED
B0B1 8466
B0B2 82A6
B0B3 9BF5
B0B4 6893
B0B5 5727
B0B6 65A1
B0B7 6271
B0B8 5B9B
B0B9 59D0
B0BA 867B
B0BB 98F4
B0BC 7D62
B0BD 7DBE
B0BE 9B8E
B0BF 6216
B0C0 7C9F
B0C1 88B7
B0C2 5B89
B0C3 5EB5
B0C4 6309
B0C5 6697
B0C6 6848
B0C7 95C7
B0C8 978D
B0C9 674F
B0CA 4EE5
B0CB 4F0A
B0CC 4F4D
B0CD 4F9D
B0CE 5049
B0CF 56F2
B0D0 5937
B0D1 59D4
B0D2 5A01
B0D3 5C09
B0D4 60DF
B0D5 610F
B0D6 6170
B0D7 6613
B0D8 6905
B0D9 70BA
B0DA 754F
B0DB 7570
B0DC 79FB
B0DD 7DAD
B0DE 7DEF
B0DF 80C3
B0E0 840E
B0E1 8863
B0E2 8B02
B0E3 9055
B0E4 907A
B0E5 533B
B0E6 4E95
B0E7 4EA5
B0E8 57DF
B0E9 80B2
B0EA 90C1
B0EB 78EF
B0EC 4E00
B0ED 58F1
B0EE 6EA2
B0EF 9038
B0F0 7A32
B0F1 8328
B0F2 828B
B0F3 9C2F
B0F4 5141
B0F5 5370
B0F6 54BD
B0F7 54E1
B0F8 56E0
B0F9 59FB
B0FA 5F15
B0FB 98F2
B0FC 6DEB
B0FD 80E4
B0FE 852D
B1A1 9662
B1A2 9670
B1A3 96A0
B1A4 97FB
B1A5 540B
B1A6 53F3
B1A7 5B87
B1A8 70CF
B1A9 7FBD
B1AA 8FC2
B1AB 96E8
B1AC 536F
B1AD 9D5C
B1AE 7ABA
B1AF 4E11
B1B0 7893
B1B1 81FC
B1B2 6E26
B1B3 5618
B1B4 5504
B1B5 6B1D
B1B6 851A
B1B7 9C3B
B1B8 59E5
B1B9 53A9
B1BA 6D66
B1BB 74DC
B1BC 958F
B1BD 5642
B1BE 4E91
B1BF 904B
B1C0 96F2
B1C1 834F
B1C2 990C
B1C3 53E1
B1C4 55B6
B1C5 5B30
B1C6 5F71
B1C7 6620
B1C8 66F3
B1C9 6804
B1CA 6C38
B1CB 6CF3
B1CC 6D29
B1CD 745B
B1CE 76C8
B1CF 7A4E
B1D0 9834
B1D1 82F1
B1D2 885B
B1D3 8A60
B1D4 92ED
B1D5 6DB2
B1D6 75AB
B1D7 76CA
B1D8 99C5
B1D9 60A6
B1DA 8B01
B1DB 8D8A
B1DC 95B2
B1DD 698E
B1DE 53AD
B1DF 5186
B1E0 5712
B1E1 5830
B1E2 5944
B1E3 5BB4
B1E4 5EF6
B1E5 6028
B1E6 63A9
B1E7 63F4
B1E8 6CBF
B1E9 6F14
B1EA 708E
B1EB 7114
B1EC 7159
B1ED 71D5
B1EE 733F
B1EF 7E01
B1F0 8276
B1F1 82D1
B1F2 8597
B1F3 9060
B1F4 925B
B1F5 9D1B
B1F6 5869
B1F7 65BC
B1F8 6C5A
B1F9 7525
B1FA 51F9
B1FB 592E
B1FC 5965
B1FD 5F80
B1FE 5FDC
B2A1 62BC
B2A2 65FA
B2A3 6A2A
B2A4 6B27
B2A5 6BB4
B2A6 738B
B2A7 7FC1
B2A8 8956
B2A9 9D2C
B2AA 9D0E
B2AB 9EC4
B2AC 5CA1
B2AD 6C96
B2AE 837B
B2AF 5104
B2B0 5C4B
B2B1 61B6
B2B2 81C6
B2B3 6876
B2B4 7261
B2B5 4E59
B2B6 4FFA
B2B7 5378
B2B8 6069
B2B9 6E29
B2BA 7A4F
B2BB 97F3
B2BC 4E0B
B2BD 5316
B2BE 4EEE
B2BF 4F55
B2C0 4F3D
B2C1 4FA1
B2C2 4F73
B2C3 52A0
B2C4 53EF
B2C5 5609
B2C6 590F
B2C7 5AC1
B2C8 5BB6
B2C9 5BE1
B2CA 79D1
B2CB 6687
B2CC 679C
B2CD 67B6
B2CE 6B4C
B2CF 6CB3
B2D0 706B
B2D1 73C2
B2D2 798D
B2D3 79BE
B2D4 7A3C
B2D5 7B87
B2D6 82B1
B2D7 82DB
B2D8 8304
B2D9 8377
B2DA 83EF
B2DB 83D3
B2DC 8766
B2DD 8AB2
B2DE 5629
B2DF 8CA8
B2E0 8FE6
B2E1 904E
B2E2 971E
B2E3 868A
B2E4 4FC4
B2E5 5CE8
B2E6 6211
B2E7 7259
B2E8 753B
B2E9 81E5
B2EA 82BD
B2EB 86FE
B2EC 8CC0
B2ED 96C5
B2EE 9913
B2EF 99D5
B2F0 4ECB
B2F1 4F1A
B2F2 89E3
B2F3 56DE
B2F4 584A
B2F5 58CA
B2F6 5EFB
B2F7 5FEB
B2F8 602A
B2F9 6094
B2FA 6062
B2FB 61D0
B2FC 6212
B2FD 62D0
B2FE 6539
B3A1 9B41
B3A2 6666
B3A3 68B0
B3A4 6D77
B3A5 7070
B3A6 754C
B3A7 7686
B3A8 7D75
B3A9 82A5
B3AA 87F9
B3AB 958B
B3AC 968E
B3AD 8C9D
B3AE 51F1
B3AF 52BE
B3B0 5916
B3B1 54B3
B3B2 5BB3
B3B3 5D16
B3B4 6168
B3B5 6982
B3B6 6DAF
B3B7 788D
B3B8 84CB
B3B9 8857
B3BA 8A72
B3BB 93A7
B3BC 9AB8
B3BD 6D6C
B3BE 99A8
B3BF 86D9
B3C0 57A3
B3C1 67FF
B3C2 86CE
B3C3 920E
B3C4 5283
B3C5 5687
B3C6 5404
B3C7 5ED3
B3C8 62E1
B3C9 64B9
B3CA 683C
B3CB 6838
B3CC 6BBB
B3CD 7372
B3CE 78BA
B3CF 7A6B
B3D0 899A
B3D1 89D2
B3D2 8D6B
B3D3 8F03
B3D4 90ED
B3D5 95A3
B3D6 9694
B3D7 9769
B3D8 5B66
B3D9 5CB3
B3DA 697D
B3DB 984D
B3DC 984E
B3DD 639B
B3DE 7B20
B3DF 6A2B
B3E0 6A7F
B3E1 68B6
B3E2 9C0D
B3E3 6F5F
B3E4 5272
B3E5 559D
B3E6 6070
B3E7 62EC
B3E8 6D3B
B3E9 6E07
B3EA 6ED1
B3EB 845B
B3EC 8910
B3ED 8F44
B3EE 4E14
B3EF 9C39
B3F0 53F6
B3F1 691B
B3F2 6A3A
B3F3 9784
B3F4 682A
B3F5 515C
B3F6 7AC3
B3F7 84B2
B3F8 91DC
B3F9 938C
B3FA 565B
B3FB 9D28
B3FC 6822
B3FD 8305
B3FE 8431
B4A1 7CA5
B4A2 5208
B4A3 82C5
B4A4 74E6
B4A5 4E7E
B4A6 4F83
B4A7 51A0
B4A8 5BD2
B4A9 520A
B4AA 52D8
B4AB 52E7
B4AC 5DFB
B4AD 559A
B4AE 582A
B4AF 59E6
B4B0 5B8C
B4B1 5B98
B4B2 5BDB
B4B3 5E72
B4B4 5E79
B4B5 60A3
B4B6 611F
B4B7 6163
B4B8 61BE
B4B9 63DB
B4BA 6562
B4BB 67D1
B4BC 6853
B4BD 68FA
B4BE 6B3E
B4BF 6B53
B4C0 6C57
B4C1 6F22
B4C2 6F97
B4C3 6F45
B4C4 74B0
B4C5 7518
B4C6 76E3
B4C7 770B
B4C8 7AFF
B4C9 7BA1
B4CA 7C21
B4CB 7DE9
B4CC 7F36
B4CD 7FF0
B4CE 809D
B4CF 8266
B4D0 839E
B4D1 89B3
B4D2 8ACC
B4D3 8CAB
B4D4 9084
B4D5 9451
B4D6 9593
B4D7 9591
B4D8 95A2
B4D9 9665
B4DA 97D3
B4DB 9928
B4DC 8218
B4DD 4E38
B4DE 542B
B4DF 5CB8
B4E0 5DCC
B4E1 73A9
B4E2 764C
B4E3 773C
B4E4 5CA9
B4E5 7FEB
B4E6 8D0B
B4E7 96C1
B4E8 9811
B4E9 9854
B4EA 9858
B4EB 4F01
B4EC 4F0E
B4ED 5371
B4EE 559C
B4EF 5668
B4F0 57FA
B4F1 5947
B4F2 5B09
B4F3 5BC4
B4F4 5C90
B4F5 5E0C
B4F6 5E7E
B4F7 5FCC
B4F8 63EE
B4F9 673A
B4FA 65D7
B4FB 65E2
B4FC 671F
B4FD 68CB
B4FE 68C4
B5A1 6A5F
B5A2 5E30
B5A3 6BC5
B5A4 6C17
B5A5 6C7D
B5A6 757F
B5A7 7948
B5A8 5B63
B5A9 7A00
B5AA 7D00
B5AB 5FBD
B5AC 898F
B5AD 8A18
B5AE 8CB4
B5AF 8D77
B5B0 8ECC
B5B1 8F1D
B5B2 98E2
B5B3 9A0E
B5B4 9B3C
B5B5 4E80
B5B6 507D
B5B7 5100
B5B8 5993
B5B9 5B9C
B5BA 622F
B5BB 6280
B5BC 64EC
B5BD 6B3A
B5BE 72A0
B5BF 7591
B5C0 7947
B5C1 7FA9
B5C2 87FB
B5C3 8ABC
B5C4 8B70
B5C5 63AC
B5C6 83CA
B5C7 97A0
B5C8 5409
B5C9 5403
B5CA 55AB
B5CB 6854
B5CC 6A58
B5CD 8A70
B5CE 7827
B5CF 6775
B5D0 9ECD
B5D1 5374
B5D2 5BA2
B5D3 811A
B5D4 8650
B5D5 9006
B5D6 4E18
B5D7 4E45
B5D8 4EC7
B5D9 4F11
B5DA 53CA
B5DB 5438
B5DC 5BAE
B5DD 5F13
B5DE 6025
B5DF 6551
B5E0 673D
B5E1 6C42
B5E2 6C72
B5E3 6CE3
B5E4 7078
B5E5 7403
B5E6 7A76
B5E7 7AAE
B5E8 7B08
B5E9 7D1A
B5EA 7CFE
B5EB 7D66
B5EC 65E7
B5ED 725B
B5EE 53BB
B5EF 5C45
B5F0 5DE8
B5F1 62D2
B5F2 62E0
B5F3 6319
B5F4 6E20
B5F5 865A
B5F6 8A31
B5F7 8DDD
B5F8 92F8
B5F9 6F01
B5FA 79A6
B5FB 9B5A
B5FC 4EA8
B5FD 4EAB
B5FE 4EAC
B6A1 4F9B
B6A2 4FA0
B6A3 50D1
B6A4 5147
B6A5 7AF6
B6A6 5171
B6A7 51F6
B6A8 5354
B6A9 5321
B6AA 537F
B6AB 53EB
B6AC 55AC
B6AD 5883
B6AE 5CE1
B6AF 5F37
B6B0 5F4A
B6B1 602F
B6B2 6050
B6B3 606D
B6B4 631F
B6B5 6559
B6B6 6A4B
B6B7 6CC1
B6B8 72C2
B6B9 72ED
B6BA 77EF
B6BB 80F8
B6BC 8105
B6BD 8208
B6BE 854E
B6BF 90F7
B6C0 93E1
B6C1 97FF
B6C2 9957
B6C3 9A5A
B6C4 4EF0
B6C5 51DD
B6C6 5C2D
B6C7 6681
B6C8 696D
B6C9 5C40
B6CA 66F2
B6CB 6975
B6CC 7389
B6CD 6850
B6CE 7C81
B6CF 50C5
B6D0 52E4
B6D1 5747
B6D2 5DFE
B6D3 9326
B6D4 65A4
B6D5 6B23
B6D6 6B3D
B6D7 7434
B6D8 7981
B6D9 79BD
B6DA 7B4B
B6DB 7DCA
B6DC 82B9
B6DD 83CC
B6DE 887F
B6DF 895F
B6E0 8B39
B6E1 8FD1
B6E2 91D1
B6E3 541F
B6E4 9280
B6E5 4E5D
B6E6 5036
B6E7 53E5
B6E8 533A
B6E9 72D7
B6EA 7396
B6EB 77E9
B6EC 82E6
B6ED 8EAF
B6EE 99C6
B6EF 99C8
B6F0 99D2
B6F1 5177
B6F2 611A
B6F3 865E
B6F4 55B0
B6F5 7A7A
B6F6 5076
B6F7 5BD3
B6F8 9047
B6F9 9685
B6FA 4E32
B6FB 6ADB
B6FC 91E7
B6FD 5C51
B6FE 5C48
B7A1 6398
B7A2 7A9F
B7A3 6C93
B7A4 9774
B7A5 8F61
B7A6 7AAA
B7A7 718A
B7A8 9688
B7A9 7C82
B7AA 6817
B7AB 7E70
B7AC 6851
B7AD 936C
B7AE 52F2
B7AF 541B
B7B0 85AB
B7B1 8A13
B7B2 7FA4
B7B3 8ECD
B7B4 90E1
B7B5 5366
B7B6 8888
B7B7 7941
B7B8 4FC2
B7B9 50BE
B7BA 5211
B7BB 5144
B7BC 5553
B7BD 572D
B7BE 73EA
B7BF 578B
B7C0 5951
B7C1 5F62
B7C2 5F84
B7C3 6075
B7C4 6176
B7C5 6167
B7C6 61A9
B7C7 63B2
B7C8 643A
B7C9 656C
B7CA 666F
B7CB 6842
B7CC 6E13
B7CD 7566
B7CE 7A3D
B7CF 7CFB
B7D0 7D4C
B7D1 7D99
B7D2 7E4B
B7D3 7F6B
B7D4 830E
B7D5 834A
B7D6 86CD
B7D7 8A08
B7D8 8A63
B7D9 8B66
B7DA 8EFD
B7DB 981A
B7DC 9D8F
B7DD 82B8
B7DE 8FCE
B7DF 9BE8
B7E0 5287
B7E1 621F
B7E2 6483
B7E3 6FC0
B7E4 9699
B7E5 6841
B7E6 5091
B7E7 6B20
B7E8 6C7A
B7E9 6F54
B7EA 7A74
B7EB 7D50
B7EC 8840
B7ED 8A23
B7EE 6708
B7EF 4EF6
B7F0 5039
B7F1 5026
B7F2 5065
B7F3 517C
B7F4 5238
B7F5 5263
B7F6 55A7
B7F7 570F
B7F8 5805
B7F9 5ACC
B7FA 5EFA
B7FB 61B2
B7FC 61F8
B7FD 62F3
B7FE 6372
B8A1 691C
B8A2 6A29
B8A3 727D
B8A4 72AC
B8A5 732E
B8A6 7814
B8A7 786F
B8A8 7D79
B8A9 770C
B8AA 80A9
B8AB 898B
B8AC 8B19
B8AD 8CE2
B8AE 8ED2
B8AF 9063
B8B0 9375
B8B1 967A
B8B2 9855
B8B3 9A13
B8B4 9E78
B8B5 5143
B8B6 539F
B8B7 53B3
B8B8 5E7B
B8B9 5F26
B8BA 6E1B
B8BB 6E90
B8BC 7384
B8BD 73FE
B8BE 7D43
B8BF 8237
B8C0 8A00
B8C1 8AFA
B8C2 9650
B8C3 4E4E
B8C4 500B
B8C5 53E4
B8C6 547C
B8C7 56FA
B8C8 59D1
B8C9 5B64
B8CA 5DF1
B8CB 5EAB
B8CC 5F27
B8CD 6238
B8CE 6545
B8CF 67AF
B8D0 6E56
B8D1 72D0
B8D2 7CCA
B8D3 88B4
B8D4 80A1
B8D5 80E1
B8D6 83F0
B8D7 864E
B8D8 8A87
B8D9 8DE8
B8DA 9237
B8DB 96C7
B8DC 9867
B8DD 9F13
B8DE 4E94
B8DF 4E92
B8E0 4F0D
B8E1 5348
B8E2 5449
B8E3 543E
B8E4 5A2F
B8E5 5F8C
B8E6 5FA1
B8E7 609F
B8E8 68A7
B8E9 6A8E
B8EA 745A
B8EB 7881
B8EC 8A9E
B8ED 8AA4
B8EE 8B77
B8EF 9190
B8F0 4E5E
B8F1 9BC9
B8F2 4EA4
B8F3 4F7C
B8F4 4FAF
B8F5 5019
B8F6 5016
B8F7 5149
B8F8 516C
B8F9 529F
B8FA 52B9
B8FB 52FE
B8FC 539A
B8FD 53E3
B8FE 5411
B9A1 540E
B9A2 5589
B9A3 5751
B9A4 57A2
B9A5 597D
B9A6 5B54
B9A7 5B5D
B9A8 5B8F
B9A9 5DE5
B9AA 5DE7
B9AB 5DF7
B9AC 5E78
B9AD 5E83
B9AE 5E9A
B9AF 5EB7
B9B0 5F18
B9B1 6052
B9B2 614C
B9B3 6297
B9B4 62D8
B9B5 63A7
B9B6 653B
B9B7 6602
B9B8 6643
B9B9 66F4
B9BA 676D
B9BB 6821
B9BC 6897
B9BD 69CB
B9BE 6C5F
B9BF 6D2A
B9C0 6D69
B9C1 6E2F
B9C2 6E9D
B9C3 7532
B9C4 7687
B9C5 786C
B9C6 7A3F
B9C7 7CE0
B9C8 7D05
B9C9 7D18
B9CA 7D5E
B9CB 7DB1
B9CC 8015
B9CD 8003
B9CE 80AF
B9CF 80B1
B9D0 8154
B9D1 818F
B9D2 822A
B9D3 8352
B9D4 884C
B9D5 8861
B9D6 8B1B
B9D7 8CA2
B9D8 8CFC
B9D9 90CA
B9DA 9175
B9DB 9271
B9DC 783F
B9DD 92FC
B9DE 95A4
B9DF 964D
B9E0 9805
B9E1 9999
B9E2 9AD8
B9E3 9D3B
B9E4 525B
B9E5 52AB
B9E6 53F7
B9E7 5408
B9E8 58D5
B9E9 62F7
B9EA 6FE0
B9EB 8C6A
B9EC 8F5F
B9ED 9EB9
B9EE 514B
B9EF 523B
B9F0 544A
B9F1 56FD
B9F2 7A40
B9F3 9177
B9F4 9D60
B9F5 9ED2
B9F6 7344
B9F7 6F09
B9F8 8170
B9F9 7511
B9FA 5FFD
B9FB 60DA
B9FC 9AA8
B9FD 72DB
B9FE 8FBC
BAA1 6B64
BAA2 9803
BAA3 4ECA
BAA4 56F0
BAA5 5764
BAA6 58BE
BAA7 5A5A
BAA8 6068
BAA9 61C7
BAAA 660F
BAAB 6606
BAAC 6839
BAAD 68B1
BAAE 6DF7
BAAF 75D5
BAB0 7D3A
BAB1 826E
BAB2 9B42
BAB3 4E9B
BAB4 4F50
BAB5 53C9
BAB6 5506
BAB7 5D6F
BAB8 5DE6
BAB9 5DEE
BABA 67FB
BABB 6C99
BABC 7473
BABD 7802
BABE 8A50
BABF 9396
BAC0 88DF
BAC1 5750
BAC2 5EA7
BAC3 632B
BAC4 50B5
BAC5 50AC
BAC6 518D
BAC7 6700
BAC8 54C9
BAC9 585E
BACA 59BB
BACB 5BB0
BACC 5F69
BACD 624D
BACE 63A1
BACF 683D
BAD0 6B73
BAD1 6E08
BAD2 707D
BAD3 91C7
BAD4 7280
BAD5 7815
BAD6 7826
BAD7 796D
BAD8 658E
BAD9 7D30
BADA 83DC
BADB 88C1
BADC 8F09
BADD 969B
BADE 5264
BADF 5728
BAE0 6750
BAE1 7F6A
BAE2 8CA1
BAE3 51B4
BAE4 5742
BAE5 962A
BAE6 583A
BAE7 698A
BAE8 80B4
BAE9 54B2
BAEA 5D0E
BAEB 57FC
BAEC 7895
BAED 9DFA
BAEE 4F5C
BAEF 524A
BAF0 548B
BAF1 643E
BAF2 6628
BAF3 6714
BAF4 67F5
BAF5 7A84
BAF6 7B56
BAF7 7D22
BAF8 932F
BAF9 685C
BAFA 9BAD
BAFB 7B39
BAFC 5319
BAFD 518A
BAFE 5237
BBA1 5BDF
BBA2 62F6
BBA3 64AE
BBA4 64E6
BBA5 672D
BBA6 6BBA
BBA7 85A9
BBA8 96D1
BBA9 7690
BBAA 9BD6
BBAB 634C
BBAC 9306
BBAD 9BAB
BBAE 76BF
BBAF 6652
BBB0 4E09
BBB1 5098
BBB2 53C2
BBB3 5C71
BBB4 60E8
BBB5 6492
BBB6 6563
BBB7 685F
BBB8 71E6
BBB9 73CA
BBBA 7523
BBBB 7B97
BBBC 7E82
BBBD 8695
BBBE 8B83
BBBF 8CDB
BBC0 9178
BBC1 9910
BBC2 65AC
BBC3 66AB
BBC4 6B8B
BBC5 4ED5
BBC6 4ED4
BBC7 4F3A
BBC8 4F7F
BBC9 523A
BBCA 53F8
BBCB 53F2
BBCC 55E3
BBCD 56DB
BBCE 58EB
BBCF 59CB
BBD0 59C9
BBD1 59FF
BBD2 5B50
BBD3 5C4D
BBD4 5E02
BBD5 5E2B
BBD6 5FD7
BBD7 601D
BBD8 6307
BBD9 652F
BBDA 5B5C
BBDB 65AF
BBDC 65BD
BBDD 65E8
BBDE 679D
BBDF 6B62
BBE0 6B7B
BBE1 6C0F
BBE2 7345
BBE3 7949
BBE4 79C1
BBE5 7CF8
BBE6 7D19
BBE7 7D2B
BBE8 80A2
BBE9 8102
BBEA 81F3
BBEB 8996
BBEC 8A5E
BBED 8A69
BBEE 8A66
BBEF 8A8C
BBF0 8AEE
BBF1 8CC7
BBF2 8CDC
BBF3 96CC
BBF4 98FC
BBF5 6B6F
BBF6 4E8B
BBF7 4F3C
BBF8 4F8D
BBF9 5150
BBFA 5B57
BBFB 5BFA
BBFC 6148
BBFD 6301
BBFE 6642
BCA1 6B21
BCA2 6ECB
BCA3 6CBB
BCA4 723E
BCA5 74BD
BCA6 75D4
BCA7 78C1
BCA8 793A
BCA9 800C
BCAA 8033
BCAB 81EA
BCAC 8494
BCAD 8F9E
BCAE 6C50
BCAF 9E7F
BCB0 5F0F
BCB1 8B58
BCB2 9D2B
BCB3 7AFA
BCB4 8EF8
BCB5 5B8D
BCB6 96EB
BCB7 4E03
BCB8 53F1
BCB9 57F7
BCBA 5931
BCBB 5AC9
BCBC 5BA4
BCBD 6089
BCBE 6E7F
BCBF 6F06
BCC0 75BE
BCC1 8CEA
BCC2 5B9F
BCC3 8500
BCC4 7BE0
BCC5 5072
BCC6 67F4
BCC7 829D
BCC8 5C61
BCC9 854A
BCCA 7E1E
BCCB 820E
BCCC 5199
BCCD 5C04
BCCE 6368
BCCF 8D66
BCD0 659C
BCD1 716E
BCD2 793E
BCD3 7D17
BCD4 8005
BCD5 8B1D
BCD6 8ECA
BCD7 906E
BCD8 86C7
BCD9 90AA
BCDA 501F
BCDB 52FA
BCDC 5C3A
BCDD 6753
BCDE 707C
BCDF 7235
BCE0 914C
BCE1 91C8
BCE2 932B
BCE3 82E5
BCE4 5BC2
BCE5 5F31
BCE6 60F9
BCE7 4E3B
BCE8 53D6
BCE9 5B88
BCEA 624B
BCEB 6731
BCEC 6B8A
BCED 72E9
BCEE 73E0
BCEF 7A2E
BCF0 816B
BCF1 8DA3
BCF2 9152
BCF3 9996
BCF4 5112
BCF5 53D7
BCF6 546A
BCF7 5BFF
BCF8 6388
BCF9 6A39
BCFA 7DAC
BCFB 9700
BCFC 56DA
BCFD 53CE
BCFE 5468
BDA1 5B97
BDA2 5C31
BDA3 5DDE
BDA4 4FEE
BDA5 6101
BDA6 62FE
BDA7 6D32
BDA8 79C0
BDA9 79CB
BDAA 7D42
BDAB 7E4D
BDAC 7FD2
BDAD 81ED
BDAE 821F
BDAF 8490
BDB0 8846
BDB1 8972
BDB2 8B90
BDB3 8E74
BDB4 8F2F
BDB5 9031
BDB6 914B
BDB7 916C
BDB8 96C6
BDB9 919C
BDBA 4EC0
BDBB 4F4F
BDBC 5145
BDBD 5341
BDBE 5F93
BDBF 620E
BDC0 67D4
BDC1 6C41
BDC2 6E0B
BDC3 7363
BDC4 7E26
BDC5 91CD
BDC6 9283
BDC7 53D4
BDC8 5919
BDC9 5BBF
BDCA 6DD1
BDCB 795D
BDCC 7E2E
BDCD 7C9B
BDCE 587E
BDCF 719F
BDD0 51FA
BDD1 8853
BDD2 8FF0
BDD3 4FCA
BDD4 5CFB
BDD5 6625
BDD6 77AC
BDD7 7AE3
BDD8 821C
BDD9 99FF
BDDA 51C6
BDDB 5FAA
BDDC 65EC
BDDD 696F
BDDE 6B89
BDDF 6DF3
BDE0 6E96
BDE1 6F64
BDE2 76FE
BDE3 7D14
BDE4 5DE1
BDE5 9075
BDE6 9187
BDE7 9806
BDE8 51E6
BDE9 521D
BDEA 6240
BDEB 6691
BDEC 66D9
BDED 6E1A
BDEE 5EB6
BDEF 7DD2
BDF0 7F72
BDF1 66F8
BDF2 85AF
BDF3 85F7
BDF4 8AF8
BDF5 52A9
BDF6 53D9
BDF7 5973
BDF8 5E8F
BDF9 5F90
BDFA 6055
BDFB 92E4
BDFC 9664
BDFD 50B7
BDFE 511F
BEA1 52DD
BEA2 5320
BEA3 5347
BEA4 53EC
BEA5 54E8
BEA6 5546
BEA7 5531
BEA8 5617
BEA9 5968
BEAA 59BE
BEAB 5A3C
BEAC 5BB5
BEAD 5C06
BEAE 5C0F
BEAF 5C11
BEB0 5C1A
BEB1 5E84
BEB2 5E8A
BEB3 5EE0
BEB4 5F70
BEB5 627F
BEB6 6284
BEB7 62DB
BEB8 638C
BEB9 6377
BEBA 6607
BEBB 660C
BEBC 662D
BEBD 6676
BEBE 677E
BEBF 68A2
BEC0 6A1F
BEC1 6A35
BEC2 6CBC
BEC3 6D88
BEC4 6E09
BEC5 6E58
BEC6 713C
BEC7 7126
BEC8 7167
BEC9 75C7
BECA 7701
BECB 785D
BECC 7901
BECD 7965
BECE 79F0
BECF 7AE0
BED0 7B11
BED1 7CA7
BED2 7D39
BED3 8096
BED4 83D6
BED5 848B
BED6 8549
BED7 885D
BED8 88F3
BED9 8A1F
BEDA 8A3C
BEDB 8A54
BEDC 8A73
BEDD 8C61
BEDE 8CDE
BEDF 91A4
BEE0 9266
BEE1 937E
BEE2 9418
BEE3 969C
BEE4 9798
BEE5 4E0A
BEE6 4E08
BEE7 4E1E
BEE8 4E57
BEE9 5197
BEEA 5270
BEEB 57CE
BEEC 5834
BEED 58CC
BEEE 5B22
BEEF 5E38
BEF0 60C5
BEF1 64FE
BEF2 6761
BEF3 6756
BEF4 6D44
BEF5 72B6
BEF6 7573
BEF7 7A63
BEF8 84B8
BEF9 8B72
BEFA 91B8
BEFB 9320
BEFC 5631
BEFD 57F4
BEFE 98FE
BFA1 62ED
BFA2 690D
BFA3 6B96
BFA4 71ED
BFA5 7E54
BFA6 8077
BFA7 8272
BFA8 89E6
BFA9 98DF
BFAA 8755
BFAB 8FB1
BFAC 5C3B
BFAD 4F38
BFAE 4FE1
BFAF 4FB5
BFB0 5507
BFB1 5A20
BFB2 5BDD
BFB3 5BE9
BFB4 5FC3
BFB5 614E
BFB6 632F
BFB7 65B0
BFB8 664B
BFB9 68EE
BFBA 699B
BFBB 6D78
BFBC 6DF1
BFBD 7533
BFBE 75B9
BFBF 771F
BFC0 795E
BFC1 79E6
BFC2 7D33
BFC3 81E3
BFC4 82AF
BFC5 85AA
BFC6 89AA
BFC7 8A3A
BFC8 8EAB
BFC9 8F9B
BFCA 9032
BFCB 91DD
BFCC 9707
BFCD 4EBA
BFCE 4EC1
BFCF 5203
BFD0 5875
BFD1 58EC
BFD2 5C0B
BFD3 751A
BFD4 5C3D
BFD5 814E
BFD6 8A0A
BFD7 8FC5
BFD8 9663
BFD9 976D
BFDA 7B25
BFDB 8ACF
BFDC 9808
BFDD 9162
BFDE 56F3
BFDF 53A8
BFE0 9017
BFE1 5439
BFE2 5782
BFE3 5E25
BFE4 63A8
BFE5 6C34
BFE6 708A
BFE7 7761
BFE8 7C8B
BFE9 7FE0
BFEA 8870
BFEB 9042
BFEC 9154
BFED 9310
BFEE 9318
BFEF 968F
BFF0 745E
BFF1 9AC4
BFF2 5D07
BFF3 5D69
BFF4 6570
BFF5 67A2
BFF6 8DA8
BFF7 96DB
BFF8 636E
BFF9 6749
BFFA 6919
BFFB 83C5
BFFC 9817
BFFD 96C0
BFFE 88FE
C0A1 6F84
C0A2 647A
C0A3 5BF8
C0A4 4E16
C0A5 702C
C0A6 755D
C0A7 662F
C0A8 51C4
C0A9 5236
C0AA 52E2
C0AB 59D3
C0AC 5F81
C0AD 6027
C0AE 6210
C0AF 653F
C0B0 6574
C0B1 661F
C0B2 6674
C0B3 68F2
C0B4 6816
C0B5 6B63
C0B6 6E05
C0B7 7272
C0B8 751F
C0B9 76DB
C0BA 7CBE
C0BB 8056
C0BC 58F0
C0BD 88FD
C0BE 897F
C0BF 8AA0
C0C0 8A93
C0C1 8ACB
C0C2 901D
C0C3 9192
C0C4 9752
C0C5 9759
C0C6 6589
C0C7 7A0E
C0C8 8106
C0C9 96BB
C0CA 5E2D
C0CB 60DC
C0CC 621A
C0CD 65A5
C0CE 6614
C0CF 6790
C0D0 77F3
C0D1 7A4D
C0D2 7C4D
C0D3 7E3E
C0D4 810A
C0D5 8CAC
C0D6 8D64
C0D7 8DE1
C0D8 8E5F
C0D9 78A9
C0DA 5207
C0DB 62D9
C0DC 63A5
C0DD 6442
C0DE 6298
C0DF 8A2D
C0E0 7A83
C0E1 7BC0
C0E2 8AAC
C0E3 96EA
C0E4 7D76
C0E5 820C
C0E6 8749
C0E7 4ED9
C0E8 5148
C0E9 5343
C0EA 5360
C0EB 5BA3
C0EC 5C02
C0ED 5C16
C0EE 5DDD
C0EF 6226
C0F0 6247
C0F1 64B0
C0F2 6813
C0F3 6834
C0F4 6CC9
C0F5 6D45
C0F6 6D17
C0F7 67D3
C0F8 6F5C
C0F9 714E
C0FA 717D
C0FB 65CB
C0FC 7A7F
C0FD 7BAD
C0FE 7DDA
C1A1 7E4A
C1A2 7FA8
C1A3 817A
C1A4 821B
C1A5 8239
C1A6 85A6
C1A7 8A6E
C1A8 8CCE
C1A9 8DF5
C1AA 9078
C1AB 9077
C1AC 92AD
C1AD 9291
C1AE 9583
C1AF 9BAE
C1B0 524D
C1B1 5584
C1B2 6F38
C1B3 7136
C1B4 5168
C1B5 7985
C1B6 7E55
C1B7 81B3
C1B8 7CCE
C1B9 564C
C1BA 5851
C1BB 5CA8
C1BC 63AA
C1BD 66FE
C1BE 66FD
C1BF 695A
C1C0 72D9
C1C1 758F
C1C2 758E
C1C3 790E
C1C4 7956
C1C5 79DF
C1C6 7C97
C1C7 7D20
C1C8 7D44
C1C9 8607
C1CA 8A34
C1CB 963B
C1CC 9061
C1CD 9F20
C1CE 50E7
C1CF 5275
C1D0 53CC
C1D1 53E2
C1D2 5009
C1D3 55AA
C1D4 58EE
C1D5 594F
C1D6 723D
C1D7 5B8B
C1D8 5C64
C1D9 531D
C1DA 60E3
C1DB 60F3
C1DC 635C
C1DD 6383
C1DE 633F
C1DF 63BB
C1E0 64CD
C1E1 65E9
C1E2 66F9
C1E3 5DE3
C1E4 69CD
C1E5 69FD
C1E6 6F15
C1E7 71E5
C1E8 4E89
C1E9 75E9
C1EA 76F8
C1EB 7A93
C1EC 7CDF
C1ED 7DCF
C1EE 7D9C
C1EF 8061
C1F0 8349
C1F1 8358
C1F2 846C
C1F3 84BC
C1F4 85FB
C1F5 88C5
C1F6 8D70
C1F7 9001
C1F8 906D
C1F9 9397
C1FA 971C
C1FB 9A12
C1FC 50CF
C1FD 5897
C1FE 618E
C2A1 81D3
C2A2 8535
C2A3 8D08
C2A4 9020
C2A5 4FC3
C2A6 5074
C2A7 5247
C2A8 5373
C2A9 606F
C2AA 6349
C2AB 675F
C2AC 6E2C
C2AD 8DB3
C2AE 901F
C2AF 4FD7
C2B0 5C5E
C2B1 8CCA
C2B2 65CF
C2B3 7D9A
C2B4 5352
C2B5 8896
C2B6 5176
C2B7 63C3
C2B8 5B58
C2B9 5B6B
C2BA 5C0A
C2BB 640D
C2BC 6751
C2BD 905C
C2BE 4ED6
C2BF 591A
C2C0 592A
C2C1 6C70
C2C2 8A51
C2C3 553E
C2C4 5815
C2C5 59A5
C2C6 60F0
C2C7 6253
C2C8 67C1
C2C9 8235
C2CA 6955
C2CB 9640
C2CC 99C4
C2CD 9A28
C2CE 4F53
C2CF 5806
C2D0 5BFE
C2D1 8010
C2D2 5CB1
C2D3 5E2F
C2D4 5F85
C2D5 6020
C2D6 614B
C2D7 6234
C2D8 66FF
C2D9 6CF0
C2DA 6EDE
C2DB 80CE
C2DC 817F
C2DD 82D4
C2DE 888B
C2DF 8CB8
C2E0 9000
C2E1 902E
C2E2 968A
C2E3 9EDB
C2E4 9BDB
C2E5 4EE3
C2E6 53F0
C2E7 5927
C2E8 7B2C
C2E9 918D
C2EA 984C
C2EB 9DF9
C2EC 6EDD
C2ED 7027
C2EE 5353
C2EF 5544
C2F0 5B85
C2F1 6258
C2F2 629E
C2F3 62D3
C2F4 6CA2
C2F5 6FEF
C2F6 7422
C2F7 8A17
C2F8 9438
C2F9 6FC1
C2FA 8AFE
C2FB 8338
C2FC 51E7
C2FD 86F8
C2FE 53EA
C3A1 53E9
C3A2 4F46
C3A3 9054
C3A4 8FB0
C3A5 596A
C3A6 8131
C3A7 5DFD
C3A8 7AEA
C3A9 8FBF
C3AA 68DA
C3AB 8C37
C3AC 72F8
C3AD 9C48
C3AE 6A3D
C3AF 8AB0
C3B0 4E39
C3B1 5358
C3B2 5606
C3B3 5766
C3B4 62C5
C3B5 63A2
C3B6 65E6
C3B7 6B4E
C3B8 6DE1
C3B9 6E5B
C3BA 70AD
C3BB 77ED
C3BC 7AEF
C3BD 7BAA
C3BE 7DBB
C3BF 803D
C3C0 80C6
C3C1 86CB
C3C2 8A95
C3C3 935B
C3C4 56E3
C3C5 58C7
C3C6 5F3E
C3C7 65AD
C3C8 6696
C3C9 6A80
C3CA 6BB5
C3CB 7537
C3CC 8AC7
C3CD 5024
C3CE 77E5
C3CF 5730
C3D0 5F1B
C3D1 6065
C3D2 667A
C3D3 6C60
C3D4 75F4
C3D5 7A1A
C3D6 7F6E
C3D7 81F4
C3D8 8718
C3D9 9045
C3DA 99B3
C3DB 7BC9
C3DC 755C
C3DD 7AF9
C3DE 7B51
C3DF 84C4
C3E0 9010
C3E1 79E9
C3E2 7A92
C3E3 8336
C3E4 5AE1
C3E5 7740
C3E6 4E2D
C3E7 4EF2
C3E8 5B99
C3E9 5FE0
C3EA 62BD
C3EB 663C
C3EC 67F1
C3ED 6CE8
C3EE 866B
C3EF 8877
C3F0 8A3B
C3F1 914E
C3F2 92F3
C3F3 99D0
C3F4 6A17
C3F5 7026
C3F6 732A
C3F7 82E7
C3F8 8457
C3F9 8CAF
C3FA 4E01
C3FB 5146
C3FC 51CB
C3FD 558B
C3FE 5BF5
C4A1 5E16
C4A2 5E33
C4A3 5E81
C4A4 5F14
C4A5 5F35
C4A6 5F6B
C4A7 5FB4
C4A8 61F2
C4A9 6311
C4AA 66A2
C4AB 671D
C4AC 6F6E
C4AD 7252
C4AE 753A
C4AF 773A
C4B0 8074
C4B1 8139
C4B2 8178
C4B3 8776
C4B4 8ABF
C4B5 8ADC
C4B6 8D85
C4B7 8DF3
C4B8 929A
C4B9 9577
C4BA 9802
C4BB 9CE5
C4BC 52C5
C4BD 6357
C4BE 76F4
C4BF 6715
C4C0 6C88
C4C1 73CD
C4C2 8CC3
C4C3 93AE
C4C4 9673
C4C5 6D25
C4C6 589C
C4C7 690E
C4C8 69CC
C4C9 8FFD
C4CA 939A
C4CB 75DB
C4CC 901A
C4CD 585A
C4CE 6802
C4CF 63B4
C4D0 69FB
C4D1 4F43
C4D2 6F2C
C4D3 67D8
C4D4 8FBB
C4D5 8526
C4D6 7DB4
C4D7 9354
C4D8 693F
C4D9 6F70
C4DA 576A
C4DB 58F7
C4DC 5B2C
C4DD 7D2C
C4DE 722A
C4DF 540A
C4E0 91E3
C4E1 9DB4
C4E2 4EAD
C4E3 4F4E
C4E4 505C
C4E5 5075
C4E6 5243
C4E7 8C9E
C4E8 5448
C4E9 5824
C4EA 5B9A
C4EB 5E1D
C4EC 5E95
C4ED 5EAD
C4EE 5EF7
C4EF 5F1F
C4F0 608C
C4F1 62B5
C4F2 633A
C4F3 63D0
C4F4 68AF
C4F5 6C40
C4F6 7887
C4F7 798E
C4F8 7A0B
C4F9 7DE0
C4FA 8247
C4FB 8A02
C4FC 8AE6
C4FD 8E44
C4FE 9013
C5A1 90B8
C5A2 912D
C5A3 91D8
C5A4 9F0E
C5A5 6CE5
C5A6 6458
C5A7 64E2
C5A8 6575
C5A9 6EF4
C5AA 7684
C5AB 7B1B
C5AC 9069
C5AD 93D1
C5AE 6EBA
C5AF 54F2
C5B0 5FB9
C5B1 64A4
C5B2 8F4D
C5B3 8FED
C5B4 9244
C5B5 5178
C5B6 586B
C5B7 5929
C5B8 5C55
C5B9 5E97
C5BA 6DFB
C5BB 7E8F
C5BC 751C
C5BD 8CBC
C5BE 8EE2
C5BF 985B
C5C0 70B9
C5C1 4F1D
C5C2 6BBF
C5C3 6FB1
C5C4 7530
C5C5 96FB
C5C6 514E
C5C7 5410
C5C8 5835
C5C9 5857
C5CA 59AC
C5CB 5C60
C5CC 5F92
C5CD 6597
C5CE 675C
C5CF 6E21
C5D0 767B
C5D1 83DF
C5D2 8CED
C5D3 9014
C5D4 90FD
C5D5 934D
C5D6 7825
C5D7 783A
C5D8 52AA
C5D9 5EA6
C5DA 571F
C5DB 5974
C5DC 6012
C5DD 5012
C5DE 515A
C5DF 51AC
C5E0 51CD
C5E1 5200
C5E2 5510
C5E3 5854
C5E4 5858
C5E5 5957
C5E6 5B95
C5E7 5CF6
C5E8 5D8B
C5E9 60BC
C5EA 6295
C5EB 642D
C5EC 6771
C5ED 6843
C5EE 68BC
C5EF 68DF
C5F0 76D7
C5F1 6DD8
C5F2 6E6F
C5F3 6D9B
C5F4 706F
C5F5 71C8
C5F6 5F53
C5F7 75D8
C5F8 7977
C5F9 7B49
C5FA 7B54
C5FB 7B52
C5FC 7CD6
C5FD 7D71
C5FE 5230
C6A1 8463
C6A2 8569
C6A3 85E4
C6A4 8A0E
C6A5 8B04
C6A6 8C46
C6A7 8E0F
C6A8 9003
C6A9 900F
C6AA 9419
C6AB 9676
C6AC 982D
C6AD 9A30
C6AE 95D8
C6AF 50CD
C6B0 52D5
C6B1 540C
C6B2 5802
C6B3 5C0E
C6B4 61A7
C6B5 649E
C6B6 6D1E
C6B7 77B3
C6B8 7AE5
C6B9 80F4
C6BA 8404
C6BB 9053
C6BC 9285
C6BD 5CE0
C6BE 9D07
C6BF 533F
C6C0 5F97
C6C1 5FB3
C6C2 6D9C
C6C3 7279
C6C4 7763
C6C5 79BF
C6C6 7BE4
C6C7 6BD2
C6C8 72EC
C6C9 8AAD
C6CA 6803
C6CB 6A61
C6CC 51F8
C6CD 7A81
C6CE 6934
C6CF 5C4A
C6D0 9CF6
C6D1 82EB
C6D2 5BC5
C6D3 9149
C6D4 701E
C6D5 5678
C6D6 5C6F
C6D7 60C7
C6D8 6566
C6D9 6C8C
C6DA 8C5A
C6DB 9041
C6DC 9813
C6DD 5451
C6DE 66C7
C6DF 920D
C6E0 5948
C6E1 90A3
C6E2 5185
C6E3 4E4D
C6E4 51EA
C6E5 8599
C6E6 8B0E
C6E7 7058
C6E8 637A
C6E9 934B
C6EA 6962
C6EB 99B4
C6EC 7E04
C6ED 7577
C6EE 5357
C6EF 6960
C6F0 8EDF
C6F1 96E3
C6F2 6C5D
C6F3 4E8C
C6F4 5C3C
C6F5 5F10
C6F6 8FE9
C6F7 5302
C6F8 8CD1
C6F9 8089
C6FA 8679
C6FB 5EFF
C6FC 65E5
C6FD 4E73
C6FE 5165
C7A1 5982
C7A2 5C3F
C7A3 97EE
C7A4 4EFB
C7A5 598A
C7A6 5FCD
C7A7 8A8D
C7A8 6FE1
C7A9 79B0
C7AA 7962
C7AB 5BE7
C7AC 8471
C7AD 732B
C7AE 71B1
C7AF 5E74
C7B0 5FF5
C7B1 637B
C7B2 649A
C7B3 71C3
C7B4 7C98
C7B5 4E43
C7B6 5EFC
C7B7 4E4B
C7B8 57DC
C7B9 56A2
C7BA 60A9
C7BB 6FC3
C7BC 7D0D
C7BD 80FD
C7BE 8133
C7BF 81BF
C7C0 8FB2
C7C1 8997
C7C2 86A4
C7C3 5DF4
C7C4 628A
C7C5 64AD
C7C6 8987
C7C7 6777
C7C8 6CE2
C7C9 6D3E
C7CA 7436
C7CB 7834
C7CC 5A46
C7CD 7F75
C7CE 82AD
C7CF 99AC
C7D0 4FF3
C7D1 5EC3
C7D2 62DD
C7D3 6392
C7D4 6557
C7D5 676F
C7D6 76C3
C7D7 724C
C7D8 80CC
C7D9 80BA
C7DA 8F29
C7DB 914D
C7DC 500D
C7DD 57F9
C7DE 5A92
C7DF 6885
C7E0 6973
C7E1 7164
C7E2 72FD
C7E3 8CB7
C7E4 58F2
C7E5 8CE0
C7E6 966A
C7E7 9019
C7E8 877F
C7E9 79E4
C7EA 77E7
C7EB 8429
C7EC 4F2F
C7ED 5265
C7EE 535A
C7EF 62CD
C7F0 67CF
C7F1 6CCA
C7F2 767D
C7F3 7B94
C7F4 7C95
C7F5 8236
C7F6 8584
C7F7 8FEB
C7F8 66DD
C7F9 6F20
C7FA 7206
C7FB 7E1B
C7FC 83AB
C7FD 99C1
C7FE 9EA6
C8A1 51FD
C8A2 7BB1
C8A3 7872
C8A4 7BB8
C8A5 8087
C8A6 7B48
C8A7 6AE8
C8A8 5E61
C8A9 808C
C8AA 7551
C8AB 7560
C8AC 516B
C8AD 9262
C8AE 6E8C
C8AF 767A
C8B0 9197
C8B1 9AEA
C8B2 4F10
C8B3 7F70
C8B4 629C
C8B5 7B4F
C8B6 95A5
C8B7 9CE9
C8B8 567A
C8B9 5859
C8BA 86E4
C8BB 96BC
C8BC 4F34
C8BD 5224
C8BE 534A
C8BF 53CD
C8C0 53DB
C8C1 5E06
C8C2 642C
C8C3 6591
C8C4 677F
C8C5 6C3E
C8C6 6C4E
C8C7 7248
C8C8 72AF
C8C9 73ED
C8CA 7554
C8CB 7E41
C8CC 822C
C8CD 85E9
C8CE 8CA9
C8CF 7BC4
C8D0 91C6
C8D1 7169
C8D2 9812
C8D3 98EF
C8D4 633D
C8D5 6669
C8D6 756A
C8D7 76E4
C8D8 78D0
C8D9 8543
C8DA 86EE
C8DB 532A
C8DC 5351
C8DD 5426
C8DE 5983
C8DF 5E87
C8E0 5F7C
C8E1 60B2
C8E2 6249
C8E3 6279
C8E4 62AB
C8E5 6590
C8E6 6BD4
C8E7 6CCC
C8E8 75B2
C8E9 76AE
C8EA 7891
C8EB 79D8
C8EC 7DCB
C8ED 7F77
C8EE 80A5
C8EF 88AB
C8F0 8AB9
C8F1 8CBB
C8F2 907F
C8F3 975E
C8F4 98DB
C8F5 6A0B
C8F6 7C38
C8F7 5099
C8F8 5C3E
C8F9 5FAE
C8FA 6787
C8FB 6BD8
C8FC 7435
C8FD 7709
C8FE 7F8E
C9A1 9F3B
C9A2 67CA
C9A3 7A17
C9A4 5339
C9A5 758B
C9A6 9AED
C9A7 5F66
C9A8 819D
C9A9 83F1
C9AA 8098
C9AB 5F3C
C9AC 5FC5
C9AD 7562
C9AE 7B46
C9AF 903C
C9B0 6867
C9B1 59EB
C9B2 5A9B
C9B3 7D10
C9B4 767E
C9B5 8B2C
C9B6 4FF5
C9B7 5F6A
C9B8 6A19
C9B9 6C37
C9BA 6F02
C9BB 74E2
C9BC 7968
C9BD 8868
C9BE 8A55
C9BF 8C79
C9C0 5EDF
C9C1 63CF
C9C2 75C5
C9C3 79D2
C9C4 82D7
C9C5 9328
C9C6 92F2
C9C7 849C
C9C8 86ED
C9C9 9C2D
C9CA 54C1
C9CB 5F6C
C9CC 658C
C9CD 6D5C
C9CE 7015
C9CF 8CA7
C9D0 8CD3
C9D1 983B
C9D2 654F
C9D3 74F6
C9D4 4E0D
C9D5 4ED8
C9D6 57E0
C9D7 592B
C9D8 5A66
C9D9 5BCC
C9DA 51A8
C9DB 5E03
C9DC 5E9C
C9DD 6016
C9DE 6276
C9DF 6577
C9E0 65A7
C9E1 666E
C9E2 6D6E
C9E3 7236
C9E4 7B26
C9E5 8150
C9E6 819A
C9E7 8299
C9E8 8B5C
C9E9 8CA0
C9EA 8CE6
C9EB 8D74
C9EC 961C
C9ED 9644
C9EE 4FAE
C9EF 64AB
C9F0 6B66
C9F1 821E
C9F2 8461
C9F3 856A
C9F4 90E8
C9F5 5C01
C9F6 6953
C9F7 98A8
C9F8 847A
C9F9 8557
C9FA 4F0F
C9FB 526F
C9FC 5FA9
C9FD 5E45
C9FE 670D
CAA1 798F
CAA2 8179
CAA3 8907
CAA4 8986
CAA5 6DF5
CAA6 5F17
CAA7 6255
CAA8 6CB8
CAA9 4ECF
CAAA 7269
CAAB 9B92
CAAC 5206
CAAD 543B
CAAE 5674
CAAF 58B3
CAB0 61A4
CAB1 626E
CAB2 711A
CAB3 596E
CAB4 7C89
CAB5 7CDE
CAB6 7D1B
CAB7 96F0
CAB8 6587
CAB9 805E
CABA 4E19
CABB 4F75
CABC 5175
CABD 5840
CABE 5E63
CABF 5E73
CAC0 5F0A
CAC1 67C4
CAC2 4E26
CAC3 853D
CAC4 9589
CAC5 965B
CAC6 7C73
CAC7 9801
CAC8 50FB
CAC9 58C1
CACA 7656
CACB 78A7
CACC 5225
CACD 77A5
CACE 8511
CACF 7B86
CAD0 504F
CAD1 5909
CAD2 7247
CAD3 7BC7
CAD4 7DE8
CAD5 8FBA
CAD6 8FD4
CAD7 904D
CAD8 4FBF
CAD9 52C9
CADA 5A29
CADB 5F01
CADC 97AD
CADD 4FDD
CADE 8217
CADF 92EA
CAE0 5703
CAE1 6355
CAE2 6B69
CAE3 752B
CAE4 88DC
CAE5 8F14
CAE6 7A42
CAE7 52DF
CAE8 5893
CAE9 6155
CAEA 620A
CAEB 66AE
CAEC 6BCD
CAED 7C3F
CAEE 83E9
CAEF 5023
CAF0 4FF8
CAF1 5305
CAF2 5446
CAF3 5831
CAF4 5949
CAF5 5B9D
CAF6 5CF0
CAF7 5CEF
CAF8 5D29
CAF9 5E96
CAFA 62B1
CAFB 6367
CAFC 653E
CAFD 65B9
CAFE 670B
CBA1 6CD5
CBA2 6CE1
CBA3 70F9
CBA4 7832
CBA5 7E2B
CBA6 80DE
CBA7 82B3
CBA8 840C
CBA9 84EC
CBAA 8702
CBAB 8912
CBAC 8A2A
CBAD 8C4A
CBAE 90A6
CBAF 92D2
CBB0 98FD
CBB1 9CF3
CBB2 9D6C
CBB3 4E4F
CBB4 4EA1
CBB5 508D
CBB6 5256
CBB7 574A
CBB8 59A8
CBB9 5E3D
CBBA 5FD8
CBBB 5FD9
CBBC 623F
CBBD 66B4
CBBE 671B
CBBF 67D0
CBC0 68D2
CBC1 5192
CBC2 7D21
CBC3 80AA
CBC4 81A8
CBC5 8B00
CBC6 8C8C
CBC7 8CBF
CBC8 927E
CBC9 9632
CBCA 5420
CBCB 982C
CBCC 5317
CBCD 50D5
CBCE 535C
CBCF 58A8
CBD0 64B2
CBD1 6734
CBD2 7267
CBD3 7766
CBD4 7A46
CBD5 91E6
CBD6 52C3
CBD7 6CA1
CBD8 6B86
CBD9 5800
CBDA 5E4C
CBDB 5954
CBDC 672C
CBDD 7FFB
CBDE 51E1
CBDF 76C6
CBE0 6469
CBE1 78E8
CBE2 9B54
CBE3 9EBB
CBE4 57CB
CBE5 59B9
CBE6 6627
CBE7 679A
CBE8 6BCE
CBE9 54E9
CBEA 69D9
CBEB 5E55
CBEC 819C
CBED 6795
CBEE 9BAA
CBEF 67FE
CBF0 9C52
CBF1 685D
CBF2 4EA6
CBF3 4FE3
CBF4 53C8
CBF5 62B9
CBF6 672B
CBF7 6CAB
CBF8 8FC4
CBF9 4FAD
CBFA 7E6D
CBFB 9EBF
CBFC 4E07
CBFD 6162
CBFE 6E80
CCA1 6F2B
CCA2 8513
CCA3 5473
CCA4 672A
CCA5 9B45
CCA6 5DF3
CCA7 7B95
CCA8 5CAC
CCA9 5BC6
CCAA 871C
CCAB 6E4A
CCAC 84D1
CCAD 7A14
CCAE 8108
CCAF 5999
CCB0 7C8D
CCB1 6C11
CCB2 7720
CCB3 52D9
CCB4 5922
CCB5 7121
CCB6 725F
CCB7 77DB
CCB8 9727
CCB9 9D61
CCBA 690B
CCBB 5A7F
CCBC 5A18
CCBD 51A5
CCBE 540D
CCBF 547D
CCC0 660E
CCC1 76DF
CCC2 8FF7
CCC3 9298
CCC4 9CF4
CCC5 59EA
CCC6 725D
CCC7 6EC5
CCC8 514D
CCC9 68C9
CCCA 7DBF
CCCB 7DEC
CCCC 9762
CCCD 9EBA
CCCE 6478
CCCF 6A21
CCD0 8302
CCD1 5984
CCD2 5B5F
CCD3 6BDB
CCD4 731B
CCD5 76F2
CCD6 7DB2
CCD7 8017
CCD8 8499
CCD9 5132
CCDA 6728
CCDB 9ED9
CCDC 76EE
CCDD 6762
CCDE 52FF
CCDF 9905
CCE0 5C24
CCE1 623B
CCE2 7C7E
CCE3 8CB0
CCE4 554F
CCE5 60B6
CCE6 7D0B
CCE7 9580
CCE8 5301
CCE9 4E5F
CCEA 51B6
CCEB 591C
CCEC 723A
CCED 8036
CCEE 91CE
CCEF 5F25
CCF0 77E2
CCF1 5384
CCF2 5F79
CCF3 7D04
CCF4 85AC
CCF5 8A33
CCF6 8E8D
CCF7 9756
CCF8 67F3
CCF9 85AE
CCFA 9453
CCFB 6109
CCFC 6108
CCFD 6CB9
CCFE 7652
CDA1 8AED
CDA2 8F38
CDA3 552F
CDA4 4F51
CDA5 512A
CDA6 52C7
CDA7 53CB
CDA8 5BA5
CDA9 5E7D
CDAA 60A0
CDAB 6182
CDAC 63D6
CDAD 6709
CDAE 67DA
CDAF 6E67
CDB0 6D8C
CDB1 7336
CDB2 7337
CDB3 7531
CDB4 7950
CDB5 88D5
CDB6 8A98
CDB7 904A
CDB8 9091
CDB9 90F5
CDBA 96C4
CDBB 878D
CDBC 5915
CDBD 4E88
CDBE 4F59
CDBF 4E0E
CDC0 8A89
CDC1 8F3F
CDC2 9810
CDC3 50AD
CDC4 5E7C
CDC5 5996
CDC6 5BB9
CDC7 5EB8
CDC8 63DA
CDC9 63FA
CDCA 64C1
CDCB 66DC
CDCC 694A
CDCD 69D8
CDCE 6D0B
CDCF 6EB6
CDD0 7194
CDD1 7528
CDD2 7AAF
CDD3 7F8A
CDD4 8000
CDD5 8449
CDD6 84C9
CDD7 8981
CDD8 8B21
CDD9 8E0A
CDDA 9065
CDDB 967D
CDDC 990A
CDDD 617E
CDDE 6291
CDDF 6B32
CDE0 6C83
CDE1 6D74
CDE2 7FCC
CDE3 7FFC
CDE4 6DC0
CDE5 7F85
CDE6 87BA
CDE7 88F8
CDE8 6765
CDE9 83B1
CDEA 983C
CDEB 96F7
CDEC 6D1B
CDED 7D61
CDEE 843D
CDEF 916A
CDF0 4E71
CDF1 5375
CDF2 5D50
CDF3 6B04
CDF4 6FEB
CDF5 85CD
CDF6 862D
CDF7 89A7
CDF8 5229
CDF9 540F
CDFA 5C65
CDFB 674E
CDFC 68A8
CDFD 7406
CDFE 7483
CEA1 75E2
CEA2 88CF
CEA3 88E1
CEA4 91CC
CEA5 96E2
CEA6 9678
CEA7 5F8B
CEA8 7387
CEA9 7ACB
CEAA 844E
CEAB 63A0
CEAC 7565
CEAD 5289
CEAE 6D41
CEAF 6E9C
CEB0 7409
CEB1 7559
CEB2 786B
CEB3 7C92
CEB4 9686
CEB5 7ADC
CEB6 9F8D
CEB7 4FB6
CEB8 616E
CEB9 65C5
CEBA 865C
CEBB 4E86
CEBC 4EAE
CEBD 50DA
CEBE 4E21
CEBF 51CC
CEC0 5BEE
CEC1 6599
CEC2 6881
CEC3 6DBC
CEC4 731F
CEC5 7642
CEC6 77AD
CEC7 7A1C
CEC8 7CE7
CEC9 826F
CECA 8AD2
CECB 907C
CECC 91CF
CECD 9675
CECE 9818
CECF 529B
CED0 7DD1
CED1 502B
CED2 5398
CED3 6797
CED4 6DCB
CED5 71D0
CED6 7433
CED7 81E8
CED8 8F2A
CED9 96A3
CEDA 9C57
CEDB 9E9F
CEDC 7460
CEDD 5841
CEDE 6D99
CEDF 7D2F
CEE0 985E
CEE1 4EE4
CEE2 4F36
CEE3 4F8B
CEE4 51B7
CEE5 52B1
CEE6 5DBA
CEE7 601C
CEE8 73B2
CEE9 793C
CEEA 82D3
CEEB 9234
CEEC 96B7
CEED 96F6
CEEE 970A
CEEF 9E97
CEF0 9F62
CEF1 66A6
CEF2 6B74
CEF3 5217
CEF4 52A3
CEF5 70C8
CEF6 88C2
CEF7 5EC9
CEF8 604B
CEF9 6190
CEFA 6F23
CEFB 7149
CEFC 7C3E
CEFD 7DF4
CEFE 806F
CFA1 84EE
CFA2 9023
CFA3 932C
CFA4 5442
CFA5 9B6F
CFA6 6AD3
CFA7 7089
CFA8 8CC2
CFA9 8DEF
CFAA 9732
CFAB 52B4
CFAC 5A41
CFAD 5ECA
CFAE 5F04
CFAF 6717
CFB0 697C
CFB1 6994
CFB2 6D6A
CFB3 6F0F
CFB4 7262
CFB5 72FC
CFB6 7BED
CFB7 8001
CFB8 807E
CFB9 874B
CFBA 90CE
CFBB 516D
CFBC 9E93
CFBD 7984
CFBE 808B
CFBF 9332
CFC0 8AD6
CFC1 502D
CFC2 548C
CFC3 8A71
CFC4 6B6A
CFC5 8CC4
CFC6 8107
CFC7 60D1
CFC8 67A0
CFC9 9DF2
CFCA 4E99
CFCB 4E98
CFCC 9C10
CFCD 8A6B
CFCE 85C1
CFCF 8568
CFD0 6900
CFD1 6E7E
CFD2 7897
CFD3 8155
D0A1 5F0C
D0A2 4E10
D0A3 4E15
D0A4 4E2A
D0A5 4E31
D0A6 4E36
D0A7 4E3C
D0A8 4E3F
D0A9 4E42
D0AA 4E56
D0AB 4E58
D0AC 4E82
D0AD 4E85
D0AE 8C6B
D0AF 4E8A
D0B0 8212
D0B1 5F0D
D0B2 4E8E
D0B3 4E9E
D0B4 4E9F
D0B5 4EA0
D0B6 4EA2
D0B7 4EB0
D0B8 4EB3
D0B9 4EB6
D0BA 4ECE
D0BB 4ECD
D0BC 4EC4
D0BD 4EC6
D0BE 4EC2
D0BF 4ED7
D0C0 4EDE
D0C1 4EED
D0C2 4EDF
D0C3 4EF7
D0C4 4F09
D0C5 4F5A
D0C6 4F30
D0C7 4F5B
D0C8 4F5D
D0C9 4F57
D0CA 4F47
D0CB 4F76
D0CC 4F88
D0CD 4F8F
D0CE 4F98
D0CF 4F7B
D0D0 4F69
D0D1 4F70
D0D2 4F91
D0D3 4F6F
D0D4 4F86
D0D5 4F96
D0D6 5118
D0D7 4FD4
D0D8 4FDF
D0D9 4FCE
D0DA 4FD8
D0DB 4FDB
D0DC 4FD1
D0DD 4FDA
D0DE 4FD0
D0DF 4FE4
D0E0 4FE5
D0E1 501A
D0E2 5028
D0E3 5014
D0E4 502A
D0E5 5025
D0E6 5005
D0E7 4F1C
D0E8 4FF6
D0E9 5021
D0EA 5029
D0EB 502C
D0EC 4FFE
D0ED 4FEF
D0EE 5011
D0EF 5006
D0F0 5043
D0F1 5047
D0F2 6703
D0F3 5055
D0F4 5050
D0F5 5048
D0F6 505A
D0F7 5056
D0F8 506C
D0F9 5078
D0FA 5080
D0FB 509A
D0FC 5085
D0FD 50B4
D0FE 50B2
D1A1 50C9
D1A2 50CA
D1A3 50B3
D1A4 50C2
D1A5 50D6
D1A6 50DE
D1A7 50E5
D1A8 50ED
D1A9 50E3
D1AA 50EE
D1AB 50F9
D1AC 50F5
D1AD 5109
D1AE 5101
D1AF 5102
D1B0 5116
D1B1 5115
D1B2 5114
D1B3 511A
D1B4 5121
D1B5 513A
D1B6 5137
D1B7 513C
D1B8 513B
D1B9 513F
D1BA 5140
D1BB 5152
D1BC 514C
D1BD 5154
D1BE 5162
D1BF 7AF8
D1C0 5169
D1C1 516A
D1C2 516E
D1C3 5180
D1C4 5182
D1C5 56D8
D1C6 518C
D1C7 5189
D1C8 518F
D1C9 5191
D1CA 5193
D1CB 5195
D1CC 5196
D1CD 51A4
D1CE 51A6
D1CF 51A2
D1D0 51A9
D1D1 51AA
D1D2 51AB
D1D3 51B3
D1D4 51B1
D1D5 51B2
D1D6 51B0
D1D7 51B5
D1D8 51BD
D1D9 51C5
D1DA 51C9
D1DB 51DB
D1DC 51E0
D1DD 8655
D1DE 51E9
D1DF 51ED
D1E0 51F0
D1E1 51F5
D1E2 51FE
D1E3 5204
D1E4 520B
D1E5 5214
D1E6 520E
D1E7 5227
D1E8 522A
D1E9 522E
D1EA 5233
D1EB 5239
D1EC 524F
D1ED 5244
D1EE 524B
D1EF 524C
D1F0 525E
D1F1 5254
D1F2 526A
D1F3 5274
D1F4 5269
D1F5 5273
D1F6 527F
D1F7 527D
D1F8 528D
D1F9 5294
D1FA 5292
D1FB 5271
D1FC 5288
D1FD 5291
D1FE 8FA8
D2A1 8FA7
D2A2 52AC
D2A3 52AD
D2A4 52BC
D2A5 52B5
D2A6 52C1
D2A7 52CD
D2A8 52D7
D2A9 52DE
D2AA 52E3
D2AB 52E6
D2AC 98ED
D2AD 52E0
D2AE 52F3
D2AF 52F5
D2B0 52F8
D2B1 52F9
D2B2 5306
D2B3 5308
D2B4 7538
D2B5 530D
D2B6 5310
D2B7 530F
D2B8 5315
D2B9 531A
D2BA 5323
D2BB 532F
D2BC 5331
D2BD 5333
D2BE 5338
D2BF 5340
D2C0 5346
D2C1 5345
D2C2 4E17
D2C3 5349
D2C4 534D
D2C5 51D6
D2C6 535E
D2C7 5369
D2C8 536E
D2C9 5918
D2CA 537B
D2CB 5377
D2CC 5382
D2CD 5396
D2CE 53A0
D2CF 53A6
D2D0 53A5
D2D1 53AE
D2D2 53B0
D2D3 53B6
D2D4 53C3
D2D5 7C12
D2D6 96D9
D2D7 53DF
D2D8 66FC
D2D9 71EE
D2DA 53EE
D2DB 53E8
D2DC 53ED
D2DD 53FA
D2DE 5401
D2DF 543D
D2E0 5440
D2E1 542C
D2E2 542D
D2E3 543C
D2E4 542E
D2E5 5436
D2E6 5429
D2E7 541D
D2E8 544E
D2E9 548F
D2EA 5475
D2EB 548E
D2EC 545F
D2ED 5471
D2EE 5477
D2EF 5470
D2F0 5492
D2F1 547B
D2F2 5480
D2F3 5476
D2F4 5484
D2F5 5490
D2F6 5486
D2F7 54C7
D2F8 54A2
D2F9 54B8
D2FA 54A5
D2FB 54AC
D2FC 54C4
D2FD 54C8
D2FE 54A8
D3A1 54AB
D3A2 54C2
D3A3 54A4
D3A4 54BE
D3A5 54BC
D3A6 54D8
D3A7 54E5
D3A8 54E6
D3A9 550F
D3AA 5514
D3AB 54FD
D3AC 54EE
D3AD 54ED
D3AE 54FA
D3AF 54E2
D3B0 5539
D3B1 5540
D3B2 5563
D3B3 554C
D3B4 552E
D3B5 555C
D3B6 5545
D3B7 5556
D3B8 5557
D3B9 5538
D3BA 5533
D3BB 555D
D3BC 5599
D3BD 5580
D3BE 54AF
D3BF 558A
D3C0 559F
D3C1 557B
D3C2 557E
D3C3 5598
D3C4 559E
D3C5 55AE
D3C6 557C
D3C7 5583
D3C8 55A9
D3C9 5587
D3CA 55A8
D3CB 55DA
D3CC 55C5
D3CD 55DF
D3CE 55C4
D3CF 55DC
D3D0 55E4
D3D1 55D4
D3D2 5614
D3D3 55F7
D3D4 5616
D3D5 55FE
D3D6 55FD
D3D7 561B
D3D8 55F9
D3D9 564E
D3DA 5650
D3DB 71DF
D3DC 5634
D3DD 5636
D3DE 5632
D3DF 5638
D3E0 566B
D3E1 5664
D3E2 562F
D3E3 566C
D3E4 566A
D3E5 5686
D3E6 5680
D3E7 568A
D3E8 56A0
D3E9 5694
D3EA 568F
D3EB 56A5
D3EC 56AE
D3ED 56B6
D3EE 56B4
D3EF 56C2
D3F0 56BC
D3F1 56C1
D3F2 56C3
D3F3 56C0
D3F4 56C8
D3F5 56CE
D3F6 56D1
D3F7 56D3
D3F8 56D7
D3F9 56EE
D3FA 56F9
D3FB 5700
D3FC 56FF
D3FD 5704
D3FE 5709
D4A1 5708
D4A2 570B
D4A3 570D
D4A4 5713
D4A5 5718
D4A6 5716
D4A7 55C7
D4A8 571C
D4A9 5726
D4AA 5737
D4AB 5738
D4AC 574E
D4AD 573B
D4AE 5740
D4AF 574F
D4B0 5769
D4B1 57C0
D4B2 5788
D4B3 5761
D4B4 577F
D4B5 5789
D4B6 5793
D4B7 57A0
D4B8 57B3
D4B9 57A4
D4BA 57AA
D4BB 57B0
D4BC 57C3
D4BD 57C6
D4BE 57D4
D4BF 57D2
D4C0 57D3
D4C1 580A
D4C2 57D6
D4C3 57E3
D4C4 580B
D4C5 5819
D4C6 581D
D4C7 5872
D4C8 5821
D4C9 5862
D4CA 584B
D4CB 5870
D4CC 6BC0
D4CD 5852
D4CE 583D
D4CF 5879
D4D0 5885
D4D1 58B9
D4D2 589F
D4D3 58AB
D4D4 58BA
D4D5 58DE
D4D6 58BB
D4D7 58B8
D4D8 58AE
D4D9 58C5
D4DA 58D3
D4DB 58D1
D4DC 58D7
D4DD 58D9
D4DE 58D8
D4DF 58E5
D4E0 58DC
D4E1 58E4
D4E2 58DF
D4E3 58EF
D4E4 58FA
D4E5 58F9
D4E6 58FB
D4E7 58FC
D4E8 58FD
D4E9 5902
D4EA 590A
D4EB 5910
D4EC 591B
D4ED 68A6
D4EE 5925
D4EF 592C
D4F0 592D
D4F1 5932
D4F2 5938
D4F3 593E
D4F4 7AD2
D4F5 5955
D4F6 5950
D4F7 594E
D4F8 595A
D4F9 5958
D4FA 5962
D4FB 5960
D4FC 5967
D4FD 596C
D4FE 5969
D5A1 5978
D5A2 5981
D5A3 599D
D5A4 4F5E
D5A5 4FAB
D5A6 59A3
D5A7 59B2
D5A8 59C6
D5A9 59E8
D5AA 59DC
D5AB 598D
D5AC 59D9
D5AD 59DA
D5AE 5A25
D5AF 5A1F
D5B0 5A11
D5B1 5A1C
D5B2 5A09
D5B3 5A1A
D5B4 5A40
D5B5 5A6C
D5B6 5A49
D5B7 5A35
D5B8 5A36
D5B9 5A62
D5BA 5A6A
D5BB 5A9A
D5BC 5ABC
D5BD 5ABE
D5BE 5ACB
D5BF 5AC2
D5C0 5ABD
D5C1 5AE3
D5C2 5AD7
D5C3 5AE6
D5C4 5AE9
D5C5 5AD6
D5C6 5AFA
D5C7 5AFB
D5C8 5B0C
D5C9 5B0B
D5CA 5B16
D5CB 5B32
D5CC 5AD0
D5CD 5B2A
D5CE 5B36
D5CF 5B3E
D5D0 5B43
D5D1 5B45
D5D2 5B40
D5D3 5B51
D5D4 5B55
D5D5 5B5A
D5D6 5B5B
D5D7 5B65
D5D8 5B69
D5D9 5B70
D5DA 5B73
D5DB 5B75
D5DC 5B78
D5DD 6588
D5DE 5B7A
D5DF 5B80
D5E0 5B83
D5E1 5BA6
D5E2 5BB8
D5E3 5BC3
D5E4 5BC7
D5E5 5BC9
D5E6 5BD4
D5E7 5BD0
D5E8 5BE4
D5E9 5BE6
D5EA 5BE2
D5EB 5BDE
D5EC 5BE5
D5ED 5BEB
D5EE 5BF0
D5EF 5BF6
D5F0 5BF3
D5F1 5C05
D5F2 5C07
D5F3 5C08
D5F4 5C0D
D5F5 5C13
D5F6 5C20
D5F7 5C22
D5F8 5C28
D5F9 5C38
D5FA 5C39
D5FB 5C41
D5FC 5C46
D5FD 5C4E
D5FE 5C53
D6A1 5C50
D6A2 5C4F
D6A3 5B71
D6A4 5C6C
D6A5 5C6E
D6A6 4E62
D6A7 5C76
D6A8 5C79
D6A9 5C8C
D6AA 5C91
D6AB 5C94
D6AC 599B
D6AD 5CAB
D6AE 5CBB
D6AF 5CB6
D6B0 5CBC
D6B1 5CB7
D6B2 5CC5
D6B3 5CBE
D6B4 5CC7
D6B5 5CD9
D6B6 5CE9
D6B7 5CFD
D6B8 5CFA
D6B9 5CED
D6BA 5D8C
D6BB 5CEA
D6BC 5D0B
D6BD 5D15
D6BE 5D17
D6BF 5D5C
D6C0 5D1F
D6C1 5D1B
D6C2 5D11
D6C3 5D14
D6C4 5D22
D6C5 5D1A
D6C6 5D19
D6C7 5D18
D6C8 5D4C
D6C9 5D52
D6CA 5D4E
D6CB 5D4B
D6CC 5D6C
D6CD 5D73
D6CE 5D76
D6CF 5D87
D6D0 5D84
D6D1 5D82
D6D2 5DA2
D6D3 5D9D
D6D4 5DAC
D6D5 5DAE
D6D6 5DBD
D6D7 5D90
D6D8 5DB7
D6D9 5DBC
D6DA 5DC9
D6DB 5DCD
D6DC 5DD3
D6DD 5DD2
D6DE 5DD6
D6DF 5DDB
D6E0 5DEB
D6E1 5DF2
D6E2 5DF5
D6E3 5E0B
D6E4 5E1A
D6E5 5E19
D6E6 5E11
D6E7 5E1B
D6E8 5E36
D6E9 5E37
D6EA 5E44
D6EB 5E43
D6EC 5E40
D6ED 5E4E
D6EE 5E57
D6EF 5E54
D6F0 5E5F
D6F1 5E62
D6F2 5E64
D6F3 5E47
D6F4 5E75
D6F5 5E76
D6F6 5E7A
D6F7 9EBC
D6F8 5E7F
D6F9 5EA0
D6FA 5EC1
D6FB 5EC2
D6FC 5EC8
D6FD 5ED0
D6FE 5ECF
D7A1 5ED6
D7A2 5EE3
D7A3 5EDD
D7A4 5EDA
D7A5 5EDB
D7A6 5EE2
D7A7 5EE1
D7A8 5EE8
D7A9 5EE9
D7AA 5EEC
D7AB 5EF1
D7AC 5EF3
D7AD 5EF0
D7AE 5EF4
D7AF 5EF8
D7B0 5EFE
D7B1 5F03
D7B2 5F09
D7B3 5F5D
D7B4 5F5C
D7B5 5F0B
D7B6 5F11
D7B7 5F16
D7B8 5F29
D7B9 5F2D
D7BA 5F38
D7BB 5F41
D7BC 5F48
D7BD 5F4C
D7BE 5F4E
D7BF 5F2F
D7C0 5F51
D7C1 5F56
D7C2 5F57
D7C3 5F59
D7C4 5F61
D7C5 5F6D
D7C6 5F73
D7C7 5F77
D7C8 5F83
D7C9 5F82
D7CA 5F7F
D7CB 5F8A
D7CC 5F88
D7CD 5F91
D7CE 5F87
D7CF 5F9E
D7D0 5F99
D7D1 5F98
D7D2 5FA0
D7D3 5FA8
D7D4 5FAD
D7D5 5FBC
D7D6 5FD6
D7D7 5FFB
D7D8 5FE4
D7D9 5FF8
D7DA 5FF1
D7DB 5FDD
D7DC 60B3
D7DD 5FFF
D7DE 6021
D7DF 6060
D7E0 6019
D7E1 6010
D7E2 6029
D7E3 600E
D7E4 6031
D7E5 601B
D7E6 6015
D7E7 602B
D7E8 6026
D7E9 600F
D7EA 603A
D7EB 605A
D7EC 6041
D7ED 606A
D7EE 6077
D7EF 605F
D7F0 604A
D7F1 6046
D7F2 604D
D7F3 6063
D7F4 6043
D7F5 6064
D7F6 6042
D7F7 606C
D7F8 606B
D7F9 6059
D7FA 6081
D7FB 608D
D7FC 60E7
D7FD 6083
D7FE 609A
D8A1 6084
D8A2 609B
D8A3 6096
D8A4 6097
D8A5 6092
D8A6 60A7
D8A7 608B
D8A8 60E1
D8A9 60B8
D8AA 60E0
D8AB 60D3
D8AC 60B4
D8AD 5FF0
D8AE 60BD
D8AF 60C6
D8B0 60B5
D8B1 60D8
D8B2 614D
D8B3 6115
D8B4 6106
D8B5 60F6
D8B6 60F7
D8B7 6100
D8B8 60F4
D8B9 60FA
D8BA 6103
D8BB 6121
D8BC 60FB
D8BD 60F1
D8BE 610D
D8BF 610E
D8C0 6147
D8C1 613E
D8C2 6128
D8C3 6127
D8C4 614A
D8C5 613F
D8C6 613C
D8C7 612C
D8C8 6134
D8C9 613D
D8CA 6142
D8CB 6144
D8CC 6173
D8CD 6177
D8CE 6158
D8CF 6159
D8D0 615A
D8D1 616B
D8D2 6174
D8D3 616F
D8D4 6165
D8D5 6171
D8D6 615F
D8D7 615D
D8D8 6153
D8D9 6175
D8DA 6199
D8DB 6196
D8DC 6187
D8DD 61AC
D8DE 6194
D8DF 619A
D8E0 618A
D8E1 6191
D8E2 61AB
D8E3 61AE
D8E4 61CC
D8E5 61CA
D8E6 61C9
D8E7 61F7
D8E8 61C8
D8E9 61C3
D8EA 61C6
D8EB 61BA
D8EC 61CB
D8ED 7F79
D8EE 61CD
D8EF 61E6
D8F0 61E3
D8F1 61F6
D8F2 61FA
D8F3 61F4
D8F4 61FF
D8F5 61FD
D8F6 61FC
D8F7 61FE
D8F8 6200
D8F9 6208
D8FA 6209
D8FB 620D
D8FC 620C
D8FD 6214
D8FE 621B
D9A1 621E
D9A2 6221
D9A3 622A
D9A4 622E
D9A5 6230
D9A6 6232
D9A7 6233
D9A8 6241
D9A9 624E
D9AA 625E
D9AB 6263
D9AC 625B
D9AD 6260
D9AE 6268
D9AF 627C
D9B0 6282
D9B1 6289
D9B2 627E
D9B3 6292
D9B4 6293
D9B5 6296
D9B6 62D4
D9B7 6283
D9B8 6294
D9B9 62D7
D9BA 62D1
D9BB 62BB
D9BC 62CF
D9BD 62FF
D9BE 62C6
D9BF 64D4
D9C0 62C8
D9C1 62DC
D9C2 62CC
D9C3 62CA
D9C4 62C2
D9C5 62C7
D9C6 629B
D9C7 62C9
D9C8 630C
D9C9 62EE
D9CA 62F1
D9CB 6327
D9CC 6302
D9CD 6308
D9CE 62EF
D9CF 62F5
D9D0 6350
D9D1 633E
D9D2 634D
D9D3 641C
D9D4 634F
D9D5 6396
D9D6 638E
D9D7 6380
D9D8 63AB
D9D9 6376
D9DA 63A3
D9DB 638F
D9DC 6389
D9DD 639F
D9DE 63B5
D9DF 636B
D9E0 6369
D9E1 63BE
D9E2 63E9
D9E3 63C0
D9E4 63C6
D9E5 63E3
D9E6 63C9
D9E7 63D2
D9E8 63F6
D9E9 63C4
D9EA 6416
D9EB 6434
D9EC 6406
D9ED 6413
D9EE 6426
D9EF 6436
D9F0 651D
D9F1 6417
D9F2 6428
D9F3 640F
D9F4 6467
D9F5 646F
D9F6 6476
D9F7 644E
D9F8 652A
D9F9 6495
D9FA 6493
D9FB 64A5
D9FC 64A9
D9FD 6488
D9FE 64BC
DAA1 64DA
DAA2 64D2
DAA3 64C5
DAA4 64C7
DAA5 64BB
DAA6 64D8
DAA7 64C2
DAA8 64F1
DAA9 64E7
DAAA 8209
DAAB 64E0
DAAC 64E1
DAAD 62AC
DAAE 64E3
DAAF 64EF
DAB0 652C
DAB1 64F6
DAB2 64F4
DAB3 64F2
DAB4 64FA
DAB5 6500
DAB6 64FD
DAB7 6518
DAB8 651C
DAB9 6505
DABA 6524
DABB 6523
DABC 652B
DABD 6534
DABE 6535
DABF 6537
DAC0 6536
DAC1 6538
DAC2 754B
DAC3 6548
DAC4 6556
DAC5 6555
DAC6 654D
DAC7 6558
DAC8 655E
DAC9 655D
DACA 6572
DACB 6578
DACC 6582
DACD 6583
DACE 8B8A
DACF 659B
DAD0 659F
DAD1 65AB
DAD2 65B7
DAD3 65C3
DAD4 65C6
DAD5 65C1
DAD6 65C4
DAD7 65CC
DAD8 65D2
DAD9 65DB
DADA 65D9
DADB 65E0
DADC 65E1
DADD 65F1
DADE 6772
DADF 660A
DAE0 6603
DAE1 65FB
DAE2 6773
DAE3 6635
DAE4 6636
DAE5 6634
DAE6 661C
DAE7 664F
DAE8 6644
DAE9 6649
DAEA 6641
DAEB 665E
DAEC 665D
DAED 6664
DAEE 6667
DAEF 6668
DAF0 665F
DAF1 6662
DAF2 6670
DAF3 6683
DAF4 6688
DAF5 668E
DAF6 6689
DAF7 6684
DAF8 6698
DAF9 669D
DAFA 66C1
DAFB 66B9
DAFC 66C9
DAFD 66BE
DAFE 66BC
DBA1 66C4
DBA2 66B8
DBA3 66D6
DBA4 66DA
DBA5 66E0
DBA6 663F
DBA7 66E6
DBA8 66E9
DBA9 66F0
DBAA 66F5
DBAB 66F7
DBAC 670F
DBAD 6716
DBAE 671E
DBAF 6726
DBB0 6727
DBB1 9738
DBB2 672E
DBB3 673F
DBB4 6736
DBB5 6741
DBB6 6738
DBB7 6737
DBB8 6746
DBB9 675E
DBBA 6760
DBBB 6759
DBBC 6763
DBBD 6764
DBBE 6789
DBBF 6770
DBC0 67A9
DBC1 677C
DBC2 676A
DBC3 678C
DBC4 678B
DBC5 67A6
DBC6 67A1
DBC7 6785
DBC8 67B7
DBC9 67EF
DBCA 67B4
DBCB 67EC
DBCC 67B3
DBCD 67E9
DBCE 67B8
DBCF 67E4
DBD0 67DE
DBD1 67DD
DBD2 67E2
DBD3 67EE
DBD4 67B9
DBD5 67CE
DBD6 67C6
DBD7 67E7
DBD8 6A9C
DBD9 681E
DBDA 6846
DBDB 6829
DBDC 6840
DBDD 684D
DBDE 6832
DBDF 684E
DBE0 68B3
DBE1 682B
DBE2 6859
DBE3 6863
DBE4 6877
DBE5 687F
DBE6 689F
DBE7 688F
DBE8 68AD
DBE9 6894
DBEA 689D
DBEB 689B
DBEC 6883
DBED 6AAE
DBEE 68B9
DBEF 6874
DBF0 68B5
DBF1 68A0
DBF2 68BA
DBF3 690F
DBF4 688D
DBF5 687E
DBF6 6901
DBF7 68CA
DBF8 6908
DBF9 68D8
DBFA 6922
DBFB 6926
DBFC 68E1
DBFD 690C
DBFE 68CD
DCA1 68D4
DCA2 68E7
DCA3 68D5
DCA4 6936
DCA5 6912
DCA6 6904
DCA7 68D7
DCA8 68E3
DCA9 6925
DCAA 68F9
DCAB 68E0
DCAC 68EF
DCAD 6928
DCAE 692A
DCAF 691A
DCB0 6923
DCB1 6921
DCB2 68C6
DCB3 6979
DCB4 6977
DCB5 695C
DCB6 6978
DCB7 696B
DCB8 6954
DCB9 697E
DCBA 696E
DCBB 6939
DCBC 6974
DCBD 693D
DCBE 6959
DCBF 6930
DCC0 6961
DCC1 695E
DCC2 695D
DCC3 6981
DCC4 696A
DCC5 69B2
DCC6 69AE
DCC7 69D0
DCC8 69BF
DCC9 69C1
DCCA 69D3
DCCB 69BE
DCCC 69CE
DCCD 5BE8
DCCE 69CA
DCCF 69DD
DCD0 69BB
DCD1 69C3
DCD2 69A7
DCD3 6A2E
DCD4 6991
DCD5 69A0
DCD6 699C
DCD7 6995
DCD8 69B4
DCD9 69DE
DCDA 69E8
DCDB 6A02
DCDC 6A1B
DCDD 69FF
DCDE 6B0A
DCDF 69F9
DCE0 69F2
DCE1 69E7
DCE2 6A05
DCE3 69B1
DCE4 6A1E
DCE5 69ED
DCE6 6A14
DCE7 69EB
DCE8 6A0A
DCE9 6A12
DCEA 6AC1
DCEB 6A23
DCEC 6A13
DCED 6A44
DCEE 6A0C
DCEF 6A72
DCF0 6A36
DCF1 6A78
DCF2 6A47
DCF3 6A62
DCF4 6A59
DCF5 6A66
DCF6 6A48
DCF7 6A38
DCF8 6A22
DCF9 6A90
DCFA 6A8D
DCFB 6AA0
DCFC 6A84
DCFD 6AA2
DCFE 6AA3
DDA1 6A97
DDA2 8617
DDA3 6ABB
DDA4 6AC3
DDA5 6AC2
DDA6 6AB8
DDA7 6AB3
DDA8 6AAC
DDA9 6ADE
DDAA 6AD1
DDAB 6ADF
DDAC 6AAA
DDAD 6ADA
DDAE 6AEA
DDAF 6AFB
DDB0 6B05
DDB1 8616
DDB2 6AFA
DDB3 6B12
DDB4 6B16
DDB5 9B31
DDB6 6B1F
DDB7 6B38
DDB8 6B37
DDB9 76DC
DDBA 6B39
DDBB 98EE
DDBC 6B47
DDBD 6B43
DDBE 6B49
DDBF 6B50
DDC0 6B59
DDC1 6B54
DDC2 6B5B
DDC3 6B5F
DDC4 6B61
DDC5 6B78
DDC6 6B79
DDC7 6B7F
DDC8 6B80
DDC9 6B84
DDCA 6B83
DDCB 6B8D
DDCC 6B98
DDCD 6B95
DDCE 6B9E
DDCF 6BA4
DDD0 6BAA
DDD1 6BAB
DDD2 6BAF
DDD3 6BB2
DDD4 6BB1
DDD5 6BB3
DDD6 6BB7
DDD7 6BBC
DDD8 6BC6
DDD9 6BCB
DDDA 6BD3
DDDB 6BDF
DDDC 6BEC
DDDD 6BEB
DDDE 6BF3
DDDF 6BEF
DDE0 9EBE
DDE1 6C08
DDE2 6C13
DDE3 6C14
DDE4 6C1B
DDE5 6C24
DDE6 6C23
DDE7 6C5E
DDE8 6C55
DDE9 6C62
DDEA 6C6A
DDEB 6C82
DDEC 6C8D
DDED 6C9A
DDEE 6C81
DDEF 6C9B
DDF0 6C7E
DDF1 6C68
DDF2 6C73
DDF3 6C92
DDF4 6C90
DDF5 6CC4
DDF6 6CF1
DDF7 6CD3
DDF8 6CBD
DDF9 6CD7
DDFA 6CC5
DDFB 6CDD
DDFC 6CAE
DDFD 6CB1
DDFE 6CBE
DEA1 6CBA
DEA2 6CDB
DEA3 6CEF
DEA4 6CD9
DEA5 6CEA
DEA6 6D1F
DEA7 884D
DEA8 6D36
DEA9 6D2B
DEAA 6D3D
DEAB 6D38
DEAC 6D19
DEAD 6D35
DEAE 6D33
DEAF 6D12
DEB0 6D0C
DEB1 6D63
DEB2 6D93
DEB3 6D64
DEB4 6D5A
DEB5 6D79
DEB6 6D59
DEB7 6D8E
DEB8 6D95
DEB9 6FE4
DEBA 6D85
DEBB 6DF9
DEBC 6E15
DEBD 6E0A
DEBE 6DB5
DEBF 6DC7
DEC0 6DE6
DEC1 6DB8
DEC2 6DC6
DEC3 6DEC
DEC4 6DDE
DEC5 6DCC
DEC6 6DE8
DEC7 6DD2
DEC8 6DC5
DEC9 6DFA
DECA 6DD9
DECB 6DE4
DECC 6DD5
DECD 6DEA
DECE 6DEE
DECF 6E2D
DED0 6E6E
DED1 6E2E
DED2 6E19
DED3 6E72
DED4 6E5F
DED5 6E3E
DED6 6E23
DED7 6E6B
DED8 6E2B
DED9 6E76
DEDA 6E4D
DEDB 6E1F
DEDC 6E43
DEDD 6E3A
DEDE 6E4E
DEDF 6E24
DEE0 6EFF
DEE1 6E1D
DEE2 6E38
DEE3 6E82
DEE4 6EAA
DEE5 6E98
DEE6 6EC9
DEE7 6EB7
DEE8 6ED3
DEE9 6EBD
DEEA 6EAF
DEEB 6EC4
DEEC 6EB2
DEED 6ED4
DEEE 6ED5
DEEF 6E8F
DEF0 6EA5
DEF1 6EC2
DEF2 6E9F
DEF3 6F41
DEF4 6F11
DEF5 704C
DEF6 6EEC
DEF7 6EF8
DEF8 6EFE
DEF9 6F3F
DEFA 6EF2
DEFB 6F31
DEFC 6EEF
DEFD 6F32
DEFE 6ECC
DFA1 6F3E
DFA2 6F13
DFA3 6EF7
DFA4 6F86
DFA5 6F7A
DFA6 6F78
DFA7 6F81
DFA8 6F80
DFA9 6F6F
DFAA 6F5B
DFAB 6FF3
DFAC 6F6D
DFAD 6F82
DFAE 6F7C
DFAF 6F58
DFB0 6F8E
DFB1 6F91
DFB2 6FC2
DFB3 6F66
DFB4 6FB3
DFB5 6FA3
DFB6 6FA1
DFB7 6FA4
DFB8 6FB9
DFB9 6FC6
DFBA 6FAA
DFBB 6FDF
DFBC 6FD5
DFBD 6FEC
DFBE 6FD4
DFBF 6FD8
DFC0 6FF1
DFC1 6FEE
DFC2 6FDB
DFC3 7009
DFC4 700B
DFC5 6FFA
DFC6 7011
DFC7 7001
DFC8 700F
DFC9 6FFE
DFCA 701B
DFCB 701A
DFCC 6F74
DFCD 701D
DFCE 7018
DFCF 701F
DFD0 7030
DFD1 703E
DFD2 7032
DFD3 7051
DFD4 7063
DFD5 7099
DFD6 7092
DFD7 70AF
DFD8 70F1
DFD9 70AC
DFDA 70B8
DFDB 70B3
DFDC 70AE
DFDD 70DF
DFDE 70CB
DFDF 70DD
DFE0 70D9
DFE1 7109
DFE2 70FD
DFE3 711C
DFE4 7119
DFE5 7165
DFE6 7155
DFE7 7188
DFE8 7166
DFE9 7162
DFEA 714C
DFEB 7156
DFEC 716C
DFED 718F
DFEE 71FB
DFEF 7184
DFF0 7195
DFF1 71A8
DFF2 71AC
DFF3 71D7
DFF4 71B9
DFF5 71BE
DFF6 71D2
DFF7 71C9
DFF8 71D4
DFF9 71CE
DFFA 71E0
DFFB 71EC
DFFC 71E7
DFFD 71F5
DFFE 71FC
E0A1 71F9
E0A2 71FF
E0A3 720D
E0A4 7210
E0A5 721B
E0A6 7228
E0A7 722D
E0A8 722C
E0A9 7230
E0AA 7232
E0AB 723B
E0AC 723C
E0AD 723F
E0AE 7240
E0AF 7246
E0B0 724B
E0B1 7258
E0B2 7274
E0B3 727E
E0B4 7282
E0B5 7281
E0B6 7287
E0B7 7292
E0B8 7296
E0B9 72A2
E0BA 72A7
E0BB 72B9
E0BC 72B2
E0BD 72C3
E0BE 72C6
E0BF 72C4
E0C0 72CE
E0C1 72D2
E0C2 72E2
E0C3 72E0
E0C4 72E1
E0C5 72F9
E0C6 72F7
E0C7 500F
E0C8 7317
E0C9 730A
E0CA 731C
E0CB 7316
E0CC 731D
E0CD 7334
E0CE 732F
E0CF 7329
E0D0 7325
E0D1 733E
E0D2 734E
E0D3 734F
E0D4 9ED8
E0D5 7357
E0D6 736A
E0D7 7368
E0D8 7370
E0D9 7378
E0DA 7375
E0DB 737B
E0DC 737A
E0DD 73C8
E0DE 73B3
E0DF 73CE
E0E0 73BB
E0E1 73C0
E0E2 73E5
E0E3 73EE
E0E4 73DE
E0E5 74A2
E0E6 7405
E0E7 746F
E0E8 7425
E0E9 73F8
E0EA 7432
E0EB 743A
E0EC 7455
E0ED 743F
E0EE 745F
E0EF 7459
E0F0 7441
E0F1 745C
E0F2 7469
E0F3 7470
E0F4 7463
E0F5 746A
E0F6 7476
E0F7 747E
E0F8 748B
E0F9 749E
E0FA 74A7
E0FB 74CA
E0FC 74CF
E0FD 74D4
E0FE 73F1
E1A1 74E0
E1A2 74E3
E1A3 74E7
E1A4 74E9
E1A5 74EE
E1A6 74F2
E1A7 74F0
E1A8 74F1
E1A9 74F8
E1AA 74F7
E1AB 7504
E1AC 7503
E1AD 7505
E1AE 750C
E1AF 750E
E1B0 750D
E1B1 7515
E1B2 7513
E1B3 751E
E1B4 7526
E1B5 752C
E1B6 753C
E1B7 7544
E1B8 754D
E1B9 754A
E1BA 7549
E1BB 755B
E1BC 7546
E1BD 755A
E1BE 7569
E1BF 7564
E1C0 7567
E1C1 756B
E1C2 756D
E1C3 7578
E1C4 7576
E1C5 7586
E1C6 7587
E1C7 7574
E1C8 758A
E1C9 7589
E1CA 7582
E1CB 7594
E1CC 759A
E1CD 759D
E1CE 75A5
E1CF 75A3
E1D0 75C2
E1D1 75B3
E1D2 75C3
E1D3 75B5
E1D4 75BD
E1D5 75B8
E1D6 75BC
E1D7 75B1
E1D8 75CD
E1D9 75CA
E1DA 75D2
E1DB 75D9
E1DC 75E3
E1DD 75DE
E1DE 75FE
E1DF 75FF
E1E0 75FC
E1E1 7601
E1E2 75F0
E1E3 75FA
E1E4 75F2
E1E5 75F3
E1E6 760B
E1E7 760D
E1E8 7609
E1E9 761F
E1EA 7627
E1EB 7620
E1EC 7621
E1ED 7622
E1EE 7624
E1EF 7634
E1F0 7630
E1F1 763B
E1F2 7647
E1F3 7648
E1F4 7646
E1F5 765C
E1F6 7658
E1F7 7661
E1F8 7662
E1F9 7668
E1FA 7669
E1FB 766A
E1FC 7667
E1FD 766C
E1FE 7670
E2A1 7672
E2A2 7676
E2A3 7678
E2A4 767C
E2A5 7680
E2A6 7683
E2A7 7688
E2A8 768B
E2A9 768E
E2AA 7696
E2AB 7693
E2AC 7699
E2AD 769A
E2AE 76B0
E2AF 76B4
E2B0 76B8
E2B1 76B9
E2B2 76BA
E2B3 76C2
E2B4 76CD
E2B5 76D6
E2B6 76D2
E2B7 76DE
E2B8 76E1
E2B9 76E5
E2BA 76E7
E2BB 76EA
E2BC 862F
E2BD 76FB
E2BE 7708
E2BF 7707
E2C0 7704
E2C1 7729
E2C2 7724
E2C3 771E
E2C4 7725
E2C5 7726
E2C6 771B
E2C7 7737
E2C8 7738
E2C9 7747
E2CA 775A
E2CB 7768
E2CC 776B
E2CD 775B
E2CE 7765
E2CF 777F
E2D0 777E
E2D1 7779
E2D2 778E
E2D3 778B
E2D4 7791
E2D5 77A0
E2D6 779E
E2D7 77B0
E2D8 77B6
E2D9 77B9
E2DA 77BF
E2DB 77BC
E2DC 77BD
E2DD 77BB
E2DE 77C7
E2DF 77CD
E2E0 77D7
E2E1 77DA
E2E2 77DC
E2E3 77E3
E2E4 77EE
E2E5 77FC
E2E6 780C
E2E7 7812
E2E8 7926
E2E9 7820
E2EA 792A
E2EB 7845
E2EC 788E
E2ED 7874
E2EE 7886
E2EF 787C
E2F0 789A
E2F1 788C
E2F2 78A3
E2F3 78B5
E2F4 78AA
E2F5 78AF
E2F6 78D1
E2F7 78C6
E2F8 78CB
E2F9 78D4
E2FA 78BE
E2FB 78BC
E2FC 78C5
E2FD 78CA
E2FE 78EC
E3A1 78E7
E3A2 78DA
E3A3 78FD
E3A4 78F4
E3A5 7907
E3A6 7912
E3A7 7911
E3A8 7919
E3A9 792C
E3AA 792B
E3AB 7940
E3AC 7960
E3AD 7957
E3AE 795F
E3AF 795A
E3B0 7955
E3B1 7953
E3B2 797A
E3B3 797F
E3B4 798A
E3B5 799D
E3B6 79A7
E3B7 9F4B
E3B8 79AA
E3B9 79AE
E3BA 79B3
E3BB 79B9
E3BC 79BA
E3BD 79C9
E3BE 79D5
E3BF 79E7
E3C0 79EC
E3C1 79E1
E3C2 79E3
E3C3 7A08
E3C4 7A0D
E3C5 7A18
E3C6 7A19
E3C7 7A20
E3C8 7A1F
E3C9 7980
E3CA 7A31
E3CB 7A3B
E3CC 7A3E
E3CD 7A37
E3CE 7A43
E3CF 7A57
E3D0 7A49
E3D1 7A61
E3D2 7A62
E3D3 7A69
E3D4 9F9D
E3D5 7A70
E3D6 7A79
E3D7 7A7D
E3D8 7A88
E3D9 7A97
E3DA 7A95
E3DB 7A98
E3DC 7A96
E3DD 7AA9
E3DE 7AC8
E3DF 7AB0
E3E0 7AB6
E3E1 7AC5
E3E2 7AC4
E3E3 7ABF
E3E4 9083
E3E5 7AC7
E3E6 7ACA
E3E7 7ACD
E3E8 7ACF
E3E9 7AD5
E3EA 7AD3
E3EB 7AD9
E3EC 7ADA
E3ED 7ADD
E3EE 7AE1
E3EF 7AE2
E3F0 7AE6
E3F1 7AED
E3F2 7AF0
E3F3 7B02
E3F4 7B0F
E3F5 7B0A
E3F6 7B06
E3F7 7B33
E3F8 7B18
E3F9 7B19
E3FA 7B1E
E3FB 7B35
E3FC 7B28
E3FD 7B36
E3FE 7B50
E4A1 7B7A
E4A2 7B04
E4A3 7B4D
E4A4 7B0B
E4A5 7B4C
E4A6 7B45
E4A7 7B75
E4A8 7B65
E4A9 7B74
E4AA 7B67
E4AB 7B70
E4AC 7B71
E4AD 7B6C
E4AE 7B6E
E4AF 7B9D
E4B0 7B98
E4B1 7B9F
E4B2 7B8D
E4B3 7B9C
E4B4 7B9A
E4B5 7B8B
E4B6 7B92
E4B7 7B8F
E4B8 7B5D
E4B9 7B99
E4BA 7BCB
E4BB 7BC1
E4BC 7BCC
E4BD 7BCF
E4BE 7BB4
E4BF 7BC6
E4C0 7BDD
E4C1 7BE9
E4C2 7C11
E4C3 7C14
E4C4 7BE6
E4C5 7BE5
E4C6 7C60
E4C7 7C00
E4C8 7C07
E4C9 7C13
E4CA 7BF3
E4CB 7BF7
E4CC 7C17
E4CD 7C0D
E4CE 7BF6
E4CF 7C23
E4D0 7C27
E4D1 7C2A
E4D2 7C1F
E4D3 7C37
E4D4 7C2B
E4D5 7C3D
E4D6 7C4C
E4D7 7C43
E4D8 7C54
E4D9 7C4F
E4DA 7C40
E4DB 7C50
E4DC 7C58
E4DD 7C5F
E4DE 7C64
E4DF 7C56
E4E0 7C65
E4E1 7C6C
E4E2 7C75
E4E3 7C83
E4E4 7C90
E4E5 7CA4
E4E6 7CAD
E4E7 7CA2
E4E8 7CAB
E4E9 7CA1
E4EA 7CA8
E4EB 7CB3
E4EC 7CB2
E4ED 7CB1
E4EE 7CAE
E4EF 7CB9
E4F0 7CBD
E4F1 7CC0
E4F2 7CC5
E4F3 7CC2
E4F4 7CD8
E4F5 7CD2
E4F6 7CDC
E4F7 7CE2
E4F8 9B3B
E4F9 7CEF
E4FA 7CF2
E4FB 7CF4
E4FC 7CF6
E4FD 7CFA
E4FE 7D06
E5A1 7D02
E5A2 7D1C
E5A3 7D15
E5A4 7D0A
E5A5 7D45
E5A6 7D4B
E5A7 7D2E
E5A8 7D32
E5A9 7D3F
E5AA 7D35
E5AB 7D46
E5AC 7D73
E5AD 7D56
E5AE 7D4E
E5AF 7D72
E5B0 7D68
E5B1 7D6E
E5B2 7D4F
E5B3 7D63
E5B4 7D93
E5B5 7D89
E5B6 7D5B
E5B7 7D8F
E5B8 7D7D
E5B9 7D9B
E5BA 7DBA
E5BB 7DAE
E5BC 7DA3
E5BD 7DB5
E5BE 7DC7
E5BF 7DBD
E5C0 7DAB
E5C1 7E3D
E5C2 7DA2
E5C3 7DAF
E5C4 7DDC
E5C5 7DB8
E5C6 7D9F
E5C7 7DB0
E5C8 7DD8
E5C9 7DDD
E5CA 7DE4
E5CB 7DDE
E5CC 7DFB
E5CD 7DF2
E5CE 7DE1
E5CF 7E05
E5D0 7E0A
E5D1 7E23
E5D2 7E21
E5D3 7E12
E5D4 7E31
E5D5 7E1F
E5D6 7E09
E5D7 7E0B
E5D8 7E22
E5D9 7E46
E5DA 7E66
E5DB 7E3B
E5DC 7E35
E5DD 7E39
E5DE 7E43
E5DF 7E37
E5E0 7E32
E5E1 7E3A
E5E2 7E67
E5E3 7E5D
E5E4 7E56
E5E5 7E5E
E5E6 7E59
E5E7 7E5A
E5E8 7E79
E5E9 7E6A
E5EA 7E69
E5EB 7E7C
E5EC 7E7B
E5ED 7E83
E5EE 7DD5
E5EF 7E7D
E5F0 8FAE
E5F1 7E7F
E5F2 7E88
E5F3 7E89
E5F4 7E8C
E5F5 7E92
E5F6 7E90
E5F7 7E93
E5F8 7E94
E5F9 7E96
E5FA 7E8E
E5FB 7E9B
E5FC 7E9C
E5FD 7F38
E5FE 7F3A
E6A1 7F45
E6A2 7F4C
E6A3 7F4D
E6A4 7F4E
E6A5 7F50
E6A6 7F51
E6A7 7F55
E6A8 7F54
E6A9 7F58
E6AA 7F5F
E6AB 7F60
E6AC 7F68
E6AD 7F69
E6AE 7F67
E6AF 7F78
E6B0 7F82
E6B1 7F86
E6B2 7F83
E6B3 7F88
E6B4 7F87
E6B5 7F8C
E6B6 7F94
E6B7 7F9E
E6B8 7F9D
E6B9 7F9A
E6BA 7FA3
E6BB 7FAF
E6BC 7FB2
E6BD 7FB9
E6BE 7FAE
E6BF 7FB6
E6C0 7FB8
E6C1 8B71
E6C2 7FC5
E6C3 7FC6
E6C4 7FCA
E6C5 7FD5
E6C6 7FD4
E6C7 7FE1
E6C8 7FE6
E6C9 7FE9
E6CA 7FF3
E6CB 7FF9
E6CC 98DC
E6CD 8006
E6CE 8004
E6CF 800B
E6D0 8012
E6D1 8018
E6D2 8019
E6D3 801C
E6D4 8021
E6D5 8028
E6D6 803F
E6D7 803B
E6D8 804A
E6D9 8046
E6DA 8052
E6DB 8058
E6DC 805A
E6DD 805F
E6DE 8062
E6DF 8068
E6E0 8073
E6E1 8072
E6E2 8070
E6E3 8076
E6E4 8079
E6E5 807D
E6E6 807F
E6E7 8084
E6E8 8086
E6E9 8085
E6EA 809B
E6EB 8093
E6EC 809A
E6ED 80AD
E6EE 5190
E6EF 80AC
E6F0 80DB
E6F1 80E5
E6F2 80D9
E6F3 80DD
E6F4 80C4
E6F5 80DA
E6F6 80D6
E6F7 8109
E6F8 80EF
E6F9 80F1
E6FA 811B
E6FB 8129
E6FC 8123
E6FD 812F
E6FE 814B
E7A1 968B
E7A2 8146
E7A3 813E
E7A4 8153
E7A5 8151
E7A6 80FC
E7A7 8171
E7A8 816E
E7A9 8165
E7AA 8166
E7AB 8174
E7AC 8183
E7AD 8188
E7AE 818A
E7AF 8180
E7B0 8182
E7B1 81A0
E7B2 8195
E7B3 81A4
E7B4 81A3
E7B5 815F
E7B6 8193
E7B7 81A9
E7B8 81B0
E7B9 81B5
E7BA 81BE
E7BB 81B8
E7BC 81BD
E7BD 81C0
E7BE 81C2
E7BF 81BA
E7C0 81C9
E7C1 81CD
E7C2 81D1
E7C3 81D9
E7C4 81D8
E7C5 81C8
E7C6 81DA
E7C7 81DF
E7C8 81E0
E7C9 81E7
E7CA 81FA
E7CB 81FB
E7CC 81FE
E7CD 8201
E7CE 8202
E7CF 8205
E7D0 8207
E7D1 820A
E7D2 820D
E7D3 8210
E7D4 8216
E7D5 8229
E7D6 822B
E7D7 8238
E7D8 8233
E7D9 8240
E7DA 8259
E7DB 8258
E7DC 825D
E7DD 825A
E7DE 825F
E7DF 8264
E7E0 8262
E7E1 8268
E7E2 826A
E7E3 826B
E7E4 822E
E7E5 8271
E7E6 8277
E7E7 8278
E7E8 827E
E7E9 828D
E7EA 8292
E7EB 82AB
E7EC 829F
E7ED 82BB
E7EE 82AC
E7EF 82E1
E7F0 82E3
E7F1 82DF
E7F2 82D2
E7F3 82F4
E7F4 82F3
E7F5 82FA
E7F6 8393
E7F7 8303
E7F8 82FB
E7F9 82F9
E7FA 82DE
E7FB 8306
E7FC 82DC
E7FD 8309
E7FE 82D9
E8A1 8335
E8A2 8334
E8A3 8316
E8A4 8332
E8A5 8331
E8A6 8340
E8A7 8339
E8A8 8350
E8A9 8345
E8AA 832F
E8AB 832B
E8AC 8317
E8AD 8318
E8AE 8385
E8AF 839A
E8B0 83AA
E8B1 839F
E8B2 83A2
E8B3 8396
E8B4 8323
E8B5 838E
E8B6 8387
E8B7 838A
E8B8 837C
E8B9 83B5
E8BA 8373
E8BB 8375
E8BC 83A0
E8BD 8389
E8BE 83A8
E8BF 83F4
E8C0 8413
E8C1 83EB
E8C2 83CE
E8C3 83FD
E8C4 8403
E8C5 83D8
E8C6 840B
E8C7 83C1
E8C8 83F7
E8C9 8407
E8CA 83E0
E8CB 83F2
E8CC 840D
E8CD 8422
E8CE 8420
E8CF 83BD
E8D0 8438
E8D1 8506
E8D2 83FB
E8D3 846D
E8D4 842A
E8D5 843C
E8D6 855A
E8D7 8484
E8D8 8477
E8D9 846B
E8DA 84AD
E8DB 846E
E8DC 8482
E8DD 8469
E8DE 8446
E8DF 842C
E8E0 846F
E8E1 8479
E8E2 8435
E8E3 84CA
E8E4 8462
E8E5 84B9
E8E6 84BF
E8E7 849F
E8E8 84D9
E8E9 84CD
E8EA 84BB
E8EB 84DA
E8EC 84D0
E8ED 84C1
E8EE 84C6
E8EF 84D6
E8F0 84A1
E8F1 8521
E8F2 84FF
E8F3 84F4
E8F4 8517
E8F5 8518
E8F6 852C
E8F7 851F
E8F8 8515
E8F9 8514
E8FA 84FC
E8FB 8540
E8FC 8563
E8FD 8558
E8FE 8548
E9A1 8541
E9A2 8602
E9A3 854B
E9A4 8555
E9A5 8580
E9A6 85A4
E9A7 8588
E9A8 8591
E9A9 858A
E9AA 85A8
E9AB 856D
E9AC 8594
E9AD 859B
E9AE 85EA
E9AF 8587
E9B0 859C
E9B1 8577
E9B2 857E
E9B3 8590
E9B4 85C9
E9B5 85BA
E9B6 85CF
E9B7 85B9
E9B8 85D0
E9B9 85D5
E9BA 85DD
E9BB 85E5
E9BC 85DC
E9BD 85F9
E9BE 860A
E9BF 8613
E9C0 860B
E9C1 85FE
E9C2 85FA
E9C3 8606
E9C4 8622
E9C5 861A
E9C6 8630
E9C7 863F
E9C8 864D
E9C9 4E55
E9CA 8654
E9CB 865F
E9CC 8667
E9CD 8671
E9CE 8693
E9CF 86A3
E9D0 86A9
E9D1 86AA
E9D2 868B
E9D3 868C
E9D4 86B6
E9D5 86AF
E9D6 86C4
E9D7 86C6
E9D8 86B0
E9D9 86C9
E9DA 8823
E9DB 86AB
E9DC 86D4
E9DD 86DE
E9DE 86E9
E9DF 86EC
E9E0 86DF
E9E1 86DB
E9E2 86EF
E9E3 8712
E9E4 8706
E9E5 8708
E9E6 8700
E9E7 8703
E9E8 86FB
E9E9 8711
E9EA 8709
E9EB 870D
E9EC 86F9
E9ED 870A
E9EE 8734
E9EF 873F
E9F0 8737
E9F1 873B
E9F2 8725
E9F3 8729
E9F4 871A
E9F5 8760
E9F6 875F
E9F7 8778
E9F8 874C
E9F9 874E
E9FA 8774
E9FB 8757
E9FC 8768
E9FD 876E
E9FE 8759
EAA1 8753
EAA2 8763
EAA3 876A
EAA4 8805
EAA5 87A2
EAA6 879F
EAA7 8782
EAA8 87AF
EAA9 87CB
EAAA 87BD
EAAB 87C0
EAAC 87D0
EAAD 96D6
EAAE 87AB
EAAF 87C4
EAB0 87B3
EAB1 87C7
EAB2 87C6
EAB3 87BB
EAB4 87EF
EAB5 87F2
EAB6 87E0
EAB7 880F
EAB8 880D
EAB9 87FE
EABA 87F6
EABB 87F7
EABC 880E
EABD 87D2
EABE 8811
EABF 8816
EAC0 8815
EAC1 8822
EAC2 8821
EAC3 8831
EAC4 8836
EAC5 8839
EAC6 8827
EAC7 883B
EAC8 8844
EAC9 8842
EACA 8852
EACB 8859
EACC 885E
EACD 8862
EACE 886B
EACF 8881
EAD0 887E
EAD1 889E
EAD2 8875
EAD3 887D
EAD4 88B5
EAD5 8872
EAD6 8882
EAD7 8897
EAD8 8892
EAD9 88AE
EADA 8899
EADB 88A2
EADC 888D
EADD 88A4
EADE 88B0
EADF 88BF
EAE0 88B1
EAE1 88C3
EAE2 88C4
EAE3 88D4
EAE4 88D8
EAE5 88D9
EAE6 88DD
EAE7 88F9
EAE8 8902
EAE9 88FC
EAEA 88F4
EAEB 88E8
EAEC 88F2
EAED 8904
EAEE 890C
EAEF 890A
EAF0 8913
EAF1 8943
EAF2 891E
EAF3 8925
EAF4 892A
EAF5 892B
EAF6 8941
EAF7 8944
EAF8 893B
EAF9 8936
EAFA 8938
EAFB 894C
EAFC 891D
EAFD 8960
EAFE 895E
EBA1 8966
EBA2 8964
EBA3 896D
EBA4 896A
EBA5 896F
EBA6 8974
EBA7 8977
EBA8 897E
EBA9 8983
EBAA 8988
EBAB 898A
EBAC 8993
EBAD 8998
EBAE 89A1
EBAF 89A9
EBB0 89A6
EBB1 89AC
EBB2 89AF
EBB3 89B2
EBB4 89BA
EBB5 89BD
EBB6 89BF
EBB7 89C0
EBB8 89DA
EBB9 89DC
EBBA 89DD
EBBB 89E7
EBBC 89F4
EBBD 89F8
EBBE 8A03
EBBF 8A16
EBC0 8A10
EBC1 8A0C
EBC2 8A1B
EBC3 8A1D
EBC4 8A25
EBC5 8A36
EBC6 8A41
EBC7 8A5B
EBC8 8A52
EBC9 8A46
EBCA 8A48
EBCB 8A7C
EBCC 8A6D
EBCD 8A6C
EBCE 8A62
EBCF 8A85
EBD0 8A82
EBD1 8A84
EBD2 8AA8
EBD3 8AA1
EBD4 8A91
EBD5 8AA5
EBD6 8AA6
EBD7 8A9A
EBD8 8AA3
EBD9 8AC4
EBDA 8ACD
EBDB 8AC2
EBDC 8ADA
EBDD 8AEB
EBDE 8AF3
EBDF 8AE7
EBE0 8AE4
EBE1 8AF1
EBE2 8B14
EBE3 8AE0
EBE4 8AE2
EBE5 8AF7
EBE6 8ADE
EBE7 8ADB
EBE8 8B0C
EBE9 8B07
EBEA 8B1A
EBEB 8AE1
EBEC 8B16
EBED 8B10
EBEE 8B17
EBEF 8B20
EBF0 8B33
EBF1 97AB
EBF2 8B26
EBF3 8B2B
EBF4 8B3E
EBF5 8B28
EBF6 8B41
EBF7 8B4C
EBF8 8B4F
EBF9 8B4E
EBFA 8B49
EBFB 8B56
EBFC 8B5B
EBFD 8B5A
EBFE 8B6B
ECA1 8B5F
ECA2 8B6C
ECA3 8B6F
ECA4 8B74
ECA5 8B7D
ECA6 8B80
ECA7 8B8C
ECA8 8B8E
ECA9 8B92
ECAA 8B93
ECAB 8B96
ECAC 8B99
ECAD 8B9A
ECAE 8C3A
ECAF 8C41
ECB0 8C3F
ECB1 8C48
ECB2 8C4C
ECB3 8C4E
ECB4 8C50
ECB5 8C55
ECB6 8C62
ECB7 8C6C
ECB8 8C78
ECB9 8C7A
ECBA 8C82
ECBB 8C89
ECBC 8C85
ECBD 8C8A
ECBE 8C8D
ECBF 8C8E
ECC0 8C94
ECC1 8C7C
ECC2 8C98
ECC3 621D
ECC4 8CAD
ECC5 8CAA
ECC6 8CBD
ECC7 8CB2
ECC8 8CB3
ECC9 8CAE
ECCA 8CB6
ECCB 8CC8
ECCC 8CC1
ECCD 8CE4
ECCE 8CE3
ECCF 8CDA
ECD0 8CFD
ECD1 8CFA
ECD2 8CFB
ECD3 8D04
ECD4 8D05
ECD5 8D0A
ECD6 8D07
ECD7 8D0F
ECD8 8D0D
ECD9 8D10
ECDA 9F4E
ECDB 8D13
ECDC 8CCD
ECDD 8D14
ECDE 8D16
ECDF 8D67
ECE0 8D6D
ECE1 8D71
ECE2 8D73
ECE3 8D81
ECE4 8D99
ECE5 8DC2
ECE6 8DBE
ECE7 8DBA
ECE8 8DCF
ECE9 8DDA
ECEA 8DD6
ECEB 8DCC
ECEC 8DDB
ECED 8DCB
ECEE 8DEA
ECEF 8DEB
ECF0 8DDF
ECF1 8DE3
ECF2 8DFC
ECF3 8E08
ECF4 8E09
ECF5 8DFF
ECF6 8E1D
ECF7 8E1E
ECF8 8E10
ECF9 8E1F
ECFA 8E42
ECFB 8E35
ECFC 8E30
ECFD 8E34
ECFE 8E4A
EDA1 8E47
EDA2 8E49
EDA3 8E4C
EDA4 8E50
EDA5 8E48
EDA6 8E59
EDA7 8E64
EDA8 8E60
EDA9 8E2A
EDAA 8E63
EDAB 8E55
EDAC 8E76
EDAD 8E72
EDAE 8E7C
EDAF 8E81
EDB0 8E87
EDB1 8E85
EDB2 8E84
EDB3 8E8B
EDB4 8E8A
EDB5 8E93
EDB6 8E91
EDB7 8E94
EDB8 8E99
EDB9 8EAA
EDBA 8EA1
EDBB 8EAC
EDBC 8EB0
EDBD 8EC6
EDBE 8EB1
EDBF 8EBE
EDC0 8EC5
EDC1 8EC8
EDC2 8ECB
EDC3 8EDB
EDC4 8EE3
EDC5 8EFC
EDC6 8EFB
EDC7 8EEB
EDC8 8EFE
EDC9 8F0A
EDCA 8F05
EDCB 8F15
EDCC 8F12
EDCD 8F19
EDCE 8F13
EDCF 8F1C
EDD0 8F1F
EDD1 8F1B
EDD2 8F0C
EDD3 8F26
EDD4 8F33
EDD5 8F3B
EDD6 8F39
EDD7 8F45
EDD8 8F42
EDD9 8F3E
EDDA 8F4C
EDDB 8F49
EDDC 8F46
EDDD 8F4E
EDDE 8F57
EDDF 8F5C
EDE0 8F62
EDE1 8F63
EDE2 8F64
EDE3 8F9C
EDE4 8F9F
EDE5 8FA3
EDE6 8FAD
EDE7 8FAF
EDE8 8FB7
EDE9 8FDA
EDEA 8FE5
EDEB 8FE2
EDEC 8FEA
EDED 8FEF
EDEE 9087
EDEF 8FF4
EDF0 9005
EDF1 8FF9
EDF2 8FFA
EDF3 9011
EDF4 9015
EDF5 9021
EDF6 900D
EDF7 901E
EDF8 9016
EDF9 900B
EDFA 9027
EDFB 9036
EDFC 9035
EDFD 9039
EDFE 8FF8
EEA1 904F
EEA2 9050
EEA3 9051
EEA4 9052
EEA5 900E
EEA6 9049
EEA7 903E
EEA8 9056
EEA9 9058
EEAA 905E
EEAB 9068
EEAC 906F
EEAD 9076
EEAE 96A8
EEAF 9072
EEB0 9082
EEB1 907D
EEB2 9081
EEB3 9080
EEB4 908A
EEB5 9089
EEB6 908F
EEB7 90A8
EEB8 90AF
EEB9 90B1
EEBA 90B5
EEBB 90E2
EEBC 90E4
EEBD 6248
EEBE 90DB
EEBF 9102
EEC0 9112
EEC1 9119
EEC2 9132
EEC3 9130
EEC4 914A
EEC5 9156
EEC6 9158
EEC7 9163
EEC8 9165
EEC9 9169
EECA 9173
EECB 9172
EECC 918B
EECD 9189
EECE 9182
EECF 91A2
EED0 91AB
EED1 91AF
EED2 91AA
EED3 91B5
EED4 91B4
EED5 91BA
EED6 91C0
EED7 91C1
EED8 91C9
EED9 91CB
EEDA 91D0
EEDB 91D6
EEDC 91DF
EEDD 91E1
EEDE 91DB
EEDF 91FC
EEE0 91F5
EEE1 91F6
EEE2 921E
EEE3 91FF
EEE4 9214
EEE5 922C
EEE6 9215
EEE7 9211
EEE8 925E
EEE9 9257
EEEA 9245
EEEB 9249
EEEC 9264
EEED 9248
EEEE 9295
EEEF 923F
EEF0 924B
EEF1 9250
EEF2 929C
EEF3 9296
EEF4 9293
EEF5 929B
EEF6 925A
EEF7 92CF
EEF8 92B9
EEF9 92B7
EEFA 92E9
EEFB 930F
EEFC 92FA
EEFD 9344
EEFE 932E
EFA1 9319
EFA2 9322
EFA3 931A
EFA4 9323
EFA5 933A
EFA6 9335
EFA7 933B
EFA8 935C
EFA9 9360
EFAA 937C
EFAB 936E
EFAC 9356
EFAD 93B0
EFAE 93AC
EFAF 93AD
EFB0 9394
EFB1 93B9
EFB2 93D6
EFB3 93D7
EFB4 93E8
EFB5 93E5
EFB6 93D8
EFB7 93C3
EFB8 93DD
EFB9 93D0
EFBA 93C8
EFBB 93E4
EFBC 941A
EFBD 9414
EFBE 9413
EFBF 9403
EFC0 9407
EFC1 9410
EFC2 9436
EFC3 942B
EFC4 9435
EFC5 9421
EFC6 943A
EFC7 9441
EFC8 9452
EFC9 9444
EFCA 945B
EFCB 9460
EFCC 9462
EFCD 945E
EFCE 946A
EFCF 9229
EFD0 9470
EFD1 9475
EFD2 9477
EFD3 947D
EFD4 945A
EFD5 947C
EFD6 947E
EFD7 9481
EFD8 947F
EFD9 9582
EFDA 9587
EFDB 958A
EFDC 9594
EFDD 9596
EFDE 9598
EFDF 9599
EFE0 95A0
EFE1 95A8
EFE2 95A7
EFE3 95AD
EFE4 95BC
EFE5 95BB
EFE6 95B9
EFE7 95BE
EFE8 95CA
EFE9 6FF6
EFEA 95C3
EFEB 95CD
EFEC 95CC
EFED 95D5
EFEE 95D4
EFEF 95D6
EFF0 95DC
EFF1 95E1
EFF2 95E5
EFF3 95E2
EFF4 9621
EFF5 9628
EFF6 962E
EFF7 962F
EFF8 9642
EFF9 964C
EFFA 964F
EFFB 964B
EFFC 9677
EFFD 965C
EFFE 965E
F0A1 965D
F0A2 965F
F0A3 9666
F0A4 9672
F0A5 966C
F0A6 968D
F0A7 9698
F0A8 9695
F0A9 9697
F0AA 96AA
F0AB 96A7
F0AC 96B1
F0AD 96B2
F0AE 96B0
F0AF 96B4
F0B0 96B6
F0B1 96B8
F0B2 96B9
F0B3 96CE
F0B4 96CB
F0B5 96C9
F0B6 96CD
F0B7 894D
F0B8 96DC
F0B9 970D
F0BA 96D5
F0BB 96F9
F0BC 9704
F0BD 9706
F0BE 9708
F0BF 9713
F0C0 970E
F0C1 9711
F0C2 970F
F0C3 9716
F0C4 9719
F0C5 9724
F0C6 972A
F0C7 9730
F0C8 9739
F0C9 973D
F0CA 973E
F0CB 9744
F0CC 9746
F0CD 9748
F0CE 9742
F0CF 9749
F0D0 975C
F0D1 9760
F0D2 9764
F0D3 9766
F0D4 9768
F0D5 52D2
F0D6 976B
F0D7 9771
F0D8 9779
F0D9 9785
F0DA 977C
F0DB 9781
F0DC 977A
F0DD 9786
F0DE 978B
F0DF 978F
F0E0 9790
F0E1 979C
F0E2 97A8
F0E3 97A6
F0E4 97A3
F0E5 97B3
F0E6 97B4
F0E7 97C3
F0E8 97C6
F0E9 97C8
F0EA 97CB
F0EB 97DC
F0EC 97ED
F0ED 9F4F
F0EE 97F2
F0EF 7ADF
F0F0 97F6
F0F1 97F5
F0F2 980F
F0F3 980C
F0F4 9838
F0F5 9824
F0F6 9821
F0F7 9837
F0F8 983D
F0F9 9846
F0FA 984F
F0FB 984B
F0FC 986B
F0FD 986F
F0FE 9870
F1A1 9871
F1A2 9874
F1A3 9873
F1A4 98AA
F1A5 98AF
F1A6 98B1
F1A7 98B6
F1A8 98C4
F1A9 98C3
F1AA 98C6
F1AB 98E9
F1AC 98EB
F1AD 9903
F1AE 9909
F1AF 9912
F1B0 9914
F1B1 9918
F1B2 9921
F1B3 991D
F1B4 991E
F1B5 9924
F1B6 9920
F1B7 992C
F1B8 992E
F1B9 993D
F1BA 993E
F1BB 9942
F1BC 9949
F1BD 9945
F1BE 9950
F1BF 994B
F1C0 9951
F1C1 9952
F1C2 994C
F1C3 9955
F1C4 9997
F1C5 9998
F1C6 99A5
F1C7 99AD
F1C8 99AE
F1C9 99BC
F1CA 99DF
F1CB 99DB
F1CC 99DD
F1CD 99D8
F1CE 99D1
F1CF 99ED
F1D0 99EE
F1D1 99F1
F1D2 99F2
F1D3 99FB
F1D4 99F8
F1D5 9A01
F1D6 9A0F
F1D7 9A05
F1D8 99E2
F1D9 9A19
F1DA 9A2B
F1DB 9A37
F1DC 9A45
F1DD 9A42
F1DE 9A40
F1DF 9A43
F1E0 9A3E
F1E1 9A55
F1E2 9A4D
F1E3 9A5B
F1E4 9A57
F1E5 9A5F
F1E6 9A62
F1E7 9A65
F1E8 9A64
F1E9 9A69
F1EA 9A6B
F1EB 9A6A
F1EC 9AAD
F1ED 9AB0
F1EE 9ABC
F1EF 9AC0
F1F0 9ACF
F1F1 9AD1
F1F2 9AD3
F1F3 9AD4
F1F4 9ADE
F1F5 9ADF
F1F6 9AE2
F1F7 9AE3
F1F8 9AE6
F1F9 9AEF
F1FA 9AEB
F1FB 9AEE
F1FC 9AF4
F1FD 9AF1
F1FE 9AF7
F2A1 9AFB
F2A2 9B06
F2A3 9B18
F2A4 9B1A
F2A5 9B1F
F2A6 9B22
F2A7 9B23
F2A8 9B25
F2A9 9B27
F2AA 9B28
F2AB 9B29
F2AC 9B2A
F2AD 9B2E
F2AE 9B2F
F2AF 9B32
F2B0 9B44
F2B1 9B43
F2B2 9B4F
F2B3 9B4D
F2B4 9B4E
F2B5 9B51
F2B6 9B58
F2B7 9B74
F2B8 9B93
F2B9 9B83
F2BA 9B91
F2BB 9B96
F2BC 9B97
F2BD 9B9F
F2BE 9BA0
F2BF 9BA8
F2C0 9BB4
F2C1 9BC0
F2C2 9BCA
F2C3 9BB9
F2C4 9BC6
F2C5 9BCF
F2C6 9BD1
F2C7 9BD2
F2C8 9BE3
F2C9 9BE2
F2CA 9BE4
F2CB 9BD4
F2CC 9BE1
F2CD 9C3A
F2CE 9BF2
F2CF 9BF1
F2D0 9BF0
F2D1 9C15
F2D2 9C14
F2D3 9C09
F2D4 9C13
F2D5 9C0C
F2D6 9C06
F2D7 9C08
F2D8 9C12
F2D9 9C0A
F2DA 9C04
F2DB 9C2E
F2DC 9C1B
F2DD 9C25
F2DE 9C24
F2DF 9C21
F2E0 9C30
F2E1 9C47
F2E2 9C32
F2E3 9C46
F2E4 9C3E
F2E5 9C5A
F2E6 9C60
F2E7 9C67
F2E8 9C76
F2E9 9C78
F2EA 9CE7
F2EB 9CEC
F2EC 9CF0
F2ED 9D09
F2EE 9D08
F2EF 9CEB
F2F0 9D03
F2F1 9D06
F2F2 9D2A
F2F3 9D26
F2F4 9DAF
F2F5 9D23
F2F6 9D1F
F2F7 9D44
F2F8 9D15
F2F9 9D12
F2FA 9D41
F2FB 9D3F
F2FC 9D3E
F2FD 9D46
F2FE 9D48
F3A1 9D5D
F3A2 9D5E
F3A3 9D64
F3A4 9D51
F3A5 9D50
F3A6 9D59
F3A7 9D72
F3A8 9D89
F3A9 9D87
F3AA 9DAB
F3AB 9D6F
F3AC 9D7A
F3AD 9D9A
F3AE 9DA4
F3AF 9DA9
F3B0 9DB2
F3B1 9DC4
F3B2 9DC1
F3B3 9DBB
F3B4 9DB8
F3B5 9DBA
F3B6 9DC6
F3B7 9DCF
F3B8 9DC2
F3B9 9DD9
F3BA 9DD3
F3BB 9DF8
F3BC 9DE6
F3BD 9DED
F3BE 9DEF
F3BF 9DFD
F3C0 9E1A
F3C1 9E1B
F3C2 9E1E
F3C3 9E75
F3C4 9E79
F3C5 9E7D
F3C6 9E81
F3C7 9E88
F3C8 9E8B
F3C9 9E8C
F3CA 9E92
F3CB 9E95
F3CC 9E91
F3CD 9E9D
F3CE 9EA5
F3CF 9EA9
F3D0 9EB8
F3D1 9EAA
F3D2 9EAD
F3D3 9761
F3D4 9ECC
F3D5 9ECE
F3D6 9ECF
F3D7 9ED0
F3D8 9ED4
F3D9 9EDC
F3DA 9EDE
F3DB 9EDD
F3DC 9EE0
F3DD 9EE5
F3DE 9EE8
F3DF 9EEF
F3E0 9EF4
F3E1 9EF6
F3E2 9EF7
F3E3 9EF9
F3E4 9EFB
F3E5 9EFC
F3E6 9EFD
F3E7 9F07
F3E8 9F08
F3E9 76B7
F3EA 9F15
F3EB 9F21
F3EC 9F2C
F3ED 9F3E
F3EE 9F4A
F3EF 9F52
F3F0 9F54
F3F1 9F63
F3F2 9F5F
F3F3 9F60
F3F4 9F61
F3F5 9F66
F3F6 9F67
F3F7 9F6C
F3F8 9F6A
F3F9 9F77
F3FA 9F72
F3FB 9F76
F3FC 9F95
F3FD 9F9C
F3FE 9FA0
F4A1 582F
F4A2 69C7
F4A3 9059
F4A4 7464
F4A5 51DC
F4A6 7199
| 143,236 | 13,137 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_typechecks.py | """Unit tests for __instancecheck__ and __subclasscheck__."""
import unittest
class ABC(type):
def __instancecheck__(cls, inst):
"""Implement isinstance(inst, cls)."""
return any(cls.__subclasscheck__(c)
for c in {type(inst), inst.__class__})
def __subclasscheck__(cls, sub):
"""Implement issubclass(sub, cls)."""
candidates = cls.__dict__.get("__subclass__", set()) | {cls}
return any(c in candidates for c in sub.mro())
class Integer(metaclass=ABC):
__subclass__ = {int}
class SubInt(Integer):
pass
class TypeChecksTest(unittest.TestCase):
def testIsSubclassInternal(self):
self.assertEqual(Integer.__subclasscheck__(int), True)
self.assertEqual(Integer.__subclasscheck__(float), False)
def testIsSubclassBuiltin(self):
self.assertEqual(issubclass(int, Integer), True)
self.assertEqual(issubclass(int, (Integer,)), True)
self.assertEqual(issubclass(float, Integer), False)
self.assertEqual(issubclass(float, (Integer,)), False)
def testIsInstanceBuiltin(self):
self.assertEqual(isinstance(42, Integer), True)
self.assertEqual(isinstance(42, (Integer,)), True)
self.assertEqual(isinstance(3.14, Integer), False)
self.assertEqual(isinstance(3.14, (Integer,)), False)
def testIsInstanceActual(self):
self.assertEqual(isinstance(Integer(), Integer), True)
self.assertEqual(isinstance(Integer(), (Integer,)), True)
def testIsSubclassActual(self):
self.assertEqual(issubclass(Integer, Integer), True)
self.assertEqual(issubclass(Integer, (Integer,)), True)
def testSubclassBehavior(self):
self.assertEqual(issubclass(SubInt, Integer), True)
self.assertEqual(issubclass(SubInt, (Integer,)), True)
self.assertEqual(issubclass(SubInt, SubInt), True)
self.assertEqual(issubclass(SubInt, (SubInt,)), True)
self.assertEqual(issubclass(Integer, SubInt), False)
self.assertEqual(issubclass(Integer, (SubInt,)), False)
self.assertEqual(issubclass(int, SubInt), False)
self.assertEqual(issubclass(int, (SubInt,)), False)
self.assertEqual(isinstance(SubInt(), Integer), True)
self.assertEqual(isinstance(SubInt(), (Integer,)), True)
self.assertEqual(isinstance(SubInt(), SubInt), True)
self.assertEqual(isinstance(SubInt(), (SubInt,)), True)
self.assertEqual(isinstance(42, SubInt), False)
self.assertEqual(isinstance(42, (SubInt,)), False)
if __name__ == "__main__":
unittest.main()
| 2,615 | 72 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_smtpd.py | import unittest
import textwrap
from test import support, mock_socket
import socket
import io
import smtpd
import asyncore
class DummyServer(smtpd.SMTPServer):
def __init__(self, *args, **kwargs):
smtpd.SMTPServer.__init__(self, *args, **kwargs)
self.messages = []
if self._decode_data:
self.return_status = 'return status'
else:
self.return_status = b'return status'
def process_message(self, peer, mailfrom, rcpttos, data, **kw):
self.messages.append((peer, mailfrom, rcpttos, data))
if data == self.return_status:
return '250 Okish'
if 'mail_options' in kw and 'SMTPUTF8' in kw['mail_options']:
return '250 SMTPUTF8 message okish'
class DummyDispatcherBroken(Exception):
pass
class BrokenDummyServer(DummyServer):
def listen(self, num):
raise DummyDispatcherBroken()
class SMTPDServerTest(unittest.TestCase):
def setUp(self):
smtpd.socket = asyncore.socket = mock_socket
def test_process_message_unimplemented(self):
server = smtpd.SMTPServer((support.HOST, 0), ('b', 0),
decode_data=True)
conn, addr = server.accept()
channel = smtpd.SMTPChannel(server, conn, addr, decode_data=True)
def write_line(line):
channel.socket.queue_recv(line)
channel.handle_read()
write_line(b'HELO example')
write_line(b'MAIL From:eggs@example')
write_line(b'RCPT To:spam@example')
write_line(b'DATA')
self.assertRaises(NotImplementedError, write_line, b'spam\r\n.\r\n')
def test_decode_data_and_enable_SMTPUTF8_raises(self):
self.assertRaises(
ValueError,
smtpd.SMTPServer,
(support.HOST, 0),
('b', 0),
enable_SMTPUTF8=True,
decode_data=True)
def tearDown(self):
asyncore.close_all()
asyncore.socket = smtpd.socket = socket
class DebuggingServerTest(unittest.TestCase):
def setUp(self):
smtpd.socket = asyncore.socket = mock_socket
def send_data(self, channel, data, enable_SMTPUTF8=False):
def write_line(line):
channel.socket.queue_recv(line)
channel.handle_read()
write_line(b'EHLO example')
if enable_SMTPUTF8:
write_line(b'MAIL From:eggs@example BODY=8BITMIME SMTPUTF8')
else:
write_line(b'MAIL From:eggs@example')
write_line(b'RCPT To:spam@example')
write_line(b'DATA')
write_line(data)
write_line(b'.')
def test_process_message_with_decode_data_true(self):
server = smtpd.DebuggingServer((support.HOST, 0), ('b', 0),
decode_data=True)
conn, addr = server.accept()
channel = smtpd.SMTPChannel(server, conn, addr, decode_data=True)
with support.captured_stdout() as s:
self.send_data(channel, b'From: test\n\nhello\n')
stdout = s.getvalue()
self.assertEqual(stdout, textwrap.dedent("""\
---------- MESSAGE FOLLOWS ----------
From: test
X-Peer: peer-address
hello
------------ END MESSAGE ------------
"""))
def test_process_message_with_decode_data_false(self):
server = smtpd.DebuggingServer((support.HOST, 0), ('b', 0))
conn, addr = server.accept()
channel = smtpd.SMTPChannel(server, conn, addr)
with support.captured_stdout() as s:
self.send_data(channel, b'From: test\n\nh\xc3\xa9llo\xff\n')
stdout = s.getvalue()
self.assertEqual(stdout, textwrap.dedent("""\
---------- MESSAGE FOLLOWS ----------
b'From: test'
b'X-Peer: peer-address'
b''
b'h\\xc3\\xa9llo\\xff'
------------ END MESSAGE ------------
"""))
def test_process_message_with_enable_SMTPUTF8_true(self):
server = smtpd.DebuggingServer((support.HOST, 0), ('b', 0),
enable_SMTPUTF8=True)
conn, addr = server.accept()
channel = smtpd.SMTPChannel(server, conn, addr, enable_SMTPUTF8=True)
with support.captured_stdout() as s:
self.send_data(channel, b'From: test\n\nh\xc3\xa9llo\xff\n')
stdout = s.getvalue()
self.assertEqual(stdout, textwrap.dedent("""\
---------- MESSAGE FOLLOWS ----------
b'From: test'
b'X-Peer: peer-address'
b''
b'h\\xc3\\xa9llo\\xff'
------------ END MESSAGE ------------
"""))
def test_process_SMTPUTF8_message_with_enable_SMTPUTF8_true(self):
server = smtpd.DebuggingServer((support.HOST, 0), ('b', 0),
enable_SMTPUTF8=True)
conn, addr = server.accept()
channel = smtpd.SMTPChannel(server, conn, addr, enable_SMTPUTF8=True)
with support.captured_stdout() as s:
self.send_data(channel, b'From: test\n\nh\xc3\xa9llo\xff\n',
enable_SMTPUTF8=True)
stdout = s.getvalue()
self.assertEqual(stdout, textwrap.dedent("""\
---------- MESSAGE FOLLOWS ----------
mail options: ['BODY=8BITMIME', 'SMTPUTF8']
b'From: test'
b'X-Peer: peer-address'
b''
b'h\\xc3\\xa9llo\\xff'
------------ END MESSAGE ------------
"""))
def tearDown(self):
asyncore.close_all()
asyncore.socket = smtpd.socket = socket
class TestFamilyDetection(unittest.TestCase):
def setUp(self):
smtpd.socket = asyncore.socket = mock_socket
def tearDown(self):
asyncore.close_all()
asyncore.socket = smtpd.socket = socket
@unittest.skipUnless(support.IPV6_ENABLED, "IPv6 not enabled")
def test_socket_uses_IPv6(self):
server = smtpd.SMTPServer((support.HOSTv6, 0), (support.HOST, 0))
self.assertEqual(server.socket.family, socket.AF_INET6)
def test_socket_uses_IPv4(self):
server = smtpd.SMTPServer((support.HOST, 0), (support.HOSTv6, 0))
self.assertEqual(server.socket.family, socket.AF_INET)
class TestRcptOptionParsing(unittest.TestCase):
error_response = (b'555 RCPT TO parameters not recognized or not '
b'implemented\r\n')
def setUp(self):
smtpd.socket = asyncore.socket = mock_socket
self.old_debugstream = smtpd.DEBUGSTREAM
self.debug = smtpd.DEBUGSTREAM = io.StringIO()
def tearDown(self):
asyncore.close_all()
asyncore.socket = smtpd.socket = socket
smtpd.DEBUGSTREAM = self.old_debugstream
def write_line(self, channel, line):
channel.socket.queue_recv(line)
channel.handle_read()
def test_params_rejected(self):
server = DummyServer((support.HOST, 0), ('b', 0))
conn, addr = server.accept()
channel = smtpd.SMTPChannel(server, conn, addr)
self.write_line(channel, b'EHLO example')
self.write_line(channel, b'MAIL from: <[email protected]> size=20')
self.write_line(channel, b'RCPT to: <[email protected]> foo=bar')
self.assertEqual(channel.socket.last, self.error_response)
def test_nothing_accepted(self):
server = DummyServer((support.HOST, 0), ('b', 0))
conn, addr = server.accept()
channel = smtpd.SMTPChannel(server, conn, addr)
self.write_line(channel, b'EHLO example')
self.write_line(channel, b'MAIL from: <[email protected]> size=20')
self.write_line(channel, b'RCPT to: <[email protected]>')
self.assertEqual(channel.socket.last, b'250 OK\r\n')
class TestMailOptionParsing(unittest.TestCase):
error_response = (b'555 MAIL FROM parameters not recognized or not '
b'implemented\r\n')
def setUp(self):
smtpd.socket = asyncore.socket = mock_socket
self.old_debugstream = smtpd.DEBUGSTREAM
self.debug = smtpd.DEBUGSTREAM = io.StringIO()
def tearDown(self):
asyncore.close_all()
asyncore.socket = smtpd.socket = socket
smtpd.DEBUGSTREAM = self.old_debugstream
def write_line(self, channel, line):
channel.socket.queue_recv(line)
channel.handle_read()
def test_with_decode_data_true(self):
server = DummyServer((support.HOST, 0), ('b', 0), decode_data=True)
conn, addr = server.accept()
channel = smtpd.SMTPChannel(server, conn, addr, decode_data=True)
self.write_line(channel, b'EHLO example')
for line in [
b'MAIL from: <[email protected]> size=20 SMTPUTF8',
b'MAIL from: <[email protected]> size=20 SMTPUTF8 BODY=8BITMIME',
b'MAIL from: <[email protected]> size=20 BODY=UNKNOWN',
b'MAIL from: <[email protected]> size=20 body=8bitmime',
]:
self.write_line(channel, line)
self.assertEqual(channel.socket.last, self.error_response)
self.write_line(channel, b'MAIL from: <[email protected]> size=20')
self.assertEqual(channel.socket.last, b'250 OK\r\n')
def test_with_decode_data_false(self):
server = DummyServer((support.HOST, 0), ('b', 0))
conn, addr = server.accept()
channel = smtpd.SMTPChannel(server, conn, addr)
self.write_line(channel, b'EHLO example')
for line in [
b'MAIL from: <[email protected]> size=20 SMTPUTF8',
b'MAIL from: <[email protected]> size=20 SMTPUTF8 BODY=8BITMIME',
]:
self.write_line(channel, line)
self.assertEqual(channel.socket.last, self.error_response)
self.write_line(
channel,
b'MAIL from: <[email protected]> size=20 SMTPUTF8 BODY=UNKNOWN')
self.assertEqual(
channel.socket.last,
b'501 Error: BODY can only be one of 7BIT, 8BITMIME\r\n')
self.write_line(
channel, b'MAIL from: <[email protected]> size=20 body=8bitmime')
self.assertEqual(channel.socket.last, b'250 OK\r\n')
def test_with_enable_smtputf8_true(self):
server = DummyServer((support.HOST, 0), ('b', 0), enable_SMTPUTF8=True)
conn, addr = server.accept()
channel = smtpd.SMTPChannel(server, conn, addr, enable_SMTPUTF8=True)
self.write_line(channel, b'EHLO example')
self.write_line(
channel,
b'MAIL from: <[email protected]> size=20 body=8bitmime smtputf8')
self.assertEqual(channel.socket.last, b'250 OK\r\n')
class SMTPDChannelTest(unittest.TestCase):
def setUp(self):
smtpd.socket = asyncore.socket = mock_socket
self.old_debugstream = smtpd.DEBUGSTREAM
self.debug = smtpd.DEBUGSTREAM = io.StringIO()
self.server = DummyServer((support.HOST, 0), ('b', 0),
decode_data=True)
conn, addr = self.server.accept()
self.channel = smtpd.SMTPChannel(self.server, conn, addr,
decode_data=True)
def tearDown(self):
asyncore.close_all()
asyncore.socket = smtpd.socket = socket
smtpd.DEBUGSTREAM = self.old_debugstream
def write_line(self, line):
self.channel.socket.queue_recv(line)
self.channel.handle_read()
def test_broken_connect(self):
self.assertRaises(
DummyDispatcherBroken, BrokenDummyServer,
(support.HOST, 0), ('b', 0), decode_data=True)
def test_decode_data_and_enable_SMTPUTF8_raises(self):
self.assertRaises(
ValueError, smtpd.SMTPChannel,
self.server, self.channel.conn, self.channel.addr,
enable_SMTPUTF8=True, decode_data=True)
def test_server_accept(self):
self.server.handle_accept()
def test_missing_data(self):
self.write_line(b'')
self.assertEqual(self.channel.socket.last,
b'500 Error: bad syntax\r\n')
def test_EHLO(self):
self.write_line(b'EHLO example')
self.assertEqual(self.channel.socket.last, b'250 HELP\r\n')
def test_EHLO_bad_syntax(self):
self.write_line(b'EHLO')
self.assertEqual(self.channel.socket.last,
b'501 Syntax: EHLO hostname\r\n')
def test_EHLO_duplicate(self):
self.write_line(b'EHLO example')
self.write_line(b'EHLO example')
self.assertEqual(self.channel.socket.last,
b'503 Duplicate HELO/EHLO\r\n')
def test_EHLO_HELO_duplicate(self):
self.write_line(b'EHLO example')
self.write_line(b'HELO example')
self.assertEqual(self.channel.socket.last,
b'503 Duplicate HELO/EHLO\r\n')
def test_HELO(self):
name = smtpd.socket.getfqdn()
self.write_line(b'HELO example')
self.assertEqual(self.channel.socket.last,
'250 {}\r\n'.format(name).encode('ascii'))
def test_HELO_EHLO_duplicate(self):
self.write_line(b'HELO example')
self.write_line(b'EHLO example')
self.assertEqual(self.channel.socket.last,
b'503 Duplicate HELO/EHLO\r\n')
def test_HELP(self):
self.write_line(b'HELP')
self.assertEqual(self.channel.socket.last,
b'250 Supported commands: EHLO HELO MAIL RCPT ' + \
b'DATA RSET NOOP QUIT VRFY\r\n')
def test_HELP_command(self):
self.write_line(b'HELP MAIL')
self.assertEqual(self.channel.socket.last,
b'250 Syntax: MAIL FROM: <address>\r\n')
def test_HELP_command_unknown(self):
self.write_line(b'HELP SPAM')
self.assertEqual(self.channel.socket.last,
b'501 Supported commands: EHLO HELO MAIL RCPT ' + \
b'DATA RSET NOOP QUIT VRFY\r\n')
def test_HELO_bad_syntax(self):
self.write_line(b'HELO')
self.assertEqual(self.channel.socket.last,
b'501 Syntax: HELO hostname\r\n')
def test_HELO_duplicate(self):
self.write_line(b'HELO example')
self.write_line(b'HELO example')
self.assertEqual(self.channel.socket.last,
b'503 Duplicate HELO/EHLO\r\n')
def test_HELO_parameter_rejected_when_extensions_not_enabled(self):
self.extended_smtp = False
self.write_line(b'HELO example')
self.write_line(b'MAIL from:<[email protected]> SIZE=1234')
self.assertEqual(self.channel.socket.last,
b'501 Syntax: MAIL FROM: <address>\r\n')
def test_MAIL_allows_space_after_colon(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL from: <[email protected]>')
self.assertEqual(self.channel.socket.last,
b'250 OK\r\n')
def test_extended_MAIL_allows_space_after_colon(self):
self.write_line(b'EHLO example')
self.write_line(b'MAIL from: <[email protected]> size=20')
self.assertEqual(self.channel.socket.last,
b'250 OK\r\n')
def test_NOOP(self):
self.write_line(b'NOOP')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
def test_HELO_NOOP(self):
self.write_line(b'HELO example')
self.write_line(b'NOOP')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
def test_NOOP_bad_syntax(self):
self.write_line(b'NOOP hi')
self.assertEqual(self.channel.socket.last,
b'501 Syntax: NOOP\r\n')
def test_QUIT(self):
self.write_line(b'QUIT')
self.assertEqual(self.channel.socket.last, b'221 Bye\r\n')
def test_HELO_QUIT(self):
self.write_line(b'HELO example')
self.write_line(b'QUIT')
self.assertEqual(self.channel.socket.last, b'221 Bye\r\n')
def test_QUIT_arg_ignored(self):
self.write_line(b'QUIT bye bye')
self.assertEqual(self.channel.socket.last, b'221 Bye\r\n')
def test_bad_state(self):
self.channel.smtp_state = 'BAD STATE'
self.write_line(b'HELO example')
self.assertEqual(self.channel.socket.last,
b'451 Internal confusion\r\n')
def test_command_too_long(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL from: ' +
b'a' * self.channel.command_size_limit +
b'@example')
self.assertEqual(self.channel.socket.last,
b'500 Error: line too long\r\n')
def test_MAIL_command_limit_extended_with_SIZE(self):
self.write_line(b'EHLO example')
fill_len = self.channel.command_size_limit - len('MAIL from:<@example>')
self.write_line(b'MAIL from:<' +
b'a' * fill_len +
b'@example> SIZE=1234')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
self.write_line(b'MAIL from:<' +
b'a' * (fill_len + 26) +
b'@example> SIZE=1234')
self.assertEqual(self.channel.socket.last,
b'500 Error: line too long\r\n')
def test_MAIL_command_rejects_SMTPUTF8_by_default(self):
self.write_line(b'EHLO example')
self.write_line(
b'MAIL from: <[email protected]> BODY=8BITMIME SMTPUTF8')
self.assertEqual(self.channel.socket.last[0:1], b'5')
def test_data_longer_than_default_data_size_limit(self):
# Hack the default so we don't have to generate so much data.
self.channel.data_size_limit = 1048
self.write_line(b'HELO example')
self.write_line(b'MAIL From:eggs@example')
self.write_line(b'RCPT To:spam@example')
self.write_line(b'DATA')
self.write_line(b'A' * self.channel.data_size_limit +
b'A\r\n.')
self.assertEqual(self.channel.socket.last,
b'552 Error: Too much mail data\r\n')
def test_MAIL_size_parameter(self):
self.write_line(b'EHLO example')
self.write_line(b'MAIL FROM:<eggs@example> SIZE=512')
self.assertEqual(self.channel.socket.last,
b'250 OK\r\n')
def test_MAIL_invalid_size_parameter(self):
self.write_line(b'EHLO example')
self.write_line(b'MAIL FROM:<eggs@example> SIZE=invalid')
self.assertEqual(self.channel.socket.last,
b'501 Syntax: MAIL FROM: <address> [SP <mail-parameters>]\r\n')
def test_MAIL_RCPT_unknown_parameters(self):
self.write_line(b'EHLO example')
self.write_line(b'MAIL FROM:<eggs@example> ham=green')
self.assertEqual(self.channel.socket.last,
b'555 MAIL FROM parameters not recognized or not implemented\r\n')
self.write_line(b'MAIL FROM:<eggs@example>')
self.write_line(b'RCPT TO:<eggs@example> ham=green')
self.assertEqual(self.channel.socket.last,
b'555 RCPT TO parameters not recognized or not implemented\r\n')
def test_MAIL_size_parameter_larger_than_default_data_size_limit(self):
self.channel.data_size_limit = 1048
self.write_line(b'EHLO example')
self.write_line(b'MAIL FROM:<eggs@example> SIZE=2096')
self.assertEqual(self.channel.socket.last,
b'552 Error: message size exceeds fixed maximum message size\r\n')
def test_need_MAIL(self):
self.write_line(b'HELO example')
self.write_line(b'RCPT to:spam@example')
self.assertEqual(self.channel.socket.last,
b'503 Error: need MAIL command\r\n')
def test_MAIL_syntax_HELO(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL from eggs@example')
self.assertEqual(self.channel.socket.last,
b'501 Syntax: MAIL FROM: <address>\r\n')
def test_MAIL_syntax_EHLO(self):
self.write_line(b'EHLO example')
self.write_line(b'MAIL from eggs@example')
self.assertEqual(self.channel.socket.last,
b'501 Syntax: MAIL FROM: <address> [SP <mail-parameters>]\r\n')
def test_MAIL_missing_address(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL from:')
self.assertEqual(self.channel.socket.last,
b'501 Syntax: MAIL FROM: <address>\r\n')
def test_MAIL_chevrons(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL from:<eggs@example>')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
def test_MAIL_empty_chevrons(self):
self.write_line(b'EHLO example')
self.write_line(b'MAIL from:<>')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
def test_MAIL_quoted_localpart(self):
self.write_line(b'EHLO example')
self.write_line(b'MAIL from: <"Fred Blogs"@example.com>')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
self.assertEqual(self.channel.mailfrom, '"Fred Blogs"@example.com')
def test_MAIL_quoted_localpart_no_angles(self):
self.write_line(b'EHLO example')
self.write_line(b'MAIL from: "Fred Blogs"@example.com')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
self.assertEqual(self.channel.mailfrom, '"Fred Blogs"@example.com')
def test_MAIL_quoted_localpart_with_size(self):
self.write_line(b'EHLO example')
self.write_line(b'MAIL from: <"Fred Blogs"@example.com> SIZE=1000')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
self.assertEqual(self.channel.mailfrom, '"Fred Blogs"@example.com')
def test_MAIL_quoted_localpart_with_size_no_angles(self):
self.write_line(b'EHLO example')
self.write_line(b'MAIL from: "Fred Blogs"@example.com SIZE=1000')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
self.assertEqual(self.channel.mailfrom, '"Fred Blogs"@example.com')
def test_nested_MAIL(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL from:eggs@example')
self.write_line(b'MAIL from:spam@example')
self.assertEqual(self.channel.socket.last,
b'503 Error: nested MAIL command\r\n')
def test_VRFY(self):
self.write_line(b'VRFY eggs@example')
self.assertEqual(self.channel.socket.last,
b'252 Cannot VRFY user, but will accept message and attempt ' + \
b'delivery\r\n')
def test_VRFY_syntax(self):
self.write_line(b'VRFY')
self.assertEqual(self.channel.socket.last,
b'501 Syntax: VRFY <address>\r\n')
def test_EXPN_not_implemented(self):
self.write_line(b'EXPN')
self.assertEqual(self.channel.socket.last,
b'502 EXPN not implemented\r\n')
def test_no_HELO_MAIL(self):
self.write_line(b'MAIL from:<[email protected]>')
self.assertEqual(self.channel.socket.last,
b'503 Error: send HELO first\r\n')
def test_need_RCPT(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL From:eggs@example')
self.write_line(b'DATA')
self.assertEqual(self.channel.socket.last,
b'503 Error: need RCPT command\r\n')
def test_RCPT_syntax_HELO(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL From: eggs@example')
self.write_line(b'RCPT to eggs@example')
self.assertEqual(self.channel.socket.last,
b'501 Syntax: RCPT TO: <address>\r\n')
def test_RCPT_syntax_EHLO(self):
self.write_line(b'EHLO example')
self.write_line(b'MAIL From: eggs@example')
self.write_line(b'RCPT to eggs@example')
self.assertEqual(self.channel.socket.last,
b'501 Syntax: RCPT TO: <address> [SP <mail-parameters>]\r\n')
def test_RCPT_lowercase_to_OK(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL From: eggs@example')
self.write_line(b'RCPT to: <eggs@example>')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
def test_no_HELO_RCPT(self):
self.write_line(b'RCPT to eggs@example')
self.assertEqual(self.channel.socket.last,
b'503 Error: send HELO first\r\n')
def test_data_dialog(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL From:eggs@example')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
self.write_line(b'RCPT To:spam@example')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
self.write_line(b'DATA')
self.assertEqual(self.channel.socket.last,
b'354 End data with <CR><LF>.<CR><LF>\r\n')
self.write_line(b'data\r\nmore\r\n.')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
self.assertEqual(self.server.messages,
[(('peer-address', 'peer-port'),
'eggs@example',
['spam@example'],
'data\nmore')])
def test_DATA_syntax(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL From:eggs@example')
self.write_line(b'RCPT To:spam@example')
self.write_line(b'DATA spam')
self.assertEqual(self.channel.socket.last, b'501 Syntax: DATA\r\n')
def test_no_HELO_DATA(self):
self.write_line(b'DATA spam')
self.assertEqual(self.channel.socket.last,
b'503 Error: send HELO first\r\n')
def test_data_transparency_section_4_5_2(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL From:eggs@example')
self.write_line(b'RCPT To:spam@example')
self.write_line(b'DATA')
self.write_line(b'..\r\n.\r\n')
self.assertEqual(self.channel.received_data, '.')
def test_multiple_RCPT(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL From:eggs@example')
self.write_line(b'RCPT To:spam@example')
self.write_line(b'RCPT To:ham@example')
self.write_line(b'DATA')
self.write_line(b'data\r\n.')
self.assertEqual(self.server.messages,
[(('peer-address', 'peer-port'),
'eggs@example',
['spam@example','ham@example'],
'data')])
def test_manual_status(self):
# checks that the Channel is able to return a custom status message
self.write_line(b'HELO example')
self.write_line(b'MAIL From:eggs@example')
self.write_line(b'RCPT To:spam@example')
self.write_line(b'DATA')
self.write_line(b'return status\r\n.')
self.assertEqual(self.channel.socket.last, b'250 Okish\r\n')
def test_RSET(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL From:eggs@example')
self.write_line(b'RCPT To:spam@example')
self.write_line(b'RSET')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
self.write_line(b'MAIL From:foo@example')
self.write_line(b'RCPT To:eggs@example')
self.write_line(b'DATA')
self.write_line(b'data\r\n.')
self.assertEqual(self.server.messages,
[(('peer-address', 'peer-port'),
'foo@example',
['eggs@example'],
'data')])
def test_HELO_RSET(self):
self.write_line(b'HELO example')
self.write_line(b'RSET')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
def test_RSET_syntax(self):
self.write_line(b'RSET hi')
self.assertEqual(self.channel.socket.last, b'501 Syntax: RSET\r\n')
def test_unknown_command(self):
self.write_line(b'UNKNOWN_CMD')
self.assertEqual(self.channel.socket.last,
b'500 Error: command "UNKNOWN_CMD" not ' + \
b'recognized\r\n')
def test_attribute_deprecations(self):
with support.check_warnings(('', DeprecationWarning)):
spam = self.channel._SMTPChannel__server
with support.check_warnings(('', DeprecationWarning)):
self.channel._SMTPChannel__server = 'spam'
with support.check_warnings(('', DeprecationWarning)):
spam = self.channel._SMTPChannel__line
with support.check_warnings(('', DeprecationWarning)):
self.channel._SMTPChannel__line = 'spam'
with support.check_warnings(('', DeprecationWarning)):
spam = self.channel._SMTPChannel__state
with support.check_warnings(('', DeprecationWarning)):
self.channel._SMTPChannel__state = 'spam'
with support.check_warnings(('', DeprecationWarning)):
spam = self.channel._SMTPChannel__greeting
with support.check_warnings(('', DeprecationWarning)):
self.channel._SMTPChannel__greeting = 'spam'
with support.check_warnings(('', DeprecationWarning)):
spam = self.channel._SMTPChannel__mailfrom
with support.check_warnings(('', DeprecationWarning)):
self.channel._SMTPChannel__mailfrom = 'spam'
with support.check_warnings(('', DeprecationWarning)):
spam = self.channel._SMTPChannel__rcpttos
with support.check_warnings(('', DeprecationWarning)):
self.channel._SMTPChannel__rcpttos = 'spam'
with support.check_warnings(('', DeprecationWarning)):
spam = self.channel._SMTPChannel__data
with support.check_warnings(('', DeprecationWarning)):
self.channel._SMTPChannel__data = 'spam'
with support.check_warnings(('', DeprecationWarning)):
spam = self.channel._SMTPChannel__fqdn
with support.check_warnings(('', DeprecationWarning)):
self.channel._SMTPChannel__fqdn = 'spam'
with support.check_warnings(('', DeprecationWarning)):
spam = self.channel._SMTPChannel__peer
with support.check_warnings(('', DeprecationWarning)):
self.channel._SMTPChannel__peer = 'spam'
with support.check_warnings(('', DeprecationWarning)):
spam = self.channel._SMTPChannel__conn
with support.check_warnings(('', DeprecationWarning)):
self.channel._SMTPChannel__conn = 'spam'
with support.check_warnings(('', DeprecationWarning)):
spam = self.channel._SMTPChannel__addr
with support.check_warnings(('', DeprecationWarning)):
self.channel._SMTPChannel__addr = 'spam'
@unittest.skipUnless(support.IPV6_ENABLED, "IPv6 not enabled")
class SMTPDChannelIPv6Test(SMTPDChannelTest):
def setUp(self):
smtpd.socket = asyncore.socket = mock_socket
self.old_debugstream = smtpd.DEBUGSTREAM
self.debug = smtpd.DEBUGSTREAM = io.StringIO()
self.server = DummyServer((support.HOSTv6, 0), ('b', 0),
decode_data=True)
conn, addr = self.server.accept()
self.channel = smtpd.SMTPChannel(self.server, conn, addr,
decode_data=True)
class SMTPDChannelWithDataSizeLimitTest(unittest.TestCase):
def setUp(self):
smtpd.socket = asyncore.socket = mock_socket
self.old_debugstream = smtpd.DEBUGSTREAM
self.debug = smtpd.DEBUGSTREAM = io.StringIO()
self.server = DummyServer((support.HOST, 0), ('b', 0),
decode_data=True)
conn, addr = self.server.accept()
# Set DATA size limit to 32 bytes for easy testing
self.channel = smtpd.SMTPChannel(self.server, conn, addr, 32,
decode_data=True)
def tearDown(self):
asyncore.close_all()
asyncore.socket = smtpd.socket = socket
smtpd.DEBUGSTREAM = self.old_debugstream
def write_line(self, line):
self.channel.socket.queue_recv(line)
self.channel.handle_read()
def test_data_limit_dialog(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL From:eggs@example')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
self.write_line(b'RCPT To:spam@example')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
self.write_line(b'DATA')
self.assertEqual(self.channel.socket.last,
b'354 End data with <CR><LF>.<CR><LF>\r\n')
self.write_line(b'data\r\nmore\r\n.')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
self.assertEqual(self.server.messages,
[(('peer-address', 'peer-port'),
'eggs@example',
['spam@example'],
'data\nmore')])
def test_data_limit_dialog_too_much_data(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL From:eggs@example')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
self.write_line(b'RCPT To:spam@example')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
self.write_line(b'DATA')
self.assertEqual(self.channel.socket.last,
b'354 End data with <CR><LF>.<CR><LF>\r\n')
self.write_line(b'This message is longer than 32 bytes\r\n.')
self.assertEqual(self.channel.socket.last,
b'552 Error: Too much mail data\r\n')
class SMTPDChannelWithDecodeDataFalse(unittest.TestCase):
def setUp(self):
smtpd.socket = asyncore.socket = mock_socket
self.old_debugstream = smtpd.DEBUGSTREAM
self.debug = smtpd.DEBUGSTREAM = io.StringIO()
self.server = DummyServer((support.HOST, 0), ('b', 0))
conn, addr = self.server.accept()
self.channel = smtpd.SMTPChannel(self.server, conn, addr)
def tearDown(self):
asyncore.close_all()
asyncore.socket = smtpd.socket = socket
smtpd.DEBUGSTREAM = self.old_debugstream
def write_line(self, line):
self.channel.socket.queue_recv(line)
self.channel.handle_read()
def test_ascii_data(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL From:eggs@example')
self.write_line(b'RCPT To:spam@example')
self.write_line(b'DATA')
self.write_line(b'plain ascii text')
self.write_line(b'.')
self.assertEqual(self.channel.received_data, b'plain ascii text')
def test_utf8_data(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL From:eggs@example')
self.write_line(b'RCPT To:spam@example')
self.write_line(b'DATA')
self.write_line(b'utf8 enriched text: \xc5\xbc\xc5\xba\xc4\x87')
self.write_line(b'and some plain ascii')
self.write_line(b'.')
self.assertEqual(
self.channel.received_data,
b'utf8 enriched text: \xc5\xbc\xc5\xba\xc4\x87\n'
b'and some plain ascii')
class SMTPDChannelWithDecodeDataTrue(unittest.TestCase):
def setUp(self):
smtpd.socket = asyncore.socket = mock_socket
self.old_debugstream = smtpd.DEBUGSTREAM
self.debug = smtpd.DEBUGSTREAM = io.StringIO()
self.server = DummyServer((support.HOST, 0), ('b', 0),
decode_data=True)
conn, addr = self.server.accept()
# Set decode_data to True
self.channel = smtpd.SMTPChannel(self.server, conn, addr,
decode_data=True)
def tearDown(self):
asyncore.close_all()
asyncore.socket = smtpd.socket = socket
smtpd.DEBUGSTREAM = self.old_debugstream
def write_line(self, line):
self.channel.socket.queue_recv(line)
self.channel.handle_read()
def test_ascii_data(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL From:eggs@example')
self.write_line(b'RCPT To:spam@example')
self.write_line(b'DATA')
self.write_line(b'plain ascii text')
self.write_line(b'.')
self.assertEqual(self.channel.received_data, 'plain ascii text')
def test_utf8_data(self):
self.write_line(b'HELO example')
self.write_line(b'MAIL From:eggs@example')
self.write_line(b'RCPT To:spam@example')
self.write_line(b'DATA')
self.write_line(b'utf8 enriched text: \xc5\xbc\xc5\xba\xc4\x87')
self.write_line(b'and some plain ascii')
self.write_line(b'.')
self.assertEqual(
self.channel.received_data,
'utf8 enriched text: żźÄ\nand some plain ascii')
class SMTPDChannelTestWithEnableSMTPUTF8True(unittest.TestCase):
def setUp(self):
smtpd.socket = asyncore.socket = mock_socket
self.old_debugstream = smtpd.DEBUGSTREAM
self.debug = smtpd.DEBUGSTREAM = io.StringIO()
self.server = DummyServer((support.HOST, 0), ('b', 0),
enable_SMTPUTF8=True)
conn, addr = self.server.accept()
self.channel = smtpd.SMTPChannel(self.server, conn, addr,
enable_SMTPUTF8=True)
def tearDown(self):
asyncore.close_all()
asyncore.socket = smtpd.socket = socket
smtpd.DEBUGSTREAM = self.old_debugstream
def write_line(self, line):
self.channel.socket.queue_recv(line)
self.channel.handle_read()
def test_MAIL_command_accepts_SMTPUTF8_when_announced(self):
self.write_line(b'EHLO example')
self.write_line(
'MAIL from: <naiÌ[email protected]> BODY=8BITMIME SMTPUTF8'.encode(
'utf-8')
)
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
def test_process_smtputf8_message(self):
self.write_line(b'EHLO example')
for mail_parameters in [b'', b'BODY=8BITMIME SMTPUTF8']:
self.write_line(b'MAIL from: <a@example> ' + mail_parameters)
self.assertEqual(self.channel.socket.last[0:3], b'250')
self.write_line(b'rcpt to:<[email protected]>')
self.assertEqual(self.channel.socket.last[0:3], b'250')
self.write_line(b'data')
self.assertEqual(self.channel.socket.last[0:3], b'354')
self.write_line(b'c\r\n.')
if mail_parameters == b'':
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
else:
self.assertEqual(self.channel.socket.last,
b'250 SMTPUTF8 message okish\r\n')
def test_utf8_data(self):
self.write_line(b'EHLO example')
self.write_line(
'MAIL From: naiÌve@examplé BODY=8BITMIME SMTPUTF8'.encode('utf-8'))
self.assertEqual(self.channel.socket.last[0:3], b'250')
self.write_line('RCPT To:späm@examplé'.encode('utf-8'))
self.assertEqual(self.channel.socket.last[0:3], b'250')
self.write_line(b'DATA')
self.assertEqual(self.channel.socket.last[0:3], b'354')
self.write_line(b'utf8 enriched text: \xc5\xbc\xc5\xba\xc4\x87')
self.write_line(b'.')
self.assertEqual(
self.channel.received_data,
b'utf8 enriched text: \xc5\xbc\xc5\xba\xc4\x87')
def test_MAIL_command_limit_extended_with_SIZE_and_SMTPUTF8(self):
self.write_line(b'ehlo example')
fill_len = (512 + 26 + 10) - len('mail from:<@example>')
self.write_line(b'MAIL from:<' +
b'a' * (fill_len + 1) +
b'@example>')
self.assertEqual(self.channel.socket.last,
b'500 Error: line too long\r\n')
self.write_line(b'MAIL from:<' +
b'a' * fill_len +
b'@example>')
self.assertEqual(self.channel.socket.last, b'250 OK\r\n')
def test_multiple_emails_with_extended_command_length(self):
self.write_line(b'ehlo example')
fill_len = (512 + 26 + 10) - len('mail from:<@example>')
for char in [b'a', b'b', b'c']:
self.write_line(b'MAIL from:<' + char * fill_len + b'a@example>')
self.assertEqual(self.channel.socket.last[0:3], b'500')
self.write_line(b'MAIL from:<' + char * fill_len + b'@example>')
self.assertEqual(self.channel.socket.last[0:3], b'250')
self.write_line(b'rcpt to:<[email protected]>')
self.assertEqual(self.channel.socket.last[0:3], b'250')
self.write_line(b'data')
self.assertEqual(self.channel.socket.last[0:3], b'354')
self.write_line(b'test\r\n.')
self.assertEqual(self.channel.socket.last[0:3], b'250')
class MiscTestCase(unittest.TestCase):
def test__all__(self):
blacklist = {
"program", "Devnull", "DEBUGSTREAM", "NEWLINE", "COMMASPACE",
"DATA_SIZE_DEFAULT", "usage", "Options", "parseargs",
}
support.check__all__(self, smtpd, blacklist=blacklist)
if __name__ == "__main__":
unittest.main()
| 41,104 | 1,014 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_syntax.py | """This module tests SyntaxErrors.
Here's an example of the sort of thing that is tested.
>>> def f(x):
... global x
Traceback (most recent call last):
SyntaxError: name 'x' is parameter and global
The tests are all raise SyntaxErrors. They were created by checking
each C call that raises SyntaxError. There are several modules that
raise these exceptions-- ast.c, compile.c, future.c, pythonrun.c, and
symtable.c.
The parser itself outlaws a lot of invalid syntax. None of these
errors are tested here at the moment. We should add some tests; since
there are infinitely many programs with invalid syntax, we would need
to be judicious in selecting some.
The compiler generates a synthetic module name for code executed by
doctest. Since all the code comes from the same module, a suffix like
[1] is appended to the module name, As a consequence, changing the
order of tests in this module means renumbering all the errors after
it. (Maybe we should enable the ellipsis option for these tests.)
In ast.c, syntax errors are raised by calling ast_error().
Errors from set_context():
>>> obj.None = 1
Traceback (most recent call last):
SyntaxError: invalid syntax
>>> None = 1
Traceback (most recent call last):
SyntaxError: can't assign to keyword
>>> f() = 1
Traceback (most recent call last):
SyntaxError: can't assign to function call
>>> del f()
Traceback (most recent call last):
SyntaxError: can't delete function call
>>> a + 1 = 2
Traceback (most recent call last):
SyntaxError: can't assign to operator
>>> (x for x in x) = 1
Traceback (most recent call last):
SyntaxError: can't assign to generator expression
>>> 1 = 1
Traceback (most recent call last):
SyntaxError: can't assign to literal
>>> "abc" = 1
Traceback (most recent call last):
SyntaxError: can't assign to literal
>>> b"" = 1
Traceback (most recent call last):
SyntaxError: can't assign to literal
>>> `1` = 1
Traceback (most recent call last):
SyntaxError: invalid syntax
If the left-hand side of an assignment is a list or tuple, an illegal
expression inside that contain should still cause a syntax error.
This test just checks a couple of cases rather than enumerating all of
them.
>>> (a, "b", c) = (1, 2, 3)
Traceback (most recent call last):
SyntaxError: can't assign to literal
>>> [a, b, c + 1] = [1, 2, 3]
Traceback (most recent call last):
SyntaxError: can't assign to operator
>>> a if 1 else b = 1
Traceback (most recent call last):
SyntaxError: can't assign to conditional expression
From compiler_complex_args():
>>> def f(None=1):
... pass
Traceback (most recent call last):
SyntaxError: invalid syntax
From ast_for_arguments():
>>> def f(x, y=1, z):
... pass
Traceback (most recent call last):
SyntaxError: non-default argument follows default argument
>>> def f(x, None):
... pass
Traceback (most recent call last):
SyntaxError: invalid syntax
>>> def f(*None):
... pass
Traceback (most recent call last):
SyntaxError: invalid syntax
>>> def f(**None):
... pass
Traceback (most recent call last):
SyntaxError: invalid syntax
From ast_for_funcdef():
>>> def None(x):
... pass
Traceback (most recent call last):
SyntaxError: invalid syntax
From ast_for_call():
>>> def f(it, *varargs):
... return list(it)
>>> L = range(10)
>>> f(x for x in L)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> f(x for x in L, 1)
Traceback (most recent call last):
SyntaxError: Generator expression must be parenthesized if not sole argument
>>> f(x for x in L, y for y in L)
Traceback (most recent call last):
SyntaxError: Generator expression must be parenthesized if not sole argument
>>> f((x for x in L), 1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> f(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11,
... i12, i13, i14, i15, i16, i17, i18, i19, i20, i21, i22,
... i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33,
... i34, i35, i36, i37, i38, i39, i40, i41, i42, i43, i44,
... i45, i46, i47, i48, i49, i50, i51, i52, i53, i54, i55,
... i56, i57, i58, i59, i60, i61, i62, i63, i64, i65, i66,
... i67, i68, i69, i70, i71, i72, i73, i74, i75, i76, i77,
... i78, i79, i80, i81, i82, i83, i84, i85, i86, i87, i88,
... i89, i90, i91, i92, i93, i94, i95, i96, i97, i98, i99,
... i100, i101, i102, i103, i104, i105, i106, i107, i108,
... i109, i110, i111, i112, i113, i114, i115, i116, i117,
... i118, i119, i120, i121, i122, i123, i124, i125, i126,
... i127, i128, i129, i130, i131, i132, i133, i134, i135,
... i136, i137, i138, i139, i140, i141, i142, i143, i144,
... i145, i146, i147, i148, i149, i150, i151, i152, i153,
... i154, i155, i156, i157, i158, i159, i160, i161, i162,
... i163, i164, i165, i166, i167, i168, i169, i170, i171,
... i172, i173, i174, i175, i176, i177, i178, i179, i180,
... i181, i182, i183, i184, i185, i186, i187, i188, i189,
... i190, i191, i192, i193, i194, i195, i196, i197, i198,
... i199, i200, i201, i202, i203, i204, i205, i206, i207,
... i208, i209, i210, i211, i212, i213, i214, i215, i216,
... i217, i218, i219, i220, i221, i222, i223, i224, i225,
... i226, i227, i228, i229, i230, i231, i232, i233, i234,
... i235, i236, i237, i238, i239, i240, i241, i242, i243,
... i244, i245, i246, i247, i248, i249, i250, i251, i252,
... i253, i254, i255)
Traceback (most recent call last):
SyntaxError: more than 255 arguments
The actual error cases counts positional arguments, keyword arguments,
and generator expression arguments separately. This test combines the
three.
>>> f(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11,
... i12, i13, i14, i15, i16, i17, i18, i19, i20, i21, i22,
... i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33,
... i34, i35, i36, i37, i38, i39, i40, i41, i42, i43, i44,
... i45, i46, i47, i48, i49, i50, i51, i52, i53, i54, i55,
... i56, i57, i58, i59, i60, i61, i62, i63, i64, i65, i66,
... i67, i68, i69, i70, i71, i72, i73, i74, i75, i76, i77,
... i78, i79, i80, i81, i82, i83, i84, i85, i86, i87, i88,
... i89, i90, i91, i92, i93, i94, i95, i96, i97, i98, i99,
... i100, i101, i102, i103, i104, i105, i106, i107, i108,
... i109, i110, i111, i112, i113, i114, i115, i116, i117,
... i118, i119, i120, i121, i122, i123, i124, i125, i126,
... i127, i128, i129, i130, i131, i132, i133, i134, i135,
... i136, i137, i138, i139, i140, i141, i142, i143, i144,
... i145, i146, i147, i148, i149, i150, i151, i152, i153,
... i154, i155, i156, i157, i158, i159, i160, i161, i162,
... i163, i164, i165, i166, i167, i168, i169, i170, i171,
... i172, i173, i174, i175, i176, i177, i178, i179, i180,
... i181, i182, i183, i184, i185, i186, i187, i188, i189,
... i190, i191, i192, i193, i194, i195, i196, i197, i198,
... i199, i200, i201, i202, i203, i204, i205, i206, i207,
... i208, i209, i210, i211, i212, i213, i214, i215, i216,
... i217, i218, i219, i220, i221, i222, i223, i224, i225,
... i226, i227, i228, i229, i230, i231, i232, i233, i234,
... i235, i236, i237, i238, i239, i240, i241, i242, i243,
... (x for x in i244), i245, i246, i247, i248, i249, i250, i251,
... i252=1, i253=1, i254=1, i255=1)
Traceback (most recent call last):
SyntaxError: more than 255 arguments
>>> class C:
... def meth(self, *args):
... return args
>>> obj = C()
>>> obj.meth(
... 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
... 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
... 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
... 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
... 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
... 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
... 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
... 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
... 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
... 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163,
... 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
... 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
... 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205,
... 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
... 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
... 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
... 248, 249, 250, 251, 252, 253, 254) # doctest: +ELLIPSIS
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 252, 253, 254)
>>> f(lambda x: x[0] = 3)
Traceback (most recent call last):
SyntaxError: lambda cannot contain assignment
The grammar accepts any test (basically, any expression) in the
keyword slot of a call site. Test a few different options.
>>> f(x()=2)
Traceback (most recent call last):
SyntaxError: keyword can't be an expression
>>> f(a or b=1)
Traceback (most recent call last):
SyntaxError: keyword can't be an expression
>>> f(x.y=1)
Traceback (most recent call last):
SyntaxError: keyword can't be an expression
More set_context():
>>> (x for x in x) += 1
Traceback (most recent call last):
SyntaxError: can't assign to generator expression
>>> None += 1
Traceback (most recent call last):
SyntaxError: can't assign to keyword
>>> f() += 1
Traceback (most recent call last):
SyntaxError: can't assign to function call
Test continue in finally in weird combinations.
continue in for loop under finally should be ok.
>>> def test():
... try:
... pass
... finally:
... for abc in range(10):
... continue
... print(abc)
>>> test()
9
Start simple, a continue in a finally should not be allowed.
>>> def test():
... for abc in range(10):
... try:
... pass
... finally:
... continue
Traceback (most recent call last):
...
SyntaxError: 'continue' not supported inside 'finally' clause
This is essentially a continue in a finally which should not be allowed.
>>> def test():
... for abc in range(10):
... try:
... pass
... finally:
... try:
... continue
... except:
... pass
Traceback (most recent call last):
...
SyntaxError: 'continue' not supported inside 'finally' clause
>>> def foo():
... try:
... pass
... finally:
... continue
Traceback (most recent call last):
...
SyntaxError: 'continue' not supported inside 'finally' clause
>>> def foo():
... for a in ():
... try:
... pass
... finally:
... continue
Traceback (most recent call last):
...
SyntaxError: 'continue' not supported inside 'finally' clause
>>> def foo():
... for a in ():
... try:
... pass
... finally:
... try:
... continue
... finally:
... pass
Traceback (most recent call last):
...
SyntaxError: 'continue' not supported inside 'finally' clause
>>> def foo():
... for a in ():
... try: pass
... finally:
... try:
... pass
... except:
... continue
Traceback (most recent call last):
...
SyntaxError: 'continue' not supported inside 'finally' clause
There is one test for a break that is not in a loop. The compiler
uses a single data structure to keep track of try-finally and loops,
so we need to be sure that a break is actually inside a loop. If it
isn't, there should be a syntax error.
>>> try:
... print(1)
... break
... print(2)
... finally:
... print(3)
Traceback (most recent call last):
...
SyntaxError: 'break' outside loop
This raises a SyntaxError, it used to raise a SystemError.
Context for this change can be found on issue #27514
In 2.5 there was a missing exception and an assert was triggered in a debug
build. The number of blocks must be greater than CO_MAXBLOCKS. SF #1565514
>>> while 1:
... while 2:
... while 3:
... while 4:
... while 5:
... while 6:
... while 8:
... while 9:
... while 10:
... while 11:
... while 12:
... while 13:
... while 14:
... while 15:
... while 16:
... while 17:
... while 18:
... while 19:
... while 20:
... while 21:
... while 22:
... break
Traceback (most recent call last):
...
SyntaxError: too many statically nested blocks
Misuse of the nonlocal and global statement can lead to a few unique syntax errors.
>>> def f():
... x = 1
... global x
Traceback (most recent call last):
...
SyntaxError: name 'x' is assigned to before global declaration
>>> def f():
... x = 1
... def g():
... print(x)
... nonlocal x
Traceback (most recent call last):
...
SyntaxError: name 'x' is used prior to nonlocal declaration
>>> def f():
... x = 1
... def g():
... x = 2
... nonlocal x
Traceback (most recent call last):
...
SyntaxError: name 'x' is assigned to before nonlocal declaration
>>> def f(x):
... nonlocal x
Traceback (most recent call last):
...
SyntaxError: name 'x' is parameter and nonlocal
>>> def f():
... global x
... nonlocal x
Traceback (most recent call last):
...
SyntaxError: name 'x' is nonlocal and global
>>> def f():
... nonlocal x
Traceback (most recent call last):
...
SyntaxError: no binding for nonlocal 'x' found
From SF bug #1705365
>>> nonlocal x
Traceback (most recent call last):
...
SyntaxError: nonlocal declaration not allowed at module level
From https://bugs.python.org/issue25973
>>> class A:
... def f(self):
... nonlocal __x
Traceback (most recent call last):
...
SyntaxError: no binding for nonlocal '_A__x' found
This tests assignment-context; there was a bug in Python 2.5 where compiling
a complex 'if' (one with 'elif') would fail to notice an invalid suite,
leading to spurious errors.
>>> if 1:
... x() = 1
... elif 1:
... pass
Traceback (most recent call last):
...
SyntaxError: can't assign to function call
>>> if 1:
... pass
... elif 1:
... x() = 1
Traceback (most recent call last):
...
SyntaxError: can't assign to function call
>>> if 1:
... x() = 1
... elif 1:
... pass
... else:
... pass
Traceback (most recent call last):
...
SyntaxError: can't assign to function call
>>> if 1:
... pass
... elif 1:
... x() = 1
... else:
... pass
Traceback (most recent call last):
...
SyntaxError: can't assign to function call
>>> if 1:
... pass
... elif 1:
... pass
... else:
... x() = 1
Traceback (most recent call last):
...
SyntaxError: can't assign to function call
Make sure that the old "raise X, Y[, Z]" form is gone:
>>> raise X, Y
Traceback (most recent call last):
...
SyntaxError: invalid syntax
>>> raise X, Y, Z
Traceback (most recent call last):
...
SyntaxError: invalid syntax
>>> f(a=23, a=234)
Traceback (most recent call last):
...
SyntaxError: keyword argument repeated
>>> {1, 2, 3} = 42
Traceback (most recent call last):
SyntaxError: can't assign to literal
Corner-cases that used to fail to raise the correct error:
>>> def f(*, x=lambda __debug__:0): pass
Traceback (most recent call last):
SyntaxError: assignment to keyword
>>> def f(*args:(lambda __debug__:0)): pass
Traceback (most recent call last):
SyntaxError: assignment to keyword
>>> def f(**kwargs:(lambda __debug__:0)): pass
Traceback (most recent call last):
SyntaxError: assignment to keyword
>>> with (lambda *:0): pass
Traceback (most recent call last):
SyntaxError: named arguments must follow bare *
Corner-cases that used to crash:
>>> def f(**__debug__): pass
Traceback (most recent call last):
SyntaxError: assignment to keyword
>>> def f(*xx, __debug__): pass
Traceback (most recent call last):
SyntaxError: assignment to keyword
"""
import re
import unittest
import warnings
from test import support
class SyntaxTestCase(unittest.TestCase):
def _check_error(self, code, errtext,
filename="<testcase>", mode="exec", subclass=None, lineno=None, offset=None):
"""Check that compiling code raises SyntaxError with errtext.
errtest is a regular expression that must be present in the
test of the exception raised. If subclass is specified it
is the expected subclass of SyntaxError (e.g. IndentationError).
"""
try:
compile(code, filename, mode)
except SyntaxError as err:
if subclass and not isinstance(err, subclass):
self.fail("SyntaxError is not a %s" % subclass.__name__)
mo = re.search(errtext, str(err))
if mo is None:
self.fail("SyntaxError did not contain '%r'" % (errtext,))
self.assertEqual(err.filename, filename)
if lineno is not None:
self.assertEqual(err.lineno, lineno)
if offset is not None:
self.assertEqual(err.offset, offset)
else:
self.fail("compile() did not raise SyntaxError")
def test_assign_call(self):
self._check_error("f() = 1", "assign")
def test_assign_del(self):
self._check_error("del f()", "delete")
def test_global_err_then_warn(self):
# Bug #763201: The SyntaxError raised for one global statement
# shouldn't be clobbered by a SyntaxWarning issued for a later one.
source = """if 1:
def error(a):
global a # SyntaxError
def warning():
b = 1
global b # SyntaxWarning
"""
warnings.filterwarnings(action='ignore', category=SyntaxWarning)
self._check_error(source, "global")
warnings.filters.pop(0)
def test_break_outside_loop(self):
self._check_error("break", "outside loop")
def test_unexpected_indent(self):
self._check_error("foo()\n bar()\n", "unexpected indent",
subclass=IndentationError)
def test_no_indent(self):
self._check_error("if 1:\nfoo()", "expected an indented block",
subclass=IndentationError)
def test_bad_outdent(self):
self._check_error("if 1:\n foo()\n bar()",
"unindent does not match .* level",
subclass=IndentationError)
def test_kwargs_last(self):
self._check_error("int(base=10, '2')",
"positional argument follows keyword argument")
def test_kwargs_last2(self):
self._check_error("int(**{'base': 10}, '2')",
"positional argument follows "
"keyword argument unpacking")
def test_kwargs_last3(self):
self._check_error("int(**{'base': 10}, *['2'])",
"iterable argument unpacking follows "
"keyword argument unpacking")
def test_main():
support.run_unittest(SyntaxTestCase)
from test import test_syntax
support.run_doctest(test_syntax, verbosity=True)
if __name__ == "__main__":
test_main()
| 20,456 | 643 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_threaded_import.py | # This is a variant of the very old (early 90's) file
# Demo/threads/bug.py. It simply provokes a number of threads into
# trying to import the same module "at the same time".
# There are no pleasant failure modes -- most likely is that Python
# complains several times about module random having no attribute
# randrange, and then Python hangs.
import _imp as imp
import os
import importlib
import sys
import time
import shutil
import unittest
from test.support import (
verbose, import_module, run_unittest, TESTFN, reap_threads,
forget, unlink, rmtree, start_threads)
threading = import_module('threading')
def task(N, done, done_tasks, errors):
try:
# We don't use modulefinder but still import it in order to stress
# importing of different modules from several threads.
if len(done_tasks) % 2:
import modulefinder
import random
else:
import random
import modulefinder
# This will fail if random is not completely initialized
x = random.randrange(1, 3)
except Exception as e:
errors.append(e.with_traceback(None))
finally:
done_tasks.append(threading.get_ident())
finished = len(done_tasks) == N
if finished:
done.set()
# Create a circular import structure: A -> C -> B -> D -> A
# NOTE: `time` is already loaded and therefore doesn't threaten to deadlock.
circular_imports_modules = {
'A': """if 1:
import time
time.sleep(%(delay)s)
x = 'a'
import C
""",
'B': """if 1:
import time
time.sleep(%(delay)s)
x = 'b'
import D
""",
'C': """import B""",
'D': """import A""",
}
class Finder:
"""A dummy finder to detect concurrent access to its find_spec()
method."""
def __init__(self):
self.numcalls = 0
self.x = 0
self.lock = threading.Lock()
def find_spec(self, name, path=None, target=None):
# Simulate some thread-unsafe behaviour. If calls to find_spec()
# are properly serialized, `x` will end up the same as `numcalls`.
# Otherwise not.
assert imp.lock_held()
with self.lock:
self.numcalls += 1
x = self.x
time.sleep(0.01)
self.x = x + 1
class FlushingFinder:
"""A dummy finder which flushes sys.path_importer_cache when it gets
called."""
def find_spec(self, name, path=None, target=None):
sys.path_importer_cache.clear()
class ThreadedImportTests(unittest.TestCase):
def setUp(self):
self.old_random = sys.modules.pop('random', None)
def tearDown(self):
# If the `random` module was already initialized, we restore the
# old module at the end so that pickling tests don't fail.
# See http://bugs.python.org/issue3657#msg110461
if self.old_random is not None:
sys.modules['random'] = self.old_random
def check_parallel_module_init(self):
if imp.lock_held():
# This triggers on, e.g., from test import autotest.
raise unittest.SkipTest("can't run when import lock is held")
done = threading.Event()
for N in (20, 50) * 3:
if verbose:
print("Trying", N, "threads ...", end=' ')
# Make sure that random and modulefinder get reimported freshly
for modname in ['random', 'modulefinder']:
try:
del sys.modules[modname]
except KeyError:
pass
errors = []
done_tasks = []
done.clear()
t0 = time.monotonic()
with start_threads(threading.Thread(target=task,
args=(N, done, done_tasks, errors,))
for i in range(N)):
pass
completed = done.wait(10 * 60)
dt = time.monotonic() - t0
if verbose:
print("%.1f ms" % (dt*1e3), flush=True, end=" ")
dbg_info = 'done: %s/%s' % (len(done_tasks), N)
self.assertFalse(errors, dbg_info)
self.assertTrue(completed, dbg_info)
if verbose:
print("OK.")
def test_parallel_module_init(self):
self.check_parallel_module_init()
def test_parallel_meta_path(self):
finder = Finder()
sys.meta_path.insert(0, finder)
try:
self.check_parallel_module_init()
self.assertGreater(finder.numcalls, 0)
self.assertEqual(finder.x, finder.numcalls)
finally:
sys.meta_path.remove(finder)
def test_parallel_path_hooks(self):
# Here the Finder instance is only used to check concurrent calls
# to path_hook().
finder = Finder()
# In order for our path hook to be called at each import, we need
# to flush the path_importer_cache, which we do by registering a
# dedicated meta_path entry.
flushing_finder = FlushingFinder()
def path_hook(path):
finder.find_spec('')
raise ImportError
sys.path_hooks.insert(0, path_hook)
sys.meta_path.append(flushing_finder)
try:
# Flush the cache a first time
flushing_finder.find_spec('')
numtests = self.check_parallel_module_init()
self.assertGreater(finder.numcalls, 0)
self.assertEqual(finder.x, finder.numcalls)
finally:
sys.meta_path.remove(flushing_finder)
sys.path_hooks.remove(path_hook)
def test_import_hangers(self):
# In case this test is run again, make sure the helper module
# gets loaded from scratch again.
try:
del sys.modules['test.threaded_import_hangers']
except KeyError:
pass
import test.threaded_import_hangers
self.assertFalse(test.threaded_import_hangers.errors)
def test_circular_imports(self):
# The goal of this test is to exercise implementations of the import
# lock which use a per-module lock, rather than a global lock.
# In these implementations, there is a possible deadlock with
# circular imports, for example:
# - thread 1 imports A (grabbing the lock for A) which imports B
# - thread 2 imports B (grabbing the lock for B) which imports A
# Such implementations should be able to detect such situations and
# resolve them one way or the other, without freezing.
# NOTE: our test constructs a slightly less trivial import cycle,
# in order to better stress the deadlock avoidance mechanism.
delay = 0.5
os.mkdir(TESTFN)
self.addCleanup(shutil.rmtree, TESTFN)
sys.path.insert(0, TESTFN)
self.addCleanup(sys.path.remove, TESTFN)
for name, contents in circular_imports_modules.items():
contents = contents % {'delay': delay}
with open(os.path.join(TESTFN, name + ".py"), "wb") as f:
f.write(contents.encode('utf-8'))
self.addCleanup(forget, name)
importlib.invalidate_caches()
results = []
def import_ab():
import A
results.append(getattr(A, 'x', None))
def import_ba():
import B
results.append(getattr(B, 'x', None))
t1 = threading.Thread(target=import_ab)
t2 = threading.Thread(target=import_ba)
t1.start()
t2.start()
t1.join()
t2.join()
self.assertEqual(set(results), {'a', 'b'})
def test_side_effect_import(self):
code = """if 1:
import threading
def target():
import random
t = threading.Thread(target=target)
t.start()
t.join()
t = None"""
sys.path.insert(0, os.curdir)
self.addCleanup(sys.path.remove, os.curdir)
filename = TESTFN + ".py"
with open(filename, "wb") as f:
f.write(code.encode('utf-8'))
self.addCleanup(unlink, filename)
self.addCleanup(forget, TESTFN)
self.addCleanup(rmtree, '__pycache__')
importlib.invalidate_caches()
__import__(TESTFN)
del sys.modules[TESTFN]
@reap_threads
def test_main():
old_switchinterval = None
try:
old_switchinterval = sys.getswitchinterval()
sys.setswitchinterval(1e-5)
except AttributeError:
pass
try:
run_unittest(ThreadedImportTests)
finally:
if old_switchinterval is not None:
sys.setswitchinterval(old_switchinterval)
if __name__ == "__main__":
test_main()
| 8,782 | 255 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/lock_tests.py | """
Various tests for synchronization primitives.
"""
import sys
import time
from _thread import start_new_thread, TIMEOUT_MAX
import threading
import unittest
import weakref
from test import support
def _wait():
# A crude wait/yield function not relying on synchronization primitives.
time.sleep(0.01)
class Bunch(object):
"""
A bunch of threads.
"""
def __init__(self, f, n, wait_before_exit=False):
"""
Construct a bunch of `n` threads running the same function `f`.
If `wait_before_exit` is True, the threads won't terminate until
do_finish() is called.
"""
self.f = f
self.n = n
self.started = []
self.finished = []
self._can_exit = not wait_before_exit
self.wait_thread = support.wait_threads_exit()
self.wait_thread.__enter__()
def task():
tid = threading.get_ident()
self.started.append(tid)
try:
f()
finally:
self.finished.append(tid)
while not self._can_exit:
_wait()
try:
for i in range(n):
start_new_thread(task, ())
except:
self._can_exit = True
raise
def wait_for_started(self):
while len(self.started) < self.n:
_wait()
def wait_for_finished(self):
while len(self.finished) < self.n:
_wait()
# Wait for threads exit
self.wait_thread.__exit__(None, None, None)
def do_finish(self):
self._can_exit = True
class BaseTestCase(unittest.TestCase):
def setUp(self):
self._threads = support.threading_setup()
def tearDown(self):
support.threading_cleanup(*self._threads)
support.reap_children()
def assertTimeout(self, actual, expected):
# The waiting and/or time.time() can be imprecise, which
# is why comparing to the expected value would sometimes fail
# (especially under Windows).
self.assertGreaterEqual(actual, expected * 0.6)
# Test nothing insane happened
self.assertLess(actual, expected * 10.0)
class BaseLockTests(BaseTestCase):
"""
Tests for both recursive and non-recursive locks.
"""
def test_constructor(self):
lock = self.locktype()
del lock
def test_repr(self):
lock = self.locktype()
self.assertRegex(repr(lock), "<unlocked .* object (.*)?at .*>")
del lock
def test_locked_repr(self):
lock = self.locktype()
lock.acquire()
self.assertRegex(repr(lock), "<locked .* object (.*)?at .*>")
del lock
def test_acquire_destroy(self):
lock = self.locktype()
lock.acquire()
del lock
def test_acquire_release(self):
lock = self.locktype()
lock.acquire()
lock.release()
del lock
def test_try_acquire(self):
lock = self.locktype()
self.assertTrue(lock.acquire(False))
lock.release()
def test_try_acquire_contended(self):
lock = self.locktype()
lock.acquire()
result = []
def f():
result.append(lock.acquire(False))
Bunch(f, 1).wait_for_finished()
self.assertFalse(result[0])
lock.release()
def test_acquire_contended(self):
lock = self.locktype()
lock.acquire()
N = 5
def f():
lock.acquire()
lock.release()
b = Bunch(f, N)
b.wait_for_started()
_wait()
self.assertEqual(len(b.finished), 0)
lock.release()
b.wait_for_finished()
self.assertEqual(len(b.finished), N)
def test_with(self):
lock = self.locktype()
def f():
lock.acquire()
lock.release()
def _with(err=None):
with lock:
if err is not None:
raise err
_with()
# Check the lock is unacquired
Bunch(f, 1).wait_for_finished()
self.assertRaises(TypeError, _with, TypeError)
# Check the lock is unacquired
Bunch(f, 1).wait_for_finished()
def test_thread_leak(self):
# The lock shouldn't leak a Thread instance when used from a foreign
# (non-threading) thread.
lock = self.locktype()
def f():
lock.acquire()
lock.release()
n = len(threading.enumerate())
# We run many threads in the hope that existing threads ids won't
# be recycled.
Bunch(f, 15).wait_for_finished()
if len(threading.enumerate()) != n:
# There is a small window during which a Thread instance's
# target function has finished running, but the Thread is still
# alive and registered. Avoid spurious failures by waiting a
# bit more (seen on a buildbot).
time.sleep(0.4)
self.assertEqual(n, len(threading.enumerate()))
def test_timeout(self):
lock = self.locktype()
# Can't set timeout if not blocking
self.assertRaises(ValueError, lock.acquire, 0, 1)
# Invalid timeout values
self.assertRaises(ValueError, lock.acquire, timeout=-100)
self.assertRaises(OverflowError, lock.acquire, timeout=1e100)
self.assertRaises(OverflowError, lock.acquire, timeout=TIMEOUT_MAX + 1)
# TIMEOUT_MAX is ok
lock.acquire(timeout=TIMEOUT_MAX)
lock.release()
t1 = time.time()
self.assertTrue(lock.acquire(timeout=5))
t2 = time.time()
# Just a sanity test that it didn't actually wait for the timeout.
self.assertLess(t2 - t1, 5)
results = []
def f():
t1 = time.time()
results.append(lock.acquire(timeout=0.5))
t2 = time.time()
results.append(t2 - t1)
Bunch(f, 1).wait_for_finished()
self.assertFalse(results[0])
self.assertTimeout(results[1], 0.5)
def test_weakref_exists(self):
lock = self.locktype()
ref = weakref.ref(lock)
self.assertIsNotNone(ref())
def test_weakref_deleted(self):
lock = self.locktype()
ref = weakref.ref(lock)
del lock
self.assertIsNone(ref())
class LockTests(BaseLockTests):
"""
Tests for non-recursive, weak locks
(which can be acquired and released from different threads).
"""
def test_reacquire(self):
# Lock needs to be released before re-acquiring.
lock = self.locktype()
phase = []
def f():
lock.acquire()
phase.append(None)
lock.acquire()
phase.append(None)
with support.wait_threads_exit():
start_new_thread(f, ())
while len(phase) == 0:
_wait()
_wait()
self.assertEqual(len(phase), 1)
lock.release()
while len(phase) == 1:
_wait()
self.assertEqual(len(phase), 2)
def test_different_thread(self):
# Lock can be released from a different thread.
lock = self.locktype()
lock.acquire()
def f():
lock.release()
b = Bunch(f, 1)
b.wait_for_finished()
lock.acquire()
lock.release()
def test_state_after_timeout(self):
# Issue #11618: check that lock is in a proper state after a
# (non-zero) timeout.
lock = self.locktype()
lock.acquire()
self.assertFalse(lock.acquire(timeout=0.01))
lock.release()
self.assertFalse(lock.locked())
self.assertTrue(lock.acquire(blocking=False))
class RLockTests(BaseLockTests):
"""
Tests for recursive locks.
"""
def test_reacquire(self):
lock = self.locktype()
lock.acquire()
lock.acquire()
lock.release()
lock.acquire()
lock.release()
lock.release()
def test_release_unacquired(self):
# Cannot release an unacquired lock
lock = self.locktype()
self.assertRaises(RuntimeError, lock.release)
lock.acquire()
lock.acquire()
lock.release()
lock.acquire()
lock.release()
lock.release()
self.assertRaises(RuntimeError, lock.release)
def test_release_save_unacquired(self):
# Cannot _release_save an unacquired lock
lock = self.locktype()
self.assertRaises(RuntimeError, lock._release_save)
lock.acquire()
lock.acquire()
lock.release()
lock.acquire()
lock.release()
lock.release()
self.assertRaises(RuntimeError, lock._release_save)
def test_different_thread(self):
# Cannot release from a different thread
lock = self.locktype()
def f():
lock.acquire()
b = Bunch(f, 1, True)
try:
self.assertRaises(RuntimeError, lock.release)
finally:
b.do_finish()
b.wait_for_finished()
def test__is_owned(self):
lock = self.locktype()
self.assertFalse(lock._is_owned())
lock.acquire()
self.assertTrue(lock._is_owned())
lock.acquire()
self.assertTrue(lock._is_owned())
result = []
def f():
result.append(lock._is_owned())
Bunch(f, 1).wait_for_finished()
self.assertFalse(result[0])
lock.release()
self.assertTrue(lock._is_owned())
lock.release()
self.assertFalse(lock._is_owned())
class EventTests(BaseTestCase):
"""
Tests for Event objects.
"""
def test_is_set(self):
evt = self.eventtype()
self.assertFalse(evt.is_set())
evt.set()
self.assertTrue(evt.is_set())
evt.set()
self.assertTrue(evt.is_set())
evt.clear()
self.assertFalse(evt.is_set())
evt.clear()
self.assertFalse(evt.is_set())
def _check_notify(self, evt):
# All threads get notified
N = 5
results1 = []
results2 = []
def f():
results1.append(evt.wait())
results2.append(evt.wait())
b = Bunch(f, N)
b.wait_for_started()
_wait()
self.assertEqual(len(results1), 0)
evt.set()
b.wait_for_finished()
self.assertEqual(results1, [True] * N)
self.assertEqual(results2, [True] * N)
def test_notify(self):
evt = self.eventtype()
self._check_notify(evt)
# Another time, after an explicit clear()
evt.set()
evt.clear()
self._check_notify(evt)
def test_timeout(self):
evt = self.eventtype()
results1 = []
results2 = []
N = 5
def f():
results1.append(evt.wait(0.0))
t1 = time.time()
r = evt.wait(0.5)
t2 = time.time()
results2.append((r, t2 - t1))
Bunch(f, N).wait_for_finished()
self.assertEqual(results1, [False] * N)
for r, dt in results2:
self.assertFalse(r)
self.assertTimeout(dt, 0.5)
# The event is set
results1 = []
results2 = []
evt.set()
Bunch(f, N).wait_for_finished()
self.assertEqual(results1, [True] * N)
for r, dt in results2:
self.assertTrue(r)
def test_set_and_clear(self):
# Issue #13502: check that wait() returns true even when the event is
# cleared before the waiting thread is woken up.
evt = self.eventtype()
results = []
timeout = 0.250
N = 5
def f():
results.append(evt.wait(timeout * 4))
b = Bunch(f, N)
b.wait_for_started()
time.sleep(timeout)
evt.set()
evt.clear()
b.wait_for_finished()
self.assertEqual(results, [True] * N)
def test_reset_internal_locks(self):
# ensure that condition is still using a Lock after reset
evt = self.eventtype()
with evt._cond:
self.assertFalse(evt._cond.acquire(False))
evt._reset_internal_locks()
with evt._cond:
self.assertFalse(evt._cond.acquire(False))
class ConditionTests(BaseTestCase):
"""
Tests for condition variables.
"""
def test_acquire(self):
cond = self.condtype()
# Be default we have an RLock: the condition can be acquired multiple
# times.
cond.acquire()
cond.acquire()
cond.release()
cond.release()
lock = threading.Lock()
cond = self.condtype(lock)
cond.acquire()
self.assertFalse(lock.acquire(False))
cond.release()
self.assertTrue(lock.acquire(False))
self.assertFalse(cond.acquire(False))
lock.release()
with cond:
self.assertFalse(lock.acquire(False))
def test_unacquired_wait(self):
cond = self.condtype()
self.assertRaises(RuntimeError, cond.wait)
def test_unacquired_notify(self):
cond = self.condtype()
self.assertRaises(RuntimeError, cond.notify)
def _check_notify(self, cond):
# Note that this test is sensitive to timing. If the worker threads
# don't execute in a timely fashion, the main thread may think they
# are further along then they are. The main thread therefore issues
# _wait() statements to try to make sure that it doesn't race ahead
# of the workers.
# Secondly, this test assumes that condition variables are not subject
# to spurious wakeups. The absence of spurious wakeups is an implementation
# detail of Condition Cariables in current CPython, but in general, not
# a guaranteed property of condition variables as a programming
# construct. In particular, it is possible that this can no longer
# be conveniently guaranteed should their implementation ever change.
N = 5
ready = []
results1 = []
results2 = []
phase_num = 0
def f():
cond.acquire()
ready.append(phase_num)
result = cond.wait()
cond.release()
results1.append((result, phase_num))
cond.acquire()
ready.append(phase_num)
result = cond.wait()
cond.release()
results2.append((result, phase_num))
b = Bunch(f, N)
b.wait_for_started()
# first wait, to ensure all workers settle into cond.wait() before
# we continue. See issues #8799 and #30727.
while len(ready) < 5:
_wait()
ready.clear()
self.assertEqual(results1, [])
# Notify 3 threads at first
cond.acquire()
cond.notify(3)
_wait()
phase_num = 1
cond.release()
while len(results1) < 3:
_wait()
self.assertEqual(results1, [(True, 1)] * 3)
self.assertEqual(results2, [])
# make sure all awaken workers settle into cond.wait()
while len(ready) < 3:
_wait()
# Notify 5 threads: they might be in their first or second wait
cond.acquire()
cond.notify(5)
_wait()
phase_num = 2
cond.release()
while len(results1) + len(results2) < 8:
_wait()
self.assertEqual(results1, [(True, 1)] * 3 + [(True, 2)] * 2)
self.assertEqual(results2, [(True, 2)] * 3)
# make sure all workers settle into cond.wait()
while len(ready) < 5:
_wait()
# Notify all threads: they are all in their second wait
cond.acquire()
cond.notify_all()
_wait()
phase_num = 3
cond.release()
while len(results2) < 5:
_wait()
self.assertEqual(results1, [(True, 1)] * 3 + [(True,2)] * 2)
self.assertEqual(results2, [(True, 2)] * 3 + [(True, 3)] * 2)
b.wait_for_finished()
def test_notify(self):
cond = self.condtype()
self._check_notify(cond)
# A second time, to check internal state is still ok.
self._check_notify(cond)
def test_timeout(self):
cond = self.condtype()
results = []
N = 5
def f():
cond.acquire()
t1 = time.time()
result = cond.wait(0.5)
t2 = time.time()
cond.release()
results.append((t2 - t1, result))
Bunch(f, N).wait_for_finished()
self.assertEqual(len(results), N)
for dt, result in results:
self.assertTimeout(dt, 0.5)
# Note that conceptually (that"s the condition variable protocol)
# a wait() may succeed even if no one notifies us and before any
# timeout occurs. Spurious wakeups can occur.
# This makes it hard to verify the result value.
# In practice, this implementation has no spurious wakeups.
self.assertFalse(result)
def test_waitfor(self):
cond = self.condtype()
state = 0
def f():
with cond:
result = cond.wait_for(lambda : state==4)
self.assertTrue(result)
self.assertEqual(state, 4)
b = Bunch(f, 1)
b.wait_for_started()
for i in range(4):
time.sleep(0.01)
with cond:
state += 1
cond.notify()
b.wait_for_finished()
def test_waitfor_timeout(self):
cond = self.condtype()
state = 0
success = []
def f():
with cond:
dt = time.time()
result = cond.wait_for(lambda : state==4, timeout=0.1)
dt = time.time() - dt
self.assertFalse(result)
self.assertTimeout(dt, 0.1)
success.append(None)
b = Bunch(f, 1)
b.wait_for_started()
# Only increment 3 times, so state == 4 is never reached.
for i in range(3):
time.sleep(0.01)
with cond:
state += 1
cond.notify()
b.wait_for_finished()
self.assertEqual(len(success), 1)
class BaseSemaphoreTests(BaseTestCase):
"""
Common tests for {bounded, unbounded} semaphore objects.
"""
def test_constructor(self):
self.assertRaises(ValueError, self.semtype, value = -1)
self.assertRaises(ValueError, self.semtype, value = -sys.maxsize)
def test_acquire(self):
sem = self.semtype(1)
sem.acquire()
sem.release()
sem = self.semtype(2)
sem.acquire()
sem.acquire()
sem.release()
sem.release()
def test_acquire_destroy(self):
sem = self.semtype()
sem.acquire()
del sem
def test_acquire_contended(self):
sem = self.semtype(7)
sem.acquire()
N = 10
sem_results = []
results1 = []
results2 = []
phase_num = 0
def f():
sem_results.append(sem.acquire())
results1.append(phase_num)
sem_results.append(sem.acquire())
results2.append(phase_num)
b = Bunch(f, 10)
b.wait_for_started()
while len(results1) + len(results2) < 6:
_wait()
self.assertEqual(results1 + results2, [0] * 6)
phase_num = 1
for i in range(7):
sem.release()
while len(results1) + len(results2) < 13:
_wait()
self.assertEqual(sorted(results1 + results2), [0] * 6 + [1] * 7)
phase_num = 2
for i in range(6):
sem.release()
while len(results1) + len(results2) < 19:
_wait()
self.assertEqual(sorted(results1 + results2), [0] * 6 + [1] * 7 + [2] * 6)
# The semaphore is still locked
self.assertFalse(sem.acquire(False))
# Final release, to let the last thread finish
sem.release()
b.wait_for_finished()
self.assertEqual(sem_results, [True] * (6 + 7 + 6 + 1))
def test_try_acquire(self):
sem = self.semtype(2)
self.assertTrue(sem.acquire(False))
self.assertTrue(sem.acquire(False))
self.assertFalse(sem.acquire(False))
sem.release()
self.assertTrue(sem.acquire(False))
def test_try_acquire_contended(self):
sem = self.semtype(4)
sem.acquire()
results = []
def f():
results.append(sem.acquire(False))
results.append(sem.acquire(False))
Bunch(f, 5).wait_for_finished()
# There can be a thread switch between acquiring the semaphore and
# appending the result, therefore results will not necessarily be
# ordered.
self.assertEqual(sorted(results), [False] * 7 + [True] * 3 )
def test_acquire_timeout(self):
sem = self.semtype(2)
self.assertRaises(ValueError, sem.acquire, False, timeout=1.0)
self.assertTrue(sem.acquire(timeout=0.005))
self.assertTrue(sem.acquire(timeout=0.005))
self.assertFalse(sem.acquire(timeout=0.005))
sem.release()
self.assertTrue(sem.acquire(timeout=0.005))
t = time.time()
self.assertFalse(sem.acquire(timeout=0.5))
dt = time.time() - t
self.assertTimeout(dt, 0.5)
def test_default_value(self):
# The default initial value is 1.
sem = self.semtype()
sem.acquire()
def f():
sem.acquire()
sem.release()
b = Bunch(f, 1)
b.wait_for_started()
_wait()
self.assertFalse(b.finished)
sem.release()
b.wait_for_finished()
def test_with(self):
sem = self.semtype(2)
def _with(err=None):
with sem:
self.assertTrue(sem.acquire(False))
sem.release()
with sem:
self.assertFalse(sem.acquire(False))
if err:
raise err
_with()
self.assertTrue(sem.acquire(False))
sem.release()
self.assertRaises(TypeError, _with, TypeError)
self.assertTrue(sem.acquire(False))
sem.release()
class SemaphoreTests(BaseSemaphoreTests):
"""
Tests for unbounded semaphores.
"""
def test_release_unacquired(self):
# Unbounded releases are allowed and increment the semaphore's value
sem = self.semtype(1)
sem.release()
sem.acquire()
sem.acquire()
sem.release()
class BoundedSemaphoreTests(BaseSemaphoreTests):
"""
Tests for bounded semaphores.
"""
def test_release_unacquired(self):
# Cannot go past the initial value
sem = self.semtype()
self.assertRaises(ValueError, sem.release)
sem.acquire()
sem.release()
self.assertRaises(ValueError, sem.release)
class BarrierTests(BaseTestCase):
"""
Tests for Barrier objects.
"""
N = 5
defaultTimeout = 2.0
def setUp(self):
self.barrier = self.barriertype(self.N, timeout=self.defaultTimeout)
def tearDown(self):
self.barrier.abort()
def run_threads(self, f):
b = Bunch(f, self.N-1)
f()
b.wait_for_finished()
def multipass(self, results, n):
m = self.barrier.parties
self.assertEqual(m, self.N)
for i in range(n):
results[0].append(True)
self.assertEqual(len(results[1]), i * m)
self.barrier.wait()
results[1].append(True)
self.assertEqual(len(results[0]), (i + 1) * m)
self.barrier.wait()
self.assertEqual(self.barrier.n_waiting, 0)
self.assertFalse(self.barrier.broken)
def test_barrier(self, passes=1):
"""
Test that a barrier is passed in lockstep
"""
results = [[],[]]
def f():
self.multipass(results, passes)
self.run_threads(f)
def test_barrier_10(self):
"""
Test that a barrier works for 10 consecutive runs
"""
return self.test_barrier(10)
def test_wait_return(self):
"""
test the return value from barrier.wait
"""
results = []
def f():
r = self.barrier.wait()
results.append(r)
self.run_threads(f)
self.assertEqual(sum(results), sum(range(self.N)))
def test_action(self):
"""
Test the 'action' callback
"""
results = []
def action():
results.append(True)
barrier = self.barriertype(self.N, action)
def f():
barrier.wait()
self.assertEqual(len(results), 1)
self.run_threads(f)
def test_abort(self):
"""
Test that an abort will put the barrier in a broken state
"""
results1 = []
results2 = []
def f():
try:
i = self.barrier.wait()
if i == self.N//2:
raise RuntimeError
self.barrier.wait()
results1.append(True)
except threading.BrokenBarrierError:
results2.append(True)
except RuntimeError:
self.barrier.abort()
pass
self.run_threads(f)
self.assertEqual(len(results1), 0)
self.assertEqual(len(results2), self.N-1)
self.assertTrue(self.barrier.broken)
def test_reset(self):
"""
Test that a 'reset' on a barrier frees the waiting threads
"""
results1 = []
results2 = []
results3 = []
def f():
i = self.barrier.wait()
if i == self.N//2:
# Wait until the other threads are all in the barrier.
while self.barrier.n_waiting < self.N-1:
time.sleep(0.001)
self.barrier.reset()
else:
try:
self.barrier.wait()
results1.append(True)
except threading.BrokenBarrierError:
results2.append(True)
# Now, pass the barrier again
self.barrier.wait()
results3.append(True)
self.run_threads(f)
self.assertEqual(len(results1), 0)
self.assertEqual(len(results2), self.N-1)
self.assertEqual(len(results3), self.N)
def test_abort_and_reset(self):
"""
Test that a barrier can be reset after being broken.
"""
results1 = []
results2 = []
results3 = []
barrier2 = self.barriertype(self.N)
def f():
try:
i = self.barrier.wait()
if i == self.N//2:
raise RuntimeError
self.barrier.wait()
results1.append(True)
except threading.BrokenBarrierError:
results2.append(True)
except RuntimeError:
self.barrier.abort()
pass
# Synchronize and reset the barrier. Must synchronize first so
# that everyone has left it when we reset, and after so that no
# one enters it before the reset.
if barrier2.wait() == self.N//2:
self.barrier.reset()
barrier2.wait()
self.barrier.wait()
results3.append(True)
self.run_threads(f)
self.assertEqual(len(results1), 0)
self.assertEqual(len(results2), self.N-1)
self.assertEqual(len(results3), self.N)
def test_timeout(self):
"""
Test wait(timeout)
"""
def f():
i = self.barrier.wait()
if i == self.N // 2:
# One thread is late!
time.sleep(1.0)
# Default timeout is 2.0, so this is shorter.
self.assertRaises(threading.BrokenBarrierError,
self.barrier.wait, 0.5)
self.run_threads(f)
def test_default_timeout(self):
"""
Test the barrier's default timeout
"""
# create a barrier with a low default timeout
barrier = self.barriertype(self.N, timeout=0.3)
def f():
i = barrier.wait()
if i == self.N // 2:
# One thread is later than the default timeout of 0.3s.
time.sleep(1.0)
self.assertRaises(threading.BrokenBarrierError, barrier.wait)
self.run_threads(f)
def test_single_thread(self):
b = self.barriertype(1)
b.wait()
b.wait()
| 28,878 | 950 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_baseexception.py | import unittest
import builtins
import os
from platform import system as platform_system
class ExceptionClassTests(unittest.TestCase):
"""Tests for anything relating to exception objects themselves (e.g.,
inheritance hierarchy)"""
def test_builtins_new_style(self):
self.assertTrue(issubclass(Exception, object))
def verify_instance_interface(self, ins):
for attr in ("args", "__str__", "__repr__"):
self.assertTrue(hasattr(ins, attr),
"%s missing %s attribute" %
(ins.__class__.__name__, attr))
def test_inheritance(self):
# Make sure the inheritance hierarchy matches the documentation
exc_set = set()
for object_ in builtins.__dict__.values():
try:
if issubclass(object_, BaseException):
exc_set.add(object_.__name__)
except TypeError:
pass
inheritance_tree = open(os.path.join(os.path.split(__file__)[0],
'exception_hierarchy.txt'))
try:
superclass_name = inheritance_tree.readline().rstrip()
try:
last_exc = getattr(builtins, superclass_name)
except AttributeError:
self.fail("base class %s not a built-in" % superclass_name)
self.assertIn(superclass_name, exc_set,
'%s not found' % superclass_name)
exc_set.discard(superclass_name)
superclasses = [] # Loop will insert base exception
last_depth = 0
for exc_line in inheritance_tree:
exc_line = exc_line.rstrip()
depth = exc_line.rindex('-')
exc_name = exc_line[depth+2:] # Slice past space
if '(' in exc_name:
paren_index = exc_name.index('(')
platform_name = exc_name[paren_index+1:-1]
exc_name = exc_name[:paren_index-1] # Slice off space
if platform_system() != platform_name:
exc_set.discard(exc_name)
continue
if '[' in exc_name:
left_bracket = exc_name.index('[')
exc_name = exc_name[:left_bracket-1] # cover space
try:
exc = getattr(builtins, exc_name)
except AttributeError:
self.fail("%s not a built-in exception" % exc_name)
if last_depth < depth:
superclasses.append((last_depth, last_exc))
elif last_depth > depth:
while superclasses[-1][0] >= depth:
superclasses.pop()
self.assertTrue(issubclass(exc, superclasses[-1][1]),
"%s is not a subclass of %s" % (exc.__name__,
superclasses[-1][1].__name__))
try: # Some exceptions require arguments; just skip them
self.verify_instance_interface(exc())
except TypeError:
pass
self.assertIn(exc_name, exc_set)
exc_set.discard(exc_name)
last_exc = exc
last_depth = depth
finally:
inheritance_tree.close()
self.assertEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
interface_tests = ("length", "args", "str", "repr")
def interface_test_driver(self, results):
for test_name, (given, expected) in zip(self.interface_tests, results):
self.assertEqual(given, expected, "%s: %s != %s" % (test_name,
given, expected))
def test_interface_single_arg(self):
# Make sure interface works properly when given a single argument
arg = "spam"
exc = Exception(arg)
results = ([len(exc.args), 1], [exc.args[0], arg],
[str(exc), str(arg)],
[repr(exc), exc.__class__.__name__ + repr(exc.args)])
self.interface_test_driver(results)
def test_interface_multi_arg(self):
# Make sure interface correct when multiple arguments given
arg_count = 3
args = tuple(range(arg_count))
exc = Exception(*args)
results = ([len(exc.args), arg_count], [exc.args, args],
[str(exc), str(args)],
[repr(exc), exc.__class__.__name__ + repr(exc.args)])
self.interface_test_driver(results)
def test_interface_no_arg(self):
# Make sure that with no args that interface is correct
exc = Exception()
results = ([len(exc.args), 0], [exc.args, tuple()],
[str(exc), ''],
[repr(exc), exc.__class__.__name__ + '()'])
self.interface_test_driver(results)
class UsageTests(unittest.TestCase):
"""Test usage of exceptions"""
def raise_fails(self, object_):
"""Make sure that raising 'object_' triggers a TypeError."""
try:
raise object_
except TypeError:
return # What is expected.
self.fail("TypeError expected for raising %s" % type(object_))
def catch_fails(self, object_):
"""Catching 'object_' should raise a TypeError."""
try:
try:
raise Exception
except object_:
pass
except TypeError:
pass
except Exception:
self.fail("TypeError expected when catching %s" % type(object_))
try:
try:
raise Exception
except (object_,):
pass
except TypeError:
return
except Exception:
self.fail("TypeError expected when catching %s as specified in a "
"tuple" % type(object_))
def test_raise_new_style_non_exception(self):
# You cannot raise a new-style class that does not inherit from
# BaseException; the ability was not possible until BaseException's
# introduction so no need to support new-style objects that do not
# inherit from it.
class NewStyleClass(object):
pass
self.raise_fails(NewStyleClass)
self.raise_fails(NewStyleClass())
def test_raise_string(self):
# Raising a string raises TypeError.
self.raise_fails("spam")
def test_catch_non_BaseException(self):
# Trying to catch an object that does not inherit from BaseException
# is not allowed.
class NonBaseException(object):
pass
self.catch_fails(NonBaseException)
self.catch_fails(NonBaseException())
def test_catch_BaseException_instance(self):
# Catching an instance of a BaseException subclass won't work.
self.catch_fails(BaseException())
def test_catch_string(self):
# Catching a string is bad.
self.catch_fails("spam")
if __name__ == '__main__':
unittest.main()
| 7,028 | 184 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/badsyntax_future3.py | """This is a test"""
from __future__ import nested_scopes
from __future__ import rested_snopes
def f(x):
def g(y):
return x + y
return g
result = f(2)(4)
| 172 | 11 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_userlist.py | # Check every path through every method of UserList
from collections import UserList
from test import list_tests
import unittest
class UserListTest(list_tests.CommonTest):
type2test = UserList
def test_getslice(self):
super().test_getslice()
l = [0, 1, 2, 3, 4]
u = self.type2test(l)
for i in range(-3, 6):
self.assertEqual(u[:i], l[:i])
self.assertEqual(u[i:], l[i:])
for j in range(-3, 6):
self.assertEqual(u[i:j], l[i:j])
def test_add_specials(self):
u = UserList("spam")
u2 = u + "eggs"
self.assertEqual(u2, list("spameggs"))
def test_radd_specials(self):
u = UserList("eggs")
u2 = "spam" + u
self.assertEqual(u2, list("spameggs"))
u2 = u.__radd__(UserList("spam"))
self.assertEqual(u2, list("spameggs"))
def test_iadd(self):
super().test_iadd()
u = [0, 1]
u += UserList([0, 1])
self.assertEqual(u, [0, 1, 0, 1])
def test_mixedcmp(self):
u = self.type2test([0, 1])
self.assertEqual(u, [0, 1])
self.assertNotEqual(u, [0])
self.assertNotEqual(u, [0, 2])
def test_mixedadd(self):
u = self.type2test([0, 1])
self.assertEqual(u + [], u)
self.assertEqual(u + [2], [0, 1, 2])
def test_getitemoverwriteiter(self):
# Verify that __getitem__ overrides *are* recognized by __iter__
class T(self.type2test):
def __getitem__(self, key):
return str(key) + '!!!'
self.assertEqual(next(iter(T((1,2)))), "0!!!")
def test_userlist_copy(self):
u = self.type2test([6, 8, 1, 9, 1])
v = u.copy()
self.assertEqual(u, v)
self.assertEqual(type(u), type(v))
if __name__ == "__main__":
unittest.main()
| 1,850 | 64 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_ossaudiodev.py | from test import support
support.requires('audio')
from test.support import findfile
ossaudiodev = support.import_module('ossaudiodev')
import errno
import sys
import sunau
import time
import audioop
import unittest
# Arggh, AFMT_S16_NE not defined on all platforms -- seems to be a
# fairly recent addition to OSS.
try:
from ossaudiodev import AFMT_S16_NE
except ImportError:
if sys.byteorder == "little":
AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
else:
AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
def read_sound_file(path):
with open(path, 'rb') as fp:
au = sunau.open(fp)
rate = au.getframerate()
nchannels = au.getnchannels()
encoding = au._encoding
fp.seek(0)
data = fp.read()
if encoding != sunau.AUDIO_FILE_ENCODING_MULAW_8:
raise RuntimeError("Expect .au file with 8-bit mu-law samples")
# Convert the data to 16-bit signed.
data = audioop.ulaw2lin(data, 2)
return (data, rate, 16, nchannels)
class OSSAudioDevTests(unittest.TestCase):
def play_sound_file(self, data, rate, ssize, nchannels):
try:
dsp = ossaudiodev.open('w')
except OSError as msg:
if msg.args[0] in (errno.EACCES, errno.ENOENT,
errno.ENODEV, errno.EBUSY):
raise unittest.SkipTest(msg)
raise
# at least check that these methods can be invoked
dsp.bufsize()
dsp.obufcount()
dsp.obuffree()
dsp.getptr()
dsp.fileno()
# Make sure the read-only attributes work.
self.assertFalse(dsp.closed)
self.assertEqual(dsp.name, "/dev/dsp")
self.assertEqual(dsp.mode, "w", "bad dsp.mode: %r" % dsp.mode)
# And make sure they're really read-only.
for attr in ('closed', 'name', 'mode'):
try:
setattr(dsp, attr, 42)
except (TypeError, AttributeError):
pass
else:
self.fail("dsp.%s not read-only" % attr)
# Compute expected running time of sound sample (in seconds).
expected_time = float(len(data)) / (ssize/8) / nchannels / rate
# set parameters based on .au file headers
dsp.setparameters(AFMT_S16_NE, nchannels, rate)
self.assertTrue(abs(expected_time - 3.51) < 1e-2, expected_time)
t1 = time.time()
dsp.write(data)
dsp.close()
t2 = time.time()
elapsed_time = t2 - t1
percent_diff = (abs(elapsed_time - expected_time) / expected_time) * 100
self.assertTrue(percent_diff <= 10.0,
"elapsed time (%s) > 10%% off of expected time (%s)" %
(elapsed_time, expected_time))
def set_parameters(self, dsp):
# Two configurations for testing:
# config1 (8-bit, mono, 8 kHz) should work on even the most
# ancient and crufty sound card, but maybe not on special-
# purpose high-end hardware
# config2 (16-bit, stereo, 44.1kHz) should work on all but the
# most ancient and crufty hardware
config1 = (ossaudiodev.AFMT_U8, 1, 8000)
config2 = (AFMT_S16_NE, 2, 44100)
for config in [config1, config2]:
(fmt, channels, rate) = config
if (dsp.setfmt(fmt) == fmt and
dsp.channels(channels) == channels and
dsp.speed(rate) == rate):
break
else:
raise RuntimeError("unable to set audio sampling parameters: "
"you must have really weird audio hardware")
# setparameters() should be able to set this configuration in
# either strict or non-strict mode.
result = dsp.setparameters(fmt, channels, rate, False)
self.assertEqual(result, (fmt, channels, rate),
"setparameters%r: returned %r" % (config, result))
result = dsp.setparameters(fmt, channels, rate, True)
self.assertEqual(result, (fmt, channels, rate),
"setparameters%r: returned %r" % (config, result))
def set_bad_parameters(self, dsp):
# Now try some configurations that are presumably bogus: eg. 300
# channels currently exceeds even Hollywood's ambitions, and
# negative sampling rate is utter nonsense. setparameters() should
# accept these in non-strict mode, returning something other than
# was requested, but should barf in strict mode.
fmt = AFMT_S16_NE
rate = 44100
channels = 2
for config in [(fmt, 300, rate), # ridiculous nchannels
(fmt, -5, rate), # impossible nchannels
(fmt, channels, -50), # impossible rate
]:
(fmt, channels, rate) = config
result = dsp.setparameters(fmt, channels, rate, False)
self.assertNotEqual(result, config,
"unexpectedly got requested configuration")
try:
result = dsp.setparameters(fmt, channels, rate, True)
except ossaudiodev.OSSAudioError as err:
pass
else:
self.fail("expected OSSAudioError")
def test_playback(self):
sound_info = read_sound_file(findfile('audiotest.au'))
self.play_sound_file(*sound_info)
def test_set_parameters(self):
dsp = ossaudiodev.open("w")
try:
self.set_parameters(dsp)
# Disabled because it fails under Linux 2.6 with ALSA's OSS
# emulation layer.
#self.set_bad_parameters(dsp)
finally:
dsp.close()
self.assertTrue(dsp.closed)
def test_mixer_methods(self):
# Issue #8139: ossaudiodev didn't initialize its types properly,
# therefore some methods were unavailable.
with ossaudiodev.openmixer() as mixer:
self.assertGreaterEqual(mixer.fileno(), 0)
def test_with(self):
with ossaudiodev.open('w') as dsp:
pass
self.assertTrue(dsp.closed)
def test_on_closed(self):
dsp = ossaudiodev.open('w')
dsp.close()
self.assertRaises(ValueError, dsp.fileno)
self.assertRaises(ValueError, dsp.read, 1)
self.assertRaises(ValueError, dsp.write, b'x')
self.assertRaises(ValueError, dsp.writeall, b'x')
self.assertRaises(ValueError, dsp.bufsize)
self.assertRaises(ValueError, dsp.obufcount)
self.assertRaises(ValueError, dsp.obufcount)
self.assertRaises(ValueError, dsp.obuffree)
self.assertRaises(ValueError, dsp.getptr)
mixer = ossaudiodev.openmixer()
mixer.close()
self.assertRaises(ValueError, mixer.fileno)
def test_main():
try:
dsp = ossaudiodev.open('w')
except (ossaudiodev.error, OSError) as msg:
if msg.args[0] in (errno.EACCES, errno.ENOENT,
errno.ENODEV, errno.EBUSY):
raise unittest.SkipTest(msg)
raise
dsp.close()
support.run_unittest(__name__)
if __name__ == "__main__":
test_main()
| 7,216 | 203 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_charmapcodec.py | """ Python character mapping codec test
This uses the test codec in testcodec.py and thus also tests the
encodings package lookup scheme.
Written by Marc-Andre Lemburg ([email protected]).
(c) Copyright 2000 Guido van Rossum.
"""#"
import unittest
import codecs
# Register a search function which knows about our codec
def codec_search_function(encoding):
if encoding == 'testcodec':
from test import testcodec
return tuple(testcodec.getregentry())
return None
codecs.register(codec_search_function)
# test codec's name (see test/testcodec.py)
codecname = 'testcodec'
class CharmapCodecTest(unittest.TestCase):
def test_constructorx(self):
self.assertEqual(str(b'abc', codecname), 'abc')
self.assertEqual(str(b'xdef', codecname), 'abcdef')
self.assertEqual(str(b'defx', codecname), 'defabc')
self.assertEqual(str(b'dxf', codecname), 'dabcf')
self.assertEqual(str(b'dxfx', codecname), 'dabcfabc')
def test_encodex(self):
self.assertEqual('abc'.encode(codecname), b'abc')
self.assertEqual('xdef'.encode(codecname), b'abcdef')
self.assertEqual('defx'.encode(codecname), b'defabc')
self.assertEqual('dxf'.encode(codecname), b'dabcf')
self.assertEqual('dxfx'.encode(codecname), b'dabcfabc')
def test_constructory(self):
self.assertEqual(str(b'ydef', codecname), 'def')
self.assertEqual(str(b'defy', codecname), 'def')
self.assertEqual(str(b'dyf', codecname), 'df')
self.assertEqual(str(b'dyfy', codecname), 'df')
def test_maptoundefined(self):
self.assertRaises(UnicodeError, str, b'abc\001', codecname)
if __name__ == "__main__":
unittest.main()
| 1,718 | 54 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_glob.py | import glob
import os
import shutil
import sys
import unittest
from test.support import (TESTFN, skip_unless_symlink,
can_symlink, create_empty_file, change_cwd)
class GlobTests(unittest.TestCase):
def norm(self, *parts):
return os.path.normpath(os.path.join(self.tempdir, *parts))
def joins(self, *tuples):
return [os.path.join(self.tempdir, *parts) for parts in tuples]
def mktemp(self, *parts):
filename = self.norm(*parts)
base, file = os.path.split(filename)
if not os.path.exists(base):
os.makedirs(base)
create_empty_file(filename)
def setUp(self):
self.tempdir = TESTFN + "_dir"
self.mktemp('a', 'D')
self.mktemp('aab', 'F')
self.mktemp('.aa', 'G')
self.mktemp('.bb', 'H')
self.mktemp('aaa', 'zzzF')
self.mktemp('ZZZ')
self.mktemp('EF')
self.mktemp('a', 'bcd', 'EF')
self.mktemp('a', 'bcd', 'efg', 'ha')
if can_symlink():
os.symlink(self.norm('broken'), self.norm('sym1'))
os.symlink('broken', self.norm('sym2'))
os.symlink(os.path.join('a', 'bcd'), self.norm('sym3'))
def tearDown(self):
shutil.rmtree(self.tempdir)
def glob(self, *parts, **kwargs):
if len(parts) == 1:
pattern = parts[0]
else:
pattern = os.path.join(*parts)
p = os.path.join(self.tempdir, pattern)
res = glob.glob(p, **kwargs)
self.assertCountEqual(glob.iglob(p, **kwargs), res)
bres = [os.fsencode(x) for x in res]
self.assertCountEqual(glob.glob(os.fsencode(p), **kwargs), bres)
self.assertCountEqual(glob.iglob(os.fsencode(p), **kwargs), bres)
return res
def assertSequencesEqual_noorder(self, l1, l2):
l1 = list(l1)
l2 = list(l2)
self.assertEqual(set(l1), set(l2))
self.assertEqual(sorted(l1), sorted(l2))
def test_glob_literal(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('a'), [self.norm('a')])
eq(self.glob('a', 'D'), [self.norm('a', 'D')])
eq(self.glob('aab'), [self.norm('aab')])
eq(self.glob('zymurgy'), [])
res = glob.glob('*')
self.assertEqual({type(r) for r in res}, {str})
res = glob.glob(os.path.join(os.curdir, '*'))
self.assertEqual({type(r) for r in res}, {str})
res = glob.glob(b'*')
self.assertEqual({type(r) for r in res}, {bytes})
res = glob.glob(os.path.join(os.fsencode(os.curdir), b'*'))
self.assertEqual({type(r) for r in res}, {bytes})
def test_glob_one_directory(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('a*'), map(self.norm, ['a', 'aab', 'aaa']))
eq(self.glob('*a'), map(self.norm, ['a', 'aaa']))
eq(self.glob('.*'), map(self.norm, ['.aa', '.bb']))
eq(self.glob('?aa'), map(self.norm, ['aaa']))
eq(self.glob('aa?'), map(self.norm, ['aaa', 'aab']))
eq(self.glob('aa[ab]'), map(self.norm, ['aaa', 'aab']))
eq(self.glob('*q'), [])
def test_glob_nested_directory(self):
eq = self.assertSequencesEqual_noorder
if os.path.normcase("abCD") == "abCD":
# case-sensitive filesystem
eq(self.glob('a', 'bcd', 'E*'), [self.norm('a', 'bcd', 'EF')])
else:
# case insensitive filesystem
eq(self.glob('a', 'bcd', 'E*'), [self.norm('a', 'bcd', 'EF'),
self.norm('a', 'bcd', 'efg')])
eq(self.glob('a', 'bcd', '*g'), [self.norm('a', 'bcd', 'efg')])
def test_glob_directory_names(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('*', 'D'), [self.norm('a', 'D')])
eq(self.glob('*', '*a'), [])
eq(self.glob('a', '*', '*', '*a'),
[self.norm('a', 'bcd', 'efg', 'ha')])
eq(self.glob('?a?', '*F'), [self.norm('aaa', 'zzzF'),
self.norm('aab', 'F')])
def test_glob_directory_with_trailing_slash(self):
# Patterns ending with a slash shouldn't match non-dirs
res = glob.glob(self.norm('Z*Z') + os.sep)
self.assertEqual(res, [])
res = glob.glob(self.norm('ZZZ') + os.sep)
self.assertEqual(res, [])
# When there is a wildcard pattern which ends with os.sep, glob()
# doesn't blow up.
res = glob.glob(self.norm('aa*') + os.sep)
self.assertEqual(len(res), 2)
# either of these results is reasonable
self.assertIn(set(res), [
{self.norm('aaa'), self.norm('aab')},
{self.norm('aaa') + os.sep, self.norm('aab') + os.sep},
])
def test_glob_bytes_directory_with_trailing_slash(self):
# Same as test_glob_directory_with_trailing_slash, but with a
# bytes argument.
res = glob.glob(os.fsencode(self.norm('Z*Z') + os.sep))
self.assertEqual(res, [])
res = glob.glob(os.fsencode(self.norm('ZZZ') + os.sep))
self.assertEqual(res, [])
res = glob.glob(os.fsencode(self.norm('aa*') + os.sep))
self.assertEqual(len(res), 2)
# either of these results is reasonable
self.assertIn(set(res), [
{os.fsencode(self.norm('aaa')),
os.fsencode(self.norm('aab'))},
{os.fsencode(self.norm('aaa') + os.sep),
os.fsencode(self.norm('aab') + os.sep)},
])
@skip_unless_symlink
def test_glob_symlinks(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('sym3'), [self.norm('sym3')])
eq(self.glob('sym3', '*'), [self.norm('sym3', 'EF'),
self.norm('sym3', 'efg')])
self.assertIn(self.glob('sym3' + os.sep),
[[self.norm('sym3')], [self.norm('sym3') + os.sep]])
eq(self.glob('*', '*F'),
[self.norm('aaa', 'zzzF'),
self.norm('aab', 'F'), self.norm('sym3', 'EF')])
@skip_unless_symlink
def test_glob_broken_symlinks(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('sym*'), [self.norm('sym1'), self.norm('sym2'),
self.norm('sym3')])
eq(self.glob('sym1'), [self.norm('sym1')])
eq(self.glob('sym2'), [self.norm('sym2')])
@unittest.skipUnless(sys.platform == "win32", "Win32 specific test")
def test_glob_magic_in_drive(self):
eq = self.assertSequencesEqual_noorder
eq(glob.glob('*:'), [])
eq(glob.glob(b'*:'), [])
eq(glob.glob('?:'), [])
eq(glob.glob(b'?:'), [])
eq(glob.glob('\\\\?\\c:\\'), ['\\\\?\\c:\\'])
eq(glob.glob(b'\\\\?\\c:\\'), [b'\\\\?\\c:\\'])
eq(glob.glob('\\\\*\\*\\'), [])
eq(glob.glob(b'\\\\*\\*\\'), [])
def check_escape(self, arg, expected):
self.assertEqual(glob.escape(arg), expected)
self.assertEqual(glob.escape(os.fsencode(arg)), os.fsencode(expected))
def test_escape(self):
check = self.check_escape
check('abc', 'abc')
check('[', '[[]')
check('?', '[?]')
check('*', '[*]')
check('[[_/*?*/_]]', '[[][[]_/[*][?][*]/_]]')
check('/[[_/*?*/_]]/', '/[[][[]_/[*][?][*]/_]]/')
@unittest.skipUnless(sys.platform == "win32", "Win32 specific test")
def test_escape_windows(self):
check = self.check_escape
check('?:?', '?:[?]')
check('*:*', '*:[*]')
check(r'\\?\c:\?', r'\\?\c:\[?]')
check(r'\\*\*\*', r'\\*\*\[*]')
check('//?/c:/?', '//?/c:/[?]')
check('//*/*/*', '//*/*/[*]')
def rglob(self, *parts, **kwargs):
return self.glob(*parts, recursive=True, **kwargs)
def test_recursive_glob(self):
eq = self.assertSequencesEqual_noorder
full = [('EF',), ('ZZZ',),
('a',), ('a', 'D'),
('a', 'bcd'),
('a', 'bcd', 'EF'),
('a', 'bcd', 'efg'),
('a', 'bcd', 'efg', 'ha'),
('aaa',), ('aaa', 'zzzF'),
('aab',), ('aab', 'F'),
]
if can_symlink():
full += [('sym1',), ('sym2',),
('sym3',),
('sym3', 'EF'),
('sym3', 'efg'),
('sym3', 'efg', 'ha'),
]
eq(self.rglob('**'), self.joins(('',), *full))
eq(self.rglob(os.curdir, '**'),
self.joins((os.curdir, ''), *((os.curdir,) + i for i in full)))
dirs = [('a', ''), ('a', 'bcd', ''), ('a', 'bcd', 'efg', ''),
('aaa', ''), ('aab', '')]
if can_symlink():
dirs += [('sym3', ''), ('sym3', 'efg', '')]
eq(self.rglob('**', ''), self.joins(('',), *dirs))
eq(self.rglob('a', '**'), self.joins(
('a', ''), ('a', 'D'), ('a', 'bcd'), ('a', 'bcd', 'EF'),
('a', 'bcd', 'efg'), ('a', 'bcd', 'efg', 'ha')))
eq(self.rglob('a**'), self.joins(('a',), ('aaa',), ('aab',)))
expect = [('a', 'bcd', 'EF'), ('EF',)]
if can_symlink():
expect += [('sym3', 'EF')]
eq(self.rglob('**', 'EF'), self.joins(*expect))
expect = [('a', 'bcd', 'EF'), ('aaa', 'zzzF'), ('aab', 'F'), ('EF',)]
if can_symlink():
expect += [('sym3', 'EF')]
eq(self.rglob('**', '*F'), self.joins(*expect))
eq(self.rglob('**', '*F', ''), [])
eq(self.rglob('**', 'bcd', '*'), self.joins(
('a', 'bcd', 'EF'), ('a', 'bcd', 'efg')))
eq(self.rglob('a', '**', 'bcd'), self.joins(('a', 'bcd')))
with change_cwd(self.tempdir):
join = os.path.join
eq(glob.glob('**', recursive=True), [join(*i) for i in full])
eq(glob.glob(join('**', ''), recursive=True),
[join(*i) for i in dirs])
eq(glob.glob(join('**', '*'), recursive=True),
[join(*i) for i in full])
eq(glob.glob(join(os.curdir, '**'), recursive=True),
[join(os.curdir, '')] + [join(os.curdir, *i) for i in full])
eq(glob.glob(join(os.curdir, '**', ''), recursive=True),
[join(os.curdir, '')] + [join(os.curdir, *i) for i in dirs])
eq(glob.glob(join(os.curdir, '**', '*'), recursive=True),
[join(os.curdir, *i) for i in full])
eq(glob.glob(join('**','zz*F'), recursive=True),
[join('aaa', 'zzzF')])
eq(glob.glob('**zz*F', recursive=True), [])
expect = [join('a', 'bcd', 'EF'), 'EF']
if can_symlink():
expect += [join('sym3', 'EF')]
eq(glob.glob(join('**', 'EF'), recursive=True), expect)
@skip_unless_symlink
class SymlinkLoopGlobTests(unittest.TestCase):
def test_selflink(self):
tempdir = TESTFN + "_dir"
os.makedirs(tempdir)
self.addCleanup(shutil.rmtree, tempdir)
with change_cwd(tempdir):
os.makedirs('dir')
create_empty_file(os.path.join('dir', 'file'))
os.symlink(os.curdir, os.path.join('dir', 'link'))
results = glob.glob('**', recursive=True)
self.assertEqual(len(results), len(set(results)))
results = set(results)
depth = 0
while results:
path = os.path.join(*(['dir'] + ['link'] * depth))
self.assertIn(path, results)
results.remove(path)
if not results:
break
path = os.path.join(path, 'file')
self.assertIn(path, results)
results.remove(path)
depth += 1
results = glob.glob(os.path.join('**', 'file'), recursive=True)
self.assertEqual(len(results), len(set(results)))
results = set(results)
depth = 0
while results:
path = os.path.join(*(['dir'] + ['link'] * depth + ['file']))
self.assertIn(path, results)
results.remove(path)
depth += 1
results = glob.glob(os.path.join('**', ''), recursive=True)
self.assertEqual(len(results), len(set(results)))
results = set(results)
depth = 0
while results:
path = os.path.join(*(['dir'] + ['link'] * depth + ['']))
self.assertIn(path, results)
results.remove(path)
depth += 1
if __name__ == "__main__":
unittest.main()
| 12,688 | 318 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_minidom.py | # test for xml.dom.minidom
import copy
import pickle
from test import support
import unittest
import xml.dom.minidom
from xml.dom.minidom import parse, Node, Document, parseString
from xml.dom.minidom import getDOMImplementation
tstfile = support.findfile("test.xml", subdir="xmltestdata")
sample = ("<?xml version='1.0' encoding='us-ascii'?>\n"
"<!DOCTYPE doc PUBLIC 'http://xml.python.org/public'"
" 'http://xml.python.org/system' [\n"
" <!ELEMENT e EMPTY>\n"
" <!ENTITY ent SYSTEM 'http://xml.python.org/entity'>\n"
"]><doc attr='value'> text\n"
"<?pi sample?> <!-- comment --> <e/> </doc>")
# The tests of DocumentType importing use these helpers to construct
# the documents to work with, since not all DOM builders actually
# create the DocumentType nodes.
def create_doc_without_doctype(doctype=None):
return getDOMImplementation().createDocument(None, "doc", doctype)
def create_nonempty_doctype():
doctype = getDOMImplementation().createDocumentType("doc", None, None)
doctype.entities._seq = []
doctype.notations._seq = []
notation = xml.dom.minidom.Notation("my-notation", None,
"http://xml.python.org/notations/my")
doctype.notations._seq.append(notation)
entity = xml.dom.minidom.Entity("my-entity", None,
"http://xml.python.org/entities/my",
"my-notation")
entity.version = "1.0"
entity.encoding = "utf-8"
entity.actualEncoding = "us-ascii"
doctype.entities._seq.append(entity)
return doctype
def create_doc_with_doctype():
doctype = create_nonempty_doctype()
doc = create_doc_without_doctype(doctype)
doctype.entities.item(0).ownerDocument = doc
doctype.notations.item(0).ownerDocument = doc
return doc
class MinidomTest(unittest.TestCase):
def confirm(self, test, testname = "Test"):
self.assertTrue(test, testname)
def checkWholeText(self, node, s):
t = node.wholeText
self.confirm(t == s, "looking for %r, found %r" % (s, t))
def testDocumentAsyncAttr(self):
doc = Document()
self.assertFalse(doc.async_)
with self.assertWarns(DeprecationWarning):
self.assertFalse(getattr(doc, 'async', True))
with self.assertWarns(DeprecationWarning):
setattr(doc, 'async', True)
with self.assertWarns(DeprecationWarning):
self.assertTrue(getattr(doc, 'async', False))
self.assertTrue(doc.async_)
self.assertFalse(Document.async_)
with self.assertWarns(DeprecationWarning):
self.assertFalse(getattr(Document, 'async', True))
def testParseFromBinaryFile(self):
with open(tstfile, 'rb') as file:
dom = parse(file)
dom.unlink()
self.confirm(isinstance(dom, Document))
def testParseFromTextFile(self):
with open(tstfile, 'r', encoding='iso-8859-1') as file:
dom = parse(file)
dom.unlink()
self.confirm(isinstance(dom, Document))
def testGetElementsByTagName(self):
dom = parse(tstfile)
self.confirm(dom.getElementsByTagName("LI") == \
dom.documentElement.getElementsByTagName("LI"))
dom.unlink()
def testInsertBefore(self):
dom = parseString("<doc><foo/></doc>")
root = dom.documentElement
elem = root.childNodes[0]
nelem = dom.createElement("element")
root.insertBefore(nelem, elem)
self.confirm(len(root.childNodes) == 2
and root.childNodes.length == 2
and root.childNodes[0] is nelem
and root.childNodes.item(0) is nelem
and root.childNodes[1] is elem
and root.childNodes.item(1) is elem
and root.firstChild is nelem
and root.lastChild is elem
and root.toxml() == "<doc><element/><foo/></doc>"
, "testInsertBefore -- node properly placed in tree")
nelem = dom.createElement("element")
root.insertBefore(nelem, None)
self.confirm(len(root.childNodes) == 3
and root.childNodes.length == 3
and root.childNodes[1] is elem
and root.childNodes.item(1) is elem
and root.childNodes[2] is nelem
and root.childNodes.item(2) is nelem
and root.lastChild is nelem
and nelem.previousSibling is elem
and root.toxml() == "<doc><element/><foo/><element/></doc>"
, "testInsertBefore -- node properly placed in tree")
nelem2 = dom.createElement("bar")
root.insertBefore(nelem2, nelem)
self.confirm(len(root.childNodes) == 4
and root.childNodes.length == 4
and root.childNodes[2] is nelem2
and root.childNodes.item(2) is nelem2
and root.childNodes[3] is nelem
and root.childNodes.item(3) is nelem
and nelem2.nextSibling is nelem
and nelem.previousSibling is nelem2
and root.toxml() ==
"<doc><element/><foo/><bar/><element/></doc>"
, "testInsertBefore -- node properly placed in tree")
dom.unlink()
def _create_fragment_test_nodes(self):
dom = parseString("<doc/>")
orig = dom.createTextNode("original")
c1 = dom.createTextNode("foo")
c2 = dom.createTextNode("bar")
c3 = dom.createTextNode("bat")
dom.documentElement.appendChild(orig)
frag = dom.createDocumentFragment()
frag.appendChild(c1)
frag.appendChild(c2)
frag.appendChild(c3)
return dom, orig, c1, c2, c3, frag
def testInsertBeforeFragment(self):
dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
dom.documentElement.insertBefore(frag, None)
self.confirm(tuple(dom.documentElement.childNodes) ==
(orig, c1, c2, c3),
"insertBefore(<fragment>, None)")
frag.unlink()
dom.unlink()
dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
dom.documentElement.insertBefore(frag, orig)
self.confirm(tuple(dom.documentElement.childNodes) ==
(c1, c2, c3, orig),
"insertBefore(<fragment>, orig)")
frag.unlink()
dom.unlink()
def testAppendChild(self):
dom = parse(tstfile)
dom.documentElement.appendChild(dom.createComment("Hello"))
self.confirm(dom.documentElement.childNodes[-1].nodeName == "#comment")
self.confirm(dom.documentElement.childNodes[-1].data == "Hello")
dom.unlink()
def testAppendChildFragment(self):
dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
dom.documentElement.appendChild(frag)
self.confirm(tuple(dom.documentElement.childNodes) ==
(orig, c1, c2, c3),
"appendChild(<fragment>)")
frag.unlink()
dom.unlink()
def testReplaceChildFragment(self):
dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
dom.documentElement.replaceChild(frag, orig)
orig.unlink()
self.confirm(tuple(dom.documentElement.childNodes) == (c1, c2, c3),
"replaceChild(<fragment>)")
frag.unlink()
dom.unlink()
def testLegalChildren(self):
dom = Document()
elem = dom.createElement('element')
text = dom.createTextNode('text')
self.assertRaises(xml.dom.HierarchyRequestErr, dom.appendChild, text)
dom.appendChild(elem)
self.assertRaises(xml.dom.HierarchyRequestErr, dom.insertBefore, text,
elem)
self.assertRaises(xml.dom.HierarchyRequestErr, dom.replaceChild, text,
elem)
nodemap = elem.attributes
self.assertRaises(xml.dom.HierarchyRequestErr, nodemap.setNamedItem,
text)
self.assertRaises(xml.dom.HierarchyRequestErr, nodemap.setNamedItemNS,
text)
elem.appendChild(text)
dom.unlink()
def testNamedNodeMapSetItem(self):
dom = Document()
elem = dom.createElement('element')
attrs = elem.attributes
attrs["foo"] = "bar"
a = attrs.item(0)
self.confirm(a.ownerDocument is dom,
"NamedNodeMap.__setitem__() sets ownerDocument")
self.confirm(a.ownerElement is elem,
"NamedNodeMap.__setitem__() sets ownerElement")
self.confirm(a.value == "bar",
"NamedNodeMap.__setitem__() sets value")
self.confirm(a.nodeValue == "bar",
"NamedNodeMap.__setitem__() sets nodeValue")
elem.unlink()
dom.unlink()
def testNonZero(self):
dom = parse(tstfile)
self.confirm(dom)# should not be zero
dom.appendChild(dom.createComment("foo"))
self.confirm(not dom.childNodes[-1].childNodes)
dom.unlink()
def testUnlink(self):
dom = parse(tstfile)
self.assertTrue(dom.childNodes)
dom.unlink()
self.assertFalse(dom.childNodes)
def testContext(self):
with parse(tstfile) as dom:
self.assertTrue(dom.childNodes)
self.assertFalse(dom.childNodes)
def testElement(self):
dom = Document()
dom.appendChild(dom.createElement("abc"))
self.confirm(dom.documentElement)
dom.unlink()
def testAAA(self):
dom = parseString("<abc/>")
el = dom.documentElement
el.setAttribute("spam", "jam2")
self.confirm(el.toxml() == '<abc spam="jam2"/>', "testAAA")
a = el.getAttributeNode("spam")
self.confirm(a.ownerDocument is dom,
"setAttribute() sets ownerDocument")
self.confirm(a.ownerElement is dom.documentElement,
"setAttribute() sets ownerElement")
dom.unlink()
def testAAB(self):
dom = parseString("<abc/>")
el = dom.documentElement
el.setAttribute("spam", "jam")
el.setAttribute("spam", "jam2")
self.confirm(el.toxml() == '<abc spam="jam2"/>', "testAAB")
dom.unlink()
def testAddAttr(self):
dom = Document()
child = dom.appendChild(dom.createElement("abc"))
child.setAttribute("def", "ghi")
self.confirm(child.getAttribute("def") == "ghi")
self.confirm(child.attributes["def"].value == "ghi")
child.setAttribute("jkl", "mno")
self.confirm(child.getAttribute("jkl") == "mno")
self.confirm(child.attributes["jkl"].value == "mno")
self.confirm(len(child.attributes) == 2)
child.setAttribute("def", "newval")
self.confirm(child.getAttribute("def") == "newval")
self.confirm(child.attributes["def"].value == "newval")
self.confirm(len(child.attributes) == 2)
dom.unlink()
def testDeleteAttr(self):
dom = Document()
child = dom.appendChild(dom.createElement("abc"))
self.confirm(len(child.attributes) == 0)
child.setAttribute("def", "ghi")
self.confirm(len(child.attributes) == 1)
del child.attributes["def"]
self.confirm(len(child.attributes) == 0)
dom.unlink()
def testRemoveAttr(self):
dom = Document()
child = dom.appendChild(dom.createElement("abc"))
child.setAttribute("def", "ghi")
self.confirm(len(child.attributes) == 1)
self.assertRaises(xml.dom.NotFoundErr, child.removeAttribute, "foo")
child.removeAttribute("def")
self.confirm(len(child.attributes) == 0)
dom.unlink()
def testRemoveAttrNS(self):
dom = Document()
child = dom.appendChild(
dom.createElementNS("http://www.python.org", "python:abc"))
child.setAttributeNS("http://www.w3.org", "xmlns:python",
"http://www.python.org")
child.setAttributeNS("http://www.python.org", "python:abcattr", "foo")
self.assertRaises(xml.dom.NotFoundErr, child.removeAttributeNS,
"foo", "http://www.python.org")
self.confirm(len(child.attributes) == 2)
child.removeAttributeNS("http://www.python.org", "abcattr")
self.confirm(len(child.attributes) == 1)
dom.unlink()
def testRemoveAttributeNode(self):
dom = Document()
child = dom.appendChild(dom.createElement("foo"))
child.setAttribute("spam", "jam")
self.confirm(len(child.attributes) == 1)
node = child.getAttributeNode("spam")
self.assertRaises(xml.dom.NotFoundErr, child.removeAttributeNode,
None)
child.removeAttributeNode(node)
self.confirm(len(child.attributes) == 0
and child.getAttributeNode("spam") is None)
dom2 = Document()
child2 = dom2.appendChild(dom2.createElement("foo"))
node2 = child2.getAttributeNode("spam")
self.assertRaises(xml.dom.NotFoundErr, child2.removeAttributeNode,
node2)
dom.unlink()
def testHasAttribute(self):
dom = Document()
child = dom.appendChild(dom.createElement("foo"))
child.setAttribute("spam", "jam")
self.confirm(child.hasAttribute("spam"))
def testChangeAttr(self):
dom = parseString("<abc/>")
el = dom.documentElement
el.setAttribute("spam", "jam")
self.confirm(len(el.attributes) == 1)
el.setAttribute("spam", "bam")
# Set this attribute to be an ID and make sure that doesn't change
# when changing the value:
el.setIdAttribute("spam")
self.confirm(len(el.attributes) == 1
and el.attributes["spam"].value == "bam"
and el.attributes["spam"].nodeValue == "bam"
and el.getAttribute("spam") == "bam"
and el.getAttributeNode("spam").isId)
el.attributes["spam"] = "ham"
self.confirm(len(el.attributes) == 1
and el.attributes["spam"].value == "ham"
and el.attributes["spam"].nodeValue == "ham"
and el.getAttribute("spam") == "ham"
and el.attributes["spam"].isId)
el.setAttribute("spam2", "bam")
self.confirm(len(el.attributes) == 2
and el.attributes["spam"].value == "ham"
and el.attributes["spam"].nodeValue == "ham"
and el.getAttribute("spam") == "ham"
and el.attributes["spam2"].value == "bam"
and el.attributes["spam2"].nodeValue == "bam"
and el.getAttribute("spam2") == "bam")
el.attributes["spam2"] = "bam2"
self.confirm(len(el.attributes) == 2
and el.attributes["spam"].value == "ham"
and el.attributes["spam"].nodeValue == "ham"
and el.getAttribute("spam") == "ham"
and el.attributes["spam2"].value == "bam2"
and el.attributes["spam2"].nodeValue == "bam2"
and el.getAttribute("spam2") == "bam2")
dom.unlink()
def testGetAttrList(self):
pass
def testGetAttrValues(self):
pass
def testGetAttrLength(self):
pass
def testGetAttribute(self):
dom = Document()
child = dom.appendChild(
dom.createElementNS("http://www.python.org", "python:abc"))
self.assertEqual(child.getAttribute('missing'), '')
def testGetAttributeNS(self):
dom = Document()
child = dom.appendChild(
dom.createElementNS("http://www.python.org", "python:abc"))
child.setAttributeNS("http://www.w3.org", "xmlns:python",
"http://www.python.org")
self.assertEqual(child.getAttributeNS("http://www.w3.org", "python"),
'http://www.python.org')
self.assertEqual(child.getAttributeNS("http://www.w3.org", "other"),
'')
child2 = child.appendChild(dom.createElement('abc'))
self.assertEqual(child2.getAttributeNS("http://www.python.org", "missing"),
'')
def testGetAttributeNode(self): pass
def testGetElementsByTagNameNS(self):
d="""<foo xmlns:minidom='http://pyxml.sf.net/minidom'>
<minidom:myelem/>
</foo>"""
dom = parseString(d)
elems = dom.getElementsByTagNameNS("http://pyxml.sf.net/minidom",
"myelem")
self.confirm(len(elems) == 1
and elems[0].namespaceURI == "http://pyxml.sf.net/minidom"
and elems[0].localName == "myelem"
and elems[0].prefix == "minidom"
and elems[0].tagName == "minidom:myelem"
and elems[0].nodeName == "minidom:myelem")
dom.unlink()
def get_empty_nodelist_from_elements_by_tagName_ns_helper(self, doc, nsuri,
lname):
nodelist = doc.getElementsByTagNameNS(nsuri, lname)
self.confirm(len(nodelist) == 0)
def testGetEmptyNodeListFromElementsByTagNameNS(self):
doc = parseString('<doc/>')
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
doc, 'http://xml.python.org/namespaces/a', 'localname')
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
doc, '*', 'splat')
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
doc, 'http://xml.python.org/namespaces/a', '*')
doc = parseString('<doc xmlns="http://xml.python.org/splat"><e/></doc>')
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
doc, "http://xml.python.org/splat", "not-there")
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
doc, "*", "not-there")
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
doc, "http://somewhere.else.net/not-there", "e")
def testElementReprAndStr(self):
dom = Document()
el = dom.appendChild(dom.createElement("abc"))
string1 = repr(el)
string2 = str(el)
self.confirm(string1 == string2)
dom.unlink()
def testElementReprAndStrUnicode(self):
dom = Document()
el = dom.appendChild(dom.createElement("abc"))
string1 = repr(el)
string2 = str(el)
self.confirm(string1 == string2)
dom.unlink()
def testElementReprAndStrUnicodeNS(self):
dom = Document()
el = dom.appendChild(
dom.createElementNS("http://www.slashdot.org", "slash:abc"))
string1 = repr(el)
string2 = str(el)
self.confirm(string1 == string2)
self.confirm("slash:abc" in string1)
dom.unlink()
def testAttributeRepr(self):
dom = Document()
el = dom.appendChild(dom.createElement("abc"))
node = el.setAttribute("abc", "def")
self.confirm(str(node) == repr(node))
dom.unlink()
def testTextNodeRepr(self): pass
def testWriteXML(self):
str = '<?xml version="1.0" ?><a b="c"/>'
dom = parseString(str)
domstr = dom.toxml()
dom.unlink()
self.confirm(str == domstr)
def testAltNewline(self):
str = '<?xml version="1.0" ?>\n<a b="c"/>\n'
dom = parseString(str)
domstr = dom.toprettyxml(newl="\r\n")
dom.unlink()
self.confirm(domstr == str.replace("\n", "\r\n"))
def test_toprettyxml_with_text_nodes(self):
# see issue #4147, text nodes are not indented
decl = '<?xml version="1.0" ?>\n'
self.assertEqual(parseString('<B>A</B>').toprettyxml(),
decl + '<B>A</B>\n')
self.assertEqual(parseString('<C>A<B>A</B></C>').toprettyxml(),
decl + '<C>\n\tA\n\t<B>A</B>\n</C>\n')
self.assertEqual(parseString('<C><B>A</B>A</C>').toprettyxml(),
decl + '<C>\n\t<B>A</B>\n\tA\n</C>\n')
self.assertEqual(parseString('<C><B>A</B><B>A</B></C>').toprettyxml(),
decl + '<C>\n\t<B>A</B>\n\t<B>A</B>\n</C>\n')
self.assertEqual(parseString('<C><B>A</B>A<B>A</B></C>').toprettyxml(),
decl + '<C>\n\t<B>A</B>\n\tA\n\t<B>A</B>\n</C>\n')
def test_toprettyxml_with_adjacent_text_nodes(self):
# see issue #4147, adjacent text nodes are indented normally
dom = Document()
elem = dom.createElement('elem')
elem.appendChild(dom.createTextNode('TEXT'))
elem.appendChild(dom.createTextNode('TEXT'))
dom.appendChild(elem)
decl = '<?xml version="1.0" ?>\n'
self.assertEqual(dom.toprettyxml(),
decl + '<elem>\n\tTEXT\n\tTEXT\n</elem>\n')
def test_toprettyxml_preserves_content_of_text_node(self):
# see issue #4147
for str in ('<B>A</B>', '<A><B>C</B></A>'):
dom = parseString(str)
dom2 = parseString(dom.toprettyxml())
self.assertEqual(
dom.getElementsByTagName('B')[0].childNodes[0].toxml(),
dom2.getElementsByTagName('B')[0].childNodes[0].toxml())
def testProcessingInstruction(self):
dom = parseString('<e><?mypi \t\n data \t\n ?></e>')
pi = dom.documentElement.firstChild
self.confirm(pi.target == "mypi"
and pi.data == "data \t\n "
and pi.nodeName == "mypi"
and pi.nodeType == Node.PROCESSING_INSTRUCTION_NODE
and pi.attributes is None
and not pi.hasChildNodes()
and len(pi.childNodes) == 0
and pi.firstChild is None
and pi.lastChild is None
and pi.localName is None
and pi.namespaceURI == xml.dom.EMPTY_NAMESPACE)
def testProcessingInstructionRepr(self): pass
def testTextRepr(self): pass
def testWriteText(self): pass
def testDocumentElement(self): pass
def testTooManyDocumentElements(self):
doc = parseString("<doc/>")
elem = doc.createElement("extra")
# Should raise an exception when adding an extra document element.
self.assertRaises(xml.dom.HierarchyRequestErr, doc.appendChild, elem)
elem.unlink()
doc.unlink()
def testCreateElementNS(self): pass
def testCreateAttributeNS(self): pass
def testParse(self): pass
def testParseString(self): pass
def testComment(self): pass
def testAttrListItem(self): pass
def testAttrListItems(self): pass
def testAttrListItemNS(self): pass
def testAttrListKeys(self): pass
def testAttrListKeysNS(self): pass
def testRemoveNamedItem(self):
doc = parseString("<doc a=''/>")
e = doc.documentElement
attrs = e.attributes
a1 = e.getAttributeNode("a")
a2 = attrs.removeNamedItem("a")
self.confirm(a1.isSameNode(a2))
self.assertRaises(xml.dom.NotFoundErr, attrs.removeNamedItem, "a")
def testRemoveNamedItemNS(self):
doc = parseString("<doc xmlns:a='http://xml.python.org/' a:b=''/>")
e = doc.documentElement
attrs = e.attributes
a1 = e.getAttributeNodeNS("http://xml.python.org/", "b")
a2 = attrs.removeNamedItemNS("http://xml.python.org/", "b")
self.confirm(a1.isSameNode(a2))
self.assertRaises(xml.dom.NotFoundErr, attrs.removeNamedItemNS,
"http://xml.python.org/", "b")
def testAttrListValues(self): pass
def testAttrListLength(self): pass
def testAttrList__getitem__(self): pass
def testAttrList__setitem__(self): pass
def testSetAttrValueandNodeValue(self): pass
def testParseElement(self): pass
def testParseAttributes(self): pass
def testParseElementNamespaces(self): pass
def testParseAttributeNamespaces(self): pass
def testParseProcessingInstructions(self): pass
def testChildNodes(self): pass
def testFirstChild(self): pass
def testHasChildNodes(self):
dom = parseString("<doc><foo/></doc>")
doc = dom.documentElement
self.assertTrue(doc.hasChildNodes())
dom2 = parseString("<doc/>")
doc2 = dom2.documentElement
self.assertFalse(doc2.hasChildNodes())
def _testCloneElementCopiesAttributes(self, e1, e2, test):
attrs1 = e1.attributes
attrs2 = e2.attributes
keys1 = list(attrs1.keys())
keys2 = list(attrs2.keys())
keys1.sort()
keys2.sort()
self.confirm(keys1 == keys2, "clone of element has same attribute keys")
for i in range(len(keys1)):
a1 = attrs1.item(i)
a2 = attrs2.item(i)
self.confirm(a1 is not a2
and a1.value == a2.value
and a1.nodeValue == a2.nodeValue
and a1.namespaceURI == a2.namespaceURI
and a1.localName == a2.localName
, "clone of attribute node has proper attribute values")
self.confirm(a2.ownerElement is e2,
"clone of attribute node correctly owned")
def _setupCloneElement(self, deep):
dom = parseString("<doc attr='value'><foo/></doc>")
root = dom.documentElement
clone = root.cloneNode(deep)
self._testCloneElementCopiesAttributes(
root, clone, "testCloneElement" + (deep and "Deep" or "Shallow"))
# mutilate the original so shared data is detected
root.tagName = root.nodeName = "MODIFIED"
root.setAttribute("attr", "NEW VALUE")
root.setAttribute("added", "VALUE")
return dom, clone
def testCloneElementShallow(self):
dom, clone = self._setupCloneElement(0)
self.confirm(len(clone.childNodes) == 0
and clone.childNodes.length == 0
and clone.parentNode is None
and clone.toxml() == '<doc attr="value"/>'
, "testCloneElementShallow")
dom.unlink()
def testCloneElementDeep(self):
dom, clone = self._setupCloneElement(1)
self.confirm(len(clone.childNodes) == 1
and clone.childNodes.length == 1
and clone.parentNode is None
and clone.toxml() == '<doc attr="value"><foo/></doc>'
, "testCloneElementDeep")
dom.unlink()
def testCloneDocumentShallow(self):
doc = parseString("<?xml version='1.0'?>\n"
"<!-- comment -->"
"<!DOCTYPE doc [\n"
"<!NOTATION notation SYSTEM 'http://xml.python.org/'>\n"
"]>\n"
"<doc attr='value'/>")
doc2 = doc.cloneNode(0)
self.confirm(doc2 is None,
"testCloneDocumentShallow:"
" shallow cloning of documents makes no sense!")
def testCloneDocumentDeep(self):
doc = parseString("<?xml version='1.0'?>\n"
"<!-- comment -->"
"<!DOCTYPE doc [\n"
"<!NOTATION notation SYSTEM 'http://xml.python.org/'>\n"
"]>\n"
"<doc attr='value'/>")
doc2 = doc.cloneNode(1)
self.confirm(not (doc.isSameNode(doc2) or doc2.isSameNode(doc)),
"testCloneDocumentDeep: document objects not distinct")
self.confirm(len(doc.childNodes) == len(doc2.childNodes),
"testCloneDocumentDeep: wrong number of Document children")
self.confirm(doc2.documentElement.nodeType == Node.ELEMENT_NODE,
"testCloneDocumentDeep: documentElement not an ELEMENT_NODE")
self.confirm(doc2.documentElement.ownerDocument.isSameNode(doc2),
"testCloneDocumentDeep: documentElement owner is not new document")
self.confirm(not doc.documentElement.isSameNode(doc2.documentElement),
"testCloneDocumentDeep: documentElement should not be shared")
if doc.doctype is not None:
# check the doctype iff the original DOM maintained it
self.confirm(doc2.doctype.nodeType == Node.DOCUMENT_TYPE_NODE,
"testCloneDocumentDeep: doctype not a DOCUMENT_TYPE_NODE")
self.confirm(doc2.doctype.ownerDocument.isSameNode(doc2))
self.confirm(not doc.doctype.isSameNode(doc2.doctype))
def testCloneDocumentTypeDeepOk(self):
doctype = create_nonempty_doctype()
clone = doctype.cloneNode(1)
self.confirm(clone is not None
and clone.nodeName == doctype.nodeName
and clone.name == doctype.name
and clone.publicId == doctype.publicId
and clone.systemId == doctype.systemId
and len(clone.entities) == len(doctype.entities)
and clone.entities.item(len(clone.entities)) is None
and len(clone.notations) == len(doctype.notations)
and clone.notations.item(len(clone.notations)) is None
and len(clone.childNodes) == 0)
for i in range(len(doctype.entities)):
se = doctype.entities.item(i)
ce = clone.entities.item(i)
self.confirm((not se.isSameNode(ce))
and (not ce.isSameNode(se))
and ce.nodeName == se.nodeName
and ce.notationName == se.notationName
and ce.publicId == se.publicId
and ce.systemId == se.systemId
and ce.encoding == se.encoding
and ce.actualEncoding == se.actualEncoding
and ce.version == se.version)
for i in range(len(doctype.notations)):
sn = doctype.notations.item(i)
cn = clone.notations.item(i)
self.confirm((not sn.isSameNode(cn))
and (not cn.isSameNode(sn))
and cn.nodeName == sn.nodeName
and cn.publicId == sn.publicId
and cn.systemId == sn.systemId)
def testCloneDocumentTypeDeepNotOk(self):
doc = create_doc_with_doctype()
clone = doc.doctype.cloneNode(1)
self.confirm(clone is None, "testCloneDocumentTypeDeepNotOk")
def testCloneDocumentTypeShallowOk(self):
doctype = create_nonempty_doctype()
clone = doctype.cloneNode(0)
self.confirm(clone is not None
and clone.nodeName == doctype.nodeName
and clone.name == doctype.name
and clone.publicId == doctype.publicId
and clone.systemId == doctype.systemId
and len(clone.entities) == 0
and clone.entities.item(0) is None
and len(clone.notations) == 0
and clone.notations.item(0) is None
and len(clone.childNodes) == 0)
def testCloneDocumentTypeShallowNotOk(self):
doc = create_doc_with_doctype()
clone = doc.doctype.cloneNode(0)
self.confirm(clone is None, "testCloneDocumentTypeShallowNotOk")
def check_import_document(self, deep, testName):
doc1 = parseString("<doc/>")
doc2 = parseString("<doc/>")
self.assertRaises(xml.dom.NotSupportedErr, doc1.importNode, doc2, deep)
def testImportDocumentShallow(self):
self.check_import_document(0, "testImportDocumentShallow")
def testImportDocumentDeep(self):
self.check_import_document(1, "testImportDocumentDeep")
def testImportDocumentTypeShallow(self):
src = create_doc_with_doctype()
target = create_doc_without_doctype()
self.assertRaises(xml.dom.NotSupportedErr, target.importNode,
src.doctype, 0)
def testImportDocumentTypeDeep(self):
src = create_doc_with_doctype()
target = create_doc_without_doctype()
self.assertRaises(xml.dom.NotSupportedErr, target.importNode,
src.doctype, 1)
# Testing attribute clones uses a helper, and should always be deep,
# even if the argument to cloneNode is false.
def check_clone_attribute(self, deep, testName):
doc = parseString("<doc attr='value'/>")
attr = doc.documentElement.getAttributeNode("attr")
self.assertNotEqual(attr, None)
clone = attr.cloneNode(deep)
self.confirm(not clone.isSameNode(attr))
self.confirm(not attr.isSameNode(clone))
self.confirm(clone.ownerElement is None,
testName + ": ownerElement should be None")
self.confirm(clone.ownerDocument.isSameNode(attr.ownerDocument),
testName + ": ownerDocument does not match")
self.confirm(clone.specified,
testName + ": cloned attribute must have specified == True")
def testCloneAttributeShallow(self):
self.check_clone_attribute(0, "testCloneAttributeShallow")
def testCloneAttributeDeep(self):
self.check_clone_attribute(1, "testCloneAttributeDeep")
def check_clone_pi(self, deep, testName):
doc = parseString("<?target data?><doc/>")
pi = doc.firstChild
self.assertEqual(pi.nodeType, Node.PROCESSING_INSTRUCTION_NODE)
clone = pi.cloneNode(deep)
self.confirm(clone.target == pi.target
and clone.data == pi.data)
def testClonePIShallow(self):
self.check_clone_pi(0, "testClonePIShallow")
def testClonePIDeep(self):
self.check_clone_pi(1, "testClonePIDeep")
def check_clone_node_entity(self, clone_document):
# bpo-35052: Test user data handler in cloneNode() on a document with
# an entity
document = xml.dom.minidom.parseString("""
<?xml version="1.0" ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"
[ <!ENTITY smile "âº"> ]
>
<doc>Don't let entities make you frown ⌣</doc>
""".strip())
class Handler:
def handle(self, operation, key, data, src, dst):
self.operation = operation
self.key = key
self.data = data
self.src = src
self.dst = dst
handler = Handler()
doctype = document.doctype
entity = doctype.entities['smile']
entity.setUserData("key", "data", handler)
if clone_document:
# clone Document
clone = document.cloneNode(deep=True)
self.assertEqual(clone.documentElement.firstChild.wholeText,
"Don't let entities make you frown âº")
operation = xml.dom.UserDataHandler.NODE_IMPORTED
dst = clone.doctype.entities['smile']
else:
# clone DocumentType
with support.swap_attr(doctype, 'ownerDocument', None):
clone = doctype.cloneNode(deep=True)
operation = xml.dom.UserDataHandler.NODE_CLONED
dst = clone.entities['smile']
self.assertEqual(handler.operation, operation)
self.assertEqual(handler.key, "key")
self.assertEqual(handler.data, "data")
self.assertIs(handler.src, entity)
self.assertIs(handler.dst, dst)
def testCloneNodeEntity(self):
self.check_clone_node_entity(False)
self.check_clone_node_entity(True)
def testNormalize(self):
doc = parseString("<doc/>")
root = doc.documentElement
root.appendChild(doc.createTextNode("first"))
root.appendChild(doc.createTextNode("second"))
self.confirm(len(root.childNodes) == 2
and root.childNodes.length == 2,
"testNormalize -- preparation")
doc.normalize()
self.confirm(len(root.childNodes) == 1
and root.childNodes.length == 1
and root.firstChild is root.lastChild
and root.firstChild.data == "firstsecond"
, "testNormalize -- result")
doc.unlink()
doc = parseString("<doc/>")
root = doc.documentElement
root.appendChild(doc.createTextNode(""))
doc.normalize()
self.confirm(len(root.childNodes) == 0
and root.childNodes.length == 0,
"testNormalize -- single empty node removed")
doc.unlink()
def testNormalizeCombineAndNextSibling(self):
doc = parseString("<doc/>")
root = doc.documentElement
root.appendChild(doc.createTextNode("first"))
root.appendChild(doc.createTextNode("second"))
root.appendChild(doc.createElement("i"))
self.confirm(len(root.childNodes) == 3
and root.childNodes.length == 3,
"testNormalizeCombineAndNextSibling -- preparation")
doc.normalize()
self.confirm(len(root.childNodes) == 2
and root.childNodes.length == 2
and root.firstChild.data == "firstsecond"
and root.firstChild is not root.lastChild
and root.firstChild.nextSibling is root.lastChild
and root.firstChild.previousSibling is None
and root.lastChild.previousSibling is root.firstChild
and root.lastChild.nextSibling is None
, "testNormalizeCombinedAndNextSibling -- result")
doc.unlink()
def testNormalizeDeleteWithPrevSibling(self):
doc = parseString("<doc/>")
root = doc.documentElement
root.appendChild(doc.createTextNode("first"))
root.appendChild(doc.createTextNode(""))
self.confirm(len(root.childNodes) == 2
and root.childNodes.length == 2,
"testNormalizeDeleteWithPrevSibling -- preparation")
doc.normalize()
self.confirm(len(root.childNodes) == 1
and root.childNodes.length == 1
and root.firstChild.data == "first"
and root.firstChild is root.lastChild
and root.firstChild.nextSibling is None
and root.firstChild.previousSibling is None
, "testNormalizeDeleteWithPrevSibling -- result")
doc.unlink()
def testNormalizeDeleteWithNextSibling(self):
doc = parseString("<doc/>")
root = doc.documentElement
root.appendChild(doc.createTextNode(""))
root.appendChild(doc.createTextNode("second"))
self.confirm(len(root.childNodes) == 2
and root.childNodes.length == 2,
"testNormalizeDeleteWithNextSibling -- preparation")
doc.normalize()
self.confirm(len(root.childNodes) == 1
and root.childNodes.length == 1
and root.firstChild.data == "second"
and root.firstChild is root.lastChild
and root.firstChild.nextSibling is None
and root.firstChild.previousSibling is None
, "testNormalizeDeleteWithNextSibling -- result")
doc.unlink()
def testNormalizeDeleteWithTwoNonTextSiblings(self):
doc = parseString("<doc/>")
root = doc.documentElement
root.appendChild(doc.createElement("i"))
root.appendChild(doc.createTextNode(""))
root.appendChild(doc.createElement("i"))
self.confirm(len(root.childNodes) == 3
and root.childNodes.length == 3,
"testNormalizeDeleteWithTwoSiblings -- preparation")
doc.normalize()
self.confirm(len(root.childNodes) == 2
and root.childNodes.length == 2
and root.firstChild is not root.lastChild
and root.firstChild.nextSibling is root.lastChild
and root.firstChild.previousSibling is None
and root.lastChild.previousSibling is root.firstChild
and root.lastChild.nextSibling is None
, "testNormalizeDeleteWithTwoSiblings -- result")
doc.unlink()
def testNormalizeDeleteAndCombine(self):
doc = parseString("<doc/>")
root = doc.documentElement
root.appendChild(doc.createTextNode(""))
root.appendChild(doc.createTextNode("second"))
root.appendChild(doc.createTextNode(""))
root.appendChild(doc.createTextNode("fourth"))
root.appendChild(doc.createTextNode(""))
self.confirm(len(root.childNodes) == 5
and root.childNodes.length == 5,
"testNormalizeDeleteAndCombine -- preparation")
doc.normalize()
self.confirm(len(root.childNodes) == 1
and root.childNodes.length == 1
and root.firstChild is root.lastChild
and root.firstChild.data == "secondfourth"
and root.firstChild.previousSibling is None
and root.firstChild.nextSibling is None
, "testNormalizeDeleteAndCombine -- result")
doc.unlink()
def testNormalizeRecursion(self):
doc = parseString("<doc>"
"<o>"
"<i/>"
"t"
#
#x
"</o>"
"<o>"
"<o>"
"t2"
#x2
"</o>"
"t3"
#x3
"</o>"
#
"</doc>")
root = doc.documentElement
root.childNodes[0].appendChild(doc.createTextNode(""))
root.childNodes[0].appendChild(doc.createTextNode("x"))
root.childNodes[1].childNodes[0].appendChild(doc.createTextNode("x2"))
root.childNodes[1].appendChild(doc.createTextNode("x3"))
root.appendChild(doc.createTextNode(""))
self.confirm(len(root.childNodes) == 3
and root.childNodes.length == 3
and len(root.childNodes[0].childNodes) == 4
and root.childNodes[0].childNodes.length == 4
and len(root.childNodes[1].childNodes) == 3
and root.childNodes[1].childNodes.length == 3
and len(root.childNodes[1].childNodes[0].childNodes) == 2
and root.childNodes[1].childNodes[0].childNodes.length == 2
, "testNormalize2 -- preparation")
doc.normalize()
self.confirm(len(root.childNodes) == 2
and root.childNodes.length == 2
and len(root.childNodes[0].childNodes) == 2
and root.childNodes[0].childNodes.length == 2
and len(root.childNodes[1].childNodes) == 2
and root.childNodes[1].childNodes.length == 2
and len(root.childNodes[1].childNodes[0].childNodes) == 1
and root.childNodes[1].childNodes[0].childNodes.length == 1
, "testNormalize2 -- childNodes lengths")
self.confirm(root.childNodes[0].childNodes[1].data == "tx"
and root.childNodes[1].childNodes[0].childNodes[0].data == "t2x2"
and root.childNodes[1].childNodes[1].data == "t3x3"
, "testNormalize2 -- joined text fields")
self.confirm(root.childNodes[0].childNodes[1].nextSibling is None
and root.childNodes[0].childNodes[1].previousSibling
is root.childNodes[0].childNodes[0]
and root.childNodes[0].childNodes[0].previousSibling is None
and root.childNodes[0].childNodes[0].nextSibling
is root.childNodes[0].childNodes[1]
and root.childNodes[1].childNodes[1].nextSibling is None
and root.childNodes[1].childNodes[1].previousSibling
is root.childNodes[1].childNodes[0]
and root.childNodes[1].childNodes[0].previousSibling is None
and root.childNodes[1].childNodes[0].nextSibling
is root.childNodes[1].childNodes[1]
, "testNormalize2 -- sibling pointers")
doc.unlink()
def testBug0777884(self):
doc = parseString("<o>text</o>")
text = doc.documentElement.childNodes[0]
self.assertEqual(text.nodeType, Node.TEXT_NODE)
# Should run quietly, doing nothing.
text.normalize()
doc.unlink()
def testBug1433694(self):
doc = parseString("<o><i/>t</o>")
node = doc.documentElement
node.childNodes[1].nodeValue = ""
node.normalize()
self.confirm(node.childNodes[-1].nextSibling is None,
"Final child's .nextSibling should be None")
def testSiblings(self):
doc = parseString("<doc><?pi?>text?<elm/></doc>")
root = doc.documentElement
(pi, text, elm) = root.childNodes
self.confirm(pi.nextSibling is text and
pi.previousSibling is None and
text.nextSibling is elm and
text.previousSibling is pi and
elm.nextSibling is None and
elm.previousSibling is text, "testSiblings")
doc.unlink()
def testParents(self):
doc = parseString(
"<doc><elm1><elm2/><elm2><elm3/></elm2></elm1></doc>")
root = doc.documentElement
elm1 = root.childNodes[0]
(elm2a, elm2b) = elm1.childNodes
elm3 = elm2b.childNodes[0]
self.confirm(root.parentNode is doc and
elm1.parentNode is root and
elm2a.parentNode is elm1 and
elm2b.parentNode is elm1 and
elm3.parentNode is elm2b, "testParents")
doc.unlink()
def testNodeListItem(self):
doc = parseString("<doc><e/><e/></doc>")
children = doc.childNodes
docelem = children[0]
self.confirm(children[0] is children.item(0)
and children.item(1) is None
and docelem.childNodes.item(0) is docelem.childNodes[0]
and docelem.childNodes.item(1) is docelem.childNodes[1]
and docelem.childNodes.item(0).childNodes.item(0) is None,
"test NodeList.item()")
doc.unlink()
def testEncodings(self):
doc = parseString('<foo>€</foo>')
self.assertEqual(doc.toxml(),
'<?xml version="1.0" ?><foo>\u20ac</foo>')
self.assertEqual(doc.toxml('utf-8'),
b'<?xml version="1.0" encoding="utf-8"?><foo>\xe2\x82\xac</foo>')
return
self.assertEqual(doc.toxml('iso-8859-15'),
b'<?xml version="1.0" encoding="iso-8859-15"?><foo>\xa4</foo>')
self.assertEqual(doc.toxml('us-ascii'),
b'<?xml version="1.0" encoding="us-ascii"?><foo>€</foo>')
self.assertEqual(doc.toxml('utf-16'),
'<?xml version="1.0" encoding="utf-16"?>'
'<foo>\u20ac</foo>'.encode('utf-16'))
# Verify that character decoding errors raise exceptions instead
# of crashing
self.assertRaises(UnicodeDecodeError, parseString,
b'<fran\xe7ais>Comment \xe7a va ? Tr\xe8s bien ?</fran\xe7ais>')
doc.unlink()
class UserDataHandler:
called = 0
def handle(self, operation, key, data, src, dst):
dst.setUserData(key, data + 1, self)
src.setUserData(key, None, None)
self.called = 1
def testUserData(self):
dom = Document()
n = dom.createElement('e')
self.confirm(n.getUserData("foo") is None)
n.setUserData("foo", None, None)
self.confirm(n.getUserData("foo") is None)
n.setUserData("foo", 12, 12)
n.setUserData("bar", 13, 13)
self.confirm(n.getUserData("foo") == 12)
self.confirm(n.getUserData("bar") == 13)
n.setUserData("foo", None, None)
self.confirm(n.getUserData("foo") is None)
self.confirm(n.getUserData("bar") == 13)
handler = self.UserDataHandler()
n.setUserData("bar", 12, handler)
c = n.cloneNode(1)
self.confirm(handler.called
and n.getUserData("bar") is None
and c.getUserData("bar") == 13)
n.unlink()
c.unlink()
dom.unlink()
def checkRenameNodeSharedConstraints(self, doc, node):
# Make sure illegal NS usage is detected:
self.assertRaises(xml.dom.NamespaceErr, doc.renameNode, node,
"http://xml.python.org/ns", "xmlns:foo")
doc2 = parseString("<doc/>")
self.assertRaises(xml.dom.WrongDocumentErr, doc2.renameNode, node,
xml.dom.EMPTY_NAMESPACE, "foo")
def testRenameAttribute(self):
doc = parseString("<doc a='v'/>")
elem = doc.documentElement
attrmap = elem.attributes
attr = elem.attributes['a']
# Simple renaming
attr = doc.renameNode(attr, xml.dom.EMPTY_NAMESPACE, "b")
self.confirm(attr.name == "b"
and attr.nodeName == "b"
and attr.localName is None
and attr.namespaceURI == xml.dom.EMPTY_NAMESPACE
and attr.prefix is None
and attr.value == "v"
and elem.getAttributeNode("a") is None
and elem.getAttributeNode("b").isSameNode(attr)
and attrmap["b"].isSameNode(attr)
and attr.ownerDocument.isSameNode(doc)
and attr.ownerElement.isSameNode(elem))
# Rename to have a namespace, no prefix
attr = doc.renameNode(attr, "http://xml.python.org/ns", "c")
self.confirm(attr.name == "c"
and attr.nodeName == "c"
and attr.localName == "c"
and attr.namespaceURI == "http://xml.python.org/ns"
and attr.prefix is None
and attr.value == "v"
and elem.getAttributeNode("a") is None
and elem.getAttributeNode("b") is None
and elem.getAttributeNode("c").isSameNode(attr)
and elem.getAttributeNodeNS(
"http://xml.python.org/ns", "c").isSameNode(attr)
and attrmap["c"].isSameNode(attr)
and attrmap[("http://xml.python.org/ns", "c")].isSameNode(attr))
# Rename to have a namespace, with prefix
attr = doc.renameNode(attr, "http://xml.python.org/ns2", "p:d")
self.confirm(attr.name == "p:d"
and attr.nodeName == "p:d"
and attr.localName == "d"
and attr.namespaceURI == "http://xml.python.org/ns2"
and attr.prefix == "p"
and attr.value == "v"
and elem.getAttributeNode("a") is None
and elem.getAttributeNode("b") is None
and elem.getAttributeNode("c") is None
and elem.getAttributeNodeNS(
"http://xml.python.org/ns", "c") is None
and elem.getAttributeNode("p:d").isSameNode(attr)
and elem.getAttributeNodeNS(
"http://xml.python.org/ns2", "d").isSameNode(attr)
and attrmap["p:d"].isSameNode(attr)
and attrmap[("http://xml.python.org/ns2", "d")].isSameNode(attr))
# Rename back to a simple non-NS node
attr = doc.renameNode(attr, xml.dom.EMPTY_NAMESPACE, "e")
self.confirm(attr.name == "e"
and attr.nodeName == "e"
and attr.localName is None
and attr.namespaceURI == xml.dom.EMPTY_NAMESPACE
and attr.prefix is None
and attr.value == "v"
and elem.getAttributeNode("a") is None
and elem.getAttributeNode("b") is None
and elem.getAttributeNode("c") is None
and elem.getAttributeNode("p:d") is None
and elem.getAttributeNodeNS(
"http://xml.python.org/ns", "c") is None
and elem.getAttributeNode("e").isSameNode(attr)
and attrmap["e"].isSameNode(attr))
self.assertRaises(xml.dom.NamespaceErr, doc.renameNode, attr,
"http://xml.python.org/ns", "xmlns")
self.checkRenameNodeSharedConstraints(doc, attr)
doc.unlink()
def testRenameElement(self):
doc = parseString("<doc/>")
elem = doc.documentElement
# Simple renaming
elem = doc.renameNode(elem, xml.dom.EMPTY_NAMESPACE, "a")
self.confirm(elem.tagName == "a"
and elem.nodeName == "a"
and elem.localName is None
and elem.namespaceURI == xml.dom.EMPTY_NAMESPACE
and elem.prefix is None
and elem.ownerDocument.isSameNode(doc))
# Rename to have a namespace, no prefix
elem = doc.renameNode(elem, "http://xml.python.org/ns", "b")
self.confirm(elem.tagName == "b"
and elem.nodeName == "b"
and elem.localName == "b"
and elem.namespaceURI == "http://xml.python.org/ns"
and elem.prefix is None
and elem.ownerDocument.isSameNode(doc))
# Rename to have a namespace, with prefix
elem = doc.renameNode(elem, "http://xml.python.org/ns2", "p:c")
self.confirm(elem.tagName == "p:c"
and elem.nodeName == "p:c"
and elem.localName == "c"
and elem.namespaceURI == "http://xml.python.org/ns2"
and elem.prefix == "p"
and elem.ownerDocument.isSameNode(doc))
# Rename back to a simple non-NS node
elem = doc.renameNode(elem, xml.dom.EMPTY_NAMESPACE, "d")
self.confirm(elem.tagName == "d"
and elem.nodeName == "d"
and elem.localName is None
and elem.namespaceURI == xml.dom.EMPTY_NAMESPACE
and elem.prefix is None
and elem.ownerDocument.isSameNode(doc))
self.checkRenameNodeSharedConstraints(doc, elem)
doc.unlink()
def testRenameOther(self):
# We have to create a comment node explicitly since not all DOM
# builders used with minidom add comments to the DOM.
doc = xml.dom.minidom.getDOMImplementation().createDocument(
xml.dom.EMPTY_NAMESPACE, "e", None)
node = doc.createComment("comment")
self.assertRaises(xml.dom.NotSupportedErr, doc.renameNode, node,
xml.dom.EMPTY_NAMESPACE, "foo")
doc.unlink()
def testWholeText(self):
doc = parseString("<doc>a</doc>")
elem = doc.documentElement
text = elem.childNodes[0]
self.assertEqual(text.nodeType, Node.TEXT_NODE)
self.checkWholeText(text, "a")
elem.appendChild(doc.createTextNode("b"))
self.checkWholeText(text, "ab")
elem.insertBefore(doc.createCDATASection("c"), text)
self.checkWholeText(text, "cab")
# make sure we don't cross other nodes
splitter = doc.createComment("comment")
elem.appendChild(splitter)
text2 = doc.createTextNode("d")
elem.appendChild(text2)
self.checkWholeText(text, "cab")
self.checkWholeText(text2, "d")
x = doc.createElement("x")
elem.replaceChild(x, splitter)
splitter = x
self.checkWholeText(text, "cab")
self.checkWholeText(text2, "d")
x = doc.createProcessingInstruction("y", "z")
elem.replaceChild(x, splitter)
splitter = x
self.checkWholeText(text, "cab")
self.checkWholeText(text2, "d")
elem.removeChild(splitter)
self.checkWholeText(text, "cabd")
self.checkWholeText(text2, "cabd")
def testPatch1094164(self):
doc = parseString("<doc><e/></doc>")
elem = doc.documentElement
e = elem.firstChild
self.confirm(e.parentNode is elem, "Before replaceChild()")
# Check that replacing a child with itself leaves the tree unchanged
elem.replaceChild(e, e)
self.confirm(e.parentNode is elem, "After replaceChild()")
def testReplaceWholeText(self):
def setup():
doc = parseString("<doc>a<e/>d</doc>")
elem = doc.documentElement
text1 = elem.firstChild
text2 = elem.lastChild
splitter = text1.nextSibling
elem.insertBefore(doc.createTextNode("b"), splitter)
elem.insertBefore(doc.createCDATASection("c"), text1)
return doc, elem, text1, splitter, text2
doc, elem, text1, splitter, text2 = setup()
text = text1.replaceWholeText("new content")
self.checkWholeText(text, "new content")
self.checkWholeText(text2, "d")
self.confirm(len(elem.childNodes) == 3)
doc, elem, text1, splitter, text2 = setup()
text = text2.replaceWholeText("new content")
self.checkWholeText(text, "new content")
self.checkWholeText(text1, "cab")
self.confirm(len(elem.childNodes) == 5)
doc, elem, text1, splitter, text2 = setup()
text = text1.replaceWholeText("")
self.checkWholeText(text2, "d")
self.confirm(text is None
and len(elem.childNodes) == 2)
def testSchemaType(self):
doc = parseString(
"<!DOCTYPE doc [\n"
" <!ENTITY e1 SYSTEM 'http://xml.python.org/e1'>\n"
" <!ENTITY e2 SYSTEM 'http://xml.python.org/e2'>\n"
" <!ATTLIST doc id ID #IMPLIED \n"
" ref IDREF #IMPLIED \n"
" refs IDREFS #IMPLIED \n"
" enum (a|b) #IMPLIED \n"
" ent ENTITY #IMPLIED \n"
" ents ENTITIES #IMPLIED \n"
" nm NMTOKEN #IMPLIED \n"
" nms NMTOKENS #IMPLIED \n"
" text CDATA #IMPLIED \n"
" >\n"
"]><doc id='name' notid='name' text='splat!' enum='b'"
" ref='name' refs='name name' ent='e1' ents='e1 e2'"
" nm='123' nms='123 abc' />")
elem = doc.documentElement
# We don't want to rely on any specific loader at this point, so
# just make sure we can get to all the names, and that the
# DTD-based namespace is right. The names can vary by loader
# since each supports a different level of DTD information.
t = elem.schemaType
self.confirm(t.name is None
and t.namespace == xml.dom.EMPTY_NAMESPACE)
names = "id notid text enum ref refs ent ents nm nms".split()
for name in names:
a = elem.getAttributeNode(name)
t = a.schemaType
self.confirm(hasattr(t, "name")
and t.namespace == xml.dom.EMPTY_NAMESPACE)
def testSetIdAttribute(self):
doc = parseString("<doc a1='v' a2='w'/>")
e = doc.documentElement
a1 = e.getAttributeNode("a1")
a2 = e.getAttributeNode("a2")
self.confirm(doc.getElementById("v") is None
and not a1.isId
and not a2.isId)
e.setIdAttribute("a1")
self.confirm(e.isSameNode(doc.getElementById("v"))
and a1.isId
and not a2.isId)
e.setIdAttribute("a2")
self.confirm(e.isSameNode(doc.getElementById("v"))
and e.isSameNode(doc.getElementById("w"))
and a1.isId
and a2.isId)
# replace the a1 node; the new node should *not* be an ID
a3 = doc.createAttribute("a1")
a3.value = "v"
e.setAttributeNode(a3)
self.confirm(doc.getElementById("v") is None
and e.isSameNode(doc.getElementById("w"))
and not a1.isId
and a2.isId
and not a3.isId)
# renaming an attribute should not affect its ID-ness:
doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
self.confirm(e.isSameNode(doc.getElementById("w"))
and a2.isId)
def testSetIdAttributeNS(self):
NS1 = "http://xml.python.org/ns1"
NS2 = "http://xml.python.org/ns2"
doc = parseString("<doc"
" xmlns:ns1='" + NS1 + "'"
" xmlns:ns2='" + NS2 + "'"
" ns1:a1='v' ns2:a2='w'/>")
e = doc.documentElement
a1 = e.getAttributeNodeNS(NS1, "a1")
a2 = e.getAttributeNodeNS(NS2, "a2")
self.confirm(doc.getElementById("v") is None
and not a1.isId
and not a2.isId)
e.setIdAttributeNS(NS1, "a1")
self.confirm(e.isSameNode(doc.getElementById("v"))
and a1.isId
and not a2.isId)
e.setIdAttributeNS(NS2, "a2")
self.confirm(e.isSameNode(doc.getElementById("v"))
and e.isSameNode(doc.getElementById("w"))
and a1.isId
and a2.isId)
# replace the a1 node; the new node should *not* be an ID
a3 = doc.createAttributeNS(NS1, "a1")
a3.value = "v"
e.setAttributeNode(a3)
self.confirm(e.isSameNode(doc.getElementById("w")))
self.confirm(not a1.isId)
self.confirm(a2.isId)
self.confirm(not a3.isId)
self.confirm(doc.getElementById("v") is None)
# renaming an attribute should not affect its ID-ness:
doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
self.confirm(e.isSameNode(doc.getElementById("w"))
and a2.isId)
def testSetIdAttributeNode(self):
NS1 = "http://xml.python.org/ns1"
NS2 = "http://xml.python.org/ns2"
doc = parseString("<doc"
" xmlns:ns1='" + NS1 + "'"
" xmlns:ns2='" + NS2 + "'"
" ns1:a1='v' ns2:a2='w'/>")
e = doc.documentElement
a1 = e.getAttributeNodeNS(NS1, "a1")
a2 = e.getAttributeNodeNS(NS2, "a2")
self.confirm(doc.getElementById("v") is None
and not a1.isId
and not a2.isId)
e.setIdAttributeNode(a1)
self.confirm(e.isSameNode(doc.getElementById("v"))
and a1.isId
and not a2.isId)
e.setIdAttributeNode(a2)
self.confirm(e.isSameNode(doc.getElementById("v"))
and e.isSameNode(doc.getElementById("w"))
and a1.isId
and a2.isId)
# replace the a1 node; the new node should *not* be an ID
a3 = doc.createAttributeNS(NS1, "a1")
a3.value = "v"
e.setAttributeNode(a3)
self.confirm(e.isSameNode(doc.getElementById("w")))
self.confirm(not a1.isId)
self.confirm(a2.isId)
self.confirm(not a3.isId)
self.confirm(doc.getElementById("v") is None)
# renaming an attribute should not affect its ID-ness:
doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
self.confirm(e.isSameNode(doc.getElementById("w"))
and a2.isId)
def assert_recursive_equal(self, doc, doc2):
stack = [(doc, doc2)]
while stack:
n1, n2 = stack.pop()
self.assertEqual(n1.nodeType, n2.nodeType)
self.assertEqual(len(n1.childNodes), len(n2.childNodes))
self.assertEqual(n1.nodeName, n2.nodeName)
self.assertFalse(n1.isSameNode(n2))
self.assertFalse(n2.isSameNode(n1))
if n1.nodeType == Node.DOCUMENT_TYPE_NODE:
len(n1.entities)
len(n2.entities)
len(n1.notations)
len(n2.notations)
self.assertEqual(len(n1.entities), len(n2.entities))
self.assertEqual(len(n1.notations), len(n2.notations))
for i in range(len(n1.notations)):
# XXX this loop body doesn't seem to be executed?
no1 = n1.notations.item(i)
no2 = n1.notations.item(i)
self.assertEqual(no1.name, no2.name)
self.assertEqual(no1.publicId, no2.publicId)
self.assertEqual(no1.systemId, no2.systemId)
stack.append((no1, no2))
for i in range(len(n1.entities)):
e1 = n1.entities.item(i)
e2 = n2.entities.item(i)
self.assertEqual(e1.notationName, e2.notationName)
self.assertEqual(e1.publicId, e2.publicId)
self.assertEqual(e1.systemId, e2.systemId)
stack.append((e1, e2))
if n1.nodeType != Node.DOCUMENT_NODE:
self.assertTrue(n1.ownerDocument.isSameNode(doc))
self.assertTrue(n2.ownerDocument.isSameNode(doc2))
for i in range(len(n1.childNodes)):
stack.append((n1.childNodes[i], n2.childNodes[i]))
def testPickledDocument(self):
doc = parseString(sample)
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
s = pickle.dumps(doc, proto)
doc2 = pickle.loads(s)
self.assert_recursive_equal(doc, doc2)
def testDeepcopiedDocument(self):
doc = parseString(sample)
doc2 = copy.deepcopy(doc)
self.assert_recursive_equal(doc, doc2)
def testSerializeCommentNodeWithDoubleHyphen(self):
doc = create_doc_without_doctype()
doc.appendChild(doc.createComment("foo--bar"))
self.assertRaises(ValueError, doc.toxml)
def testEmptyXMLNSValue(self):
doc = parseString("<element xmlns=''>\n"
"<foo/>\n</element>")
doc2 = parseString(doc.toxml())
self.confirm(doc2.namespaceURI == xml.dom.EMPTY_NAMESPACE)
def testExceptionOnSpacesInXMLNSValue(self):
with self.assertRaisesRegex(ValueError, 'Unsupported syntax'):
parseString('<element xmlns:abc="http:abc.com/de f g/hi/j k"><abc:foo /></element>')
def testDocRemoveChild(self):
doc = parse(tstfile)
title_tag = doc.documentElement.getElementsByTagName("TITLE")[0]
self.assertRaises( xml.dom.NotFoundErr, doc.removeChild, title_tag)
num_children_before = len(doc.childNodes)
doc.removeChild(doc.childNodes[0])
num_children_after = len(doc.childNodes)
self.assertTrue(num_children_after == num_children_before - 1)
def testProcessingInstructionNameError(self):
# wrong variable in .nodeValue property will
# lead to "NameError: name 'data' is not defined"
doc = parse(tstfile)
pi = doc.createProcessingInstruction("y", "z")
pi.nodeValue = "crash"
if __name__ == "__main__":
unittest.main()
| 67,356 | 1,627 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_finalization.py | """
Tests for object finalization semantics, as outlined in PEP 442.
"""
import contextlib
import gc
import unittest
import weakref
try:
from _testcapi import with_tp_del
except ImportError:
def with_tp_del(cls):
class C(object):
def __new__(cls, *args, **kwargs):
raise TypeError('requires _testcapi.with_tp_del')
return C
from test import support
class NonGCSimpleBase:
"""
The base class for all the objects under test, equipped with various
testing features.
"""
survivors = []
del_calls = []
tp_del_calls = []
errors = []
_cleaning = False
__slots__ = ()
@classmethod
def _cleanup(cls):
cls.survivors.clear()
cls.errors.clear()
gc.garbage.clear()
gc.collect()
cls.del_calls.clear()
cls.tp_del_calls.clear()
@classmethod
@contextlib.contextmanager
def test(cls):
"""
A context manager to use around all finalization tests.
"""
with support.disable_gc():
cls.del_calls.clear()
cls.tp_del_calls.clear()
NonGCSimpleBase._cleaning = False
try:
yield
if cls.errors:
raise cls.errors[0]
finally:
NonGCSimpleBase._cleaning = True
cls._cleanup()
def check_sanity(self):
"""
Check the object is sane (non-broken).
"""
def __del__(self):
"""
PEP 442 finalizer. Record that this was called, check the
object is in a sane state, and invoke a side effect.
"""
try:
if not self._cleaning:
self.del_calls.append(id(self))
self.check_sanity()
self.side_effect()
except Exception as e:
self.errors.append(e)
def side_effect(self):
"""
A side effect called on destruction.
"""
class SimpleBase(NonGCSimpleBase):
def __init__(self):
self.id_ = id(self)
def check_sanity(self):
assert self.id_ == id(self)
class NonGC(NonGCSimpleBase):
__slots__ = ()
class NonGCResurrector(NonGCSimpleBase):
__slots__ = ()
def side_effect(self):
"""
Resurrect self by storing self in a class-wide list.
"""
self.survivors.append(self)
class Simple(SimpleBase):
pass
class SimpleResurrector(NonGCResurrector, SimpleBase):
pass
class TestBase:
def setUp(self):
self.old_garbage = gc.garbage[:]
gc.garbage[:] = []
def tearDown(self):
# None of the tests here should put anything in gc.garbage
try:
self.assertEqual(gc.garbage, [])
finally:
del self.old_garbage
gc.collect()
def assert_del_calls(self, ids):
self.assertEqual(sorted(SimpleBase.del_calls), sorted(ids))
def assert_tp_del_calls(self, ids):
self.assertEqual(sorted(SimpleBase.tp_del_calls), sorted(ids))
def assert_survivors(self, ids):
self.assertEqual(sorted(id(x) for x in SimpleBase.survivors), sorted(ids))
def assert_garbage(self, ids):
self.assertEqual(sorted(id(x) for x in gc.garbage), sorted(ids))
def clear_survivors(self):
SimpleBase.survivors.clear()
class SimpleFinalizationTest(TestBase, unittest.TestCase):
"""
Test finalization without refcycles.
"""
def test_simple(self):
with SimpleBase.test():
s = Simple()
ids = [id(s)]
wr = weakref.ref(s)
del s
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors([])
self.assertIs(wr(), None)
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors([])
def test_simple_resurrect(self):
with SimpleBase.test():
s = SimpleResurrector()
ids = [id(s)]
wr = weakref.ref(s)
del s
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors(ids)
self.assertIsNot(wr(), None)
self.clear_survivors()
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors([])
self.assertIs(wr(), None)
def test_non_gc(self):
with SimpleBase.test():
s = NonGC()
self.assertFalse(gc.is_tracked(s))
ids = [id(s)]
del s
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors([])
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors([])
def test_non_gc_resurrect(self):
with SimpleBase.test():
s = NonGCResurrector()
self.assertFalse(gc.is_tracked(s))
ids = [id(s)]
del s
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors(ids)
self.clear_survivors()
gc.collect()
self.assert_del_calls(ids * 2)
self.assert_survivors(ids)
class SelfCycleBase:
def __init__(self):
super().__init__()
self.ref = self
def check_sanity(self):
super().check_sanity()
assert self.ref is self
class SimpleSelfCycle(SelfCycleBase, Simple):
pass
class SelfCycleResurrector(SelfCycleBase, SimpleResurrector):
pass
class SuicidalSelfCycle(SelfCycleBase, Simple):
def side_effect(self):
"""
Explicitly break the reference cycle.
"""
self.ref = None
class SelfCycleFinalizationTest(TestBase, unittest.TestCase):
"""
Test finalization of an object having a single cyclic reference to
itself.
"""
def test_simple(self):
with SimpleBase.test():
s = SimpleSelfCycle()
ids = [id(s)]
wr = weakref.ref(s)
del s
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors([])
self.assertIs(wr(), None)
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors([])
def test_simple_resurrect(self):
# Test that __del__ can resurrect the object being finalized.
with SimpleBase.test():
s = SelfCycleResurrector()
ids = [id(s)]
wr = weakref.ref(s)
del s
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors(ids)
# XXX is this desirable?
self.assertIs(wr(), None)
# When trying to destroy the object a second time, __del__
# isn't called anymore (and the object isn't resurrected).
self.clear_survivors()
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors([])
self.assertIs(wr(), None)
def test_simple_suicide(self):
# Test the GC is able to deal with an object that kills its last
# reference during __del__.
with SimpleBase.test():
s = SuicidalSelfCycle()
ids = [id(s)]
wr = weakref.ref(s)
del s
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors([])
self.assertIs(wr(), None)
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors([])
self.assertIs(wr(), None)
class ChainedBase:
def chain(self, left):
self.suicided = False
self.left = left
left.right = self
def check_sanity(self):
super().check_sanity()
if self.suicided:
assert self.left is None
assert self.right is None
else:
left = self.left
if left.suicided:
assert left.right is None
else:
assert left.right is self
right = self.right
if right.suicided:
assert right.left is None
else:
assert right.left is self
class SimpleChained(ChainedBase, Simple):
pass
class ChainedResurrector(ChainedBase, SimpleResurrector):
pass
class SuicidalChained(ChainedBase, Simple):
def side_effect(self):
"""
Explicitly break the reference cycle.
"""
self.suicided = True
self.left = None
self.right = None
class CycleChainFinalizationTest(TestBase, unittest.TestCase):
"""
Test finalization of a cyclic chain. These tests are similar in
spirit to the self-cycle tests above, but the collectable object
graph isn't trivial anymore.
"""
def build_chain(self, classes):
nodes = [cls() for cls in classes]
for i in range(len(nodes)):
nodes[i].chain(nodes[i-1])
return nodes
def check_non_resurrecting_chain(self, classes):
N = len(classes)
with SimpleBase.test():
nodes = self.build_chain(classes)
ids = [id(s) for s in nodes]
wrs = [weakref.ref(s) for s in nodes]
del nodes
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors([])
self.assertEqual([wr() for wr in wrs], [None] * N)
gc.collect()
self.assert_del_calls(ids)
def check_resurrecting_chain(self, classes):
N = len(classes)
with SimpleBase.test():
nodes = self.build_chain(classes)
N = len(nodes)
ids = [id(s) for s in nodes]
survivor_ids = [id(s) for s in nodes if isinstance(s, SimpleResurrector)]
wrs = [weakref.ref(s) for s in nodes]
del nodes
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors(survivor_ids)
# XXX desirable?
self.assertEqual([wr() for wr in wrs], [None] * N)
self.clear_survivors()
gc.collect()
self.assert_del_calls(ids)
self.assert_survivors([])
def test_homogenous(self):
self.check_non_resurrecting_chain([SimpleChained] * 3)
def test_homogenous_resurrect(self):
self.check_resurrecting_chain([ChainedResurrector] * 3)
def test_homogenous_suicidal(self):
self.check_non_resurrecting_chain([SuicidalChained] * 3)
def test_heterogenous_suicidal_one(self):
self.check_non_resurrecting_chain([SuicidalChained, SimpleChained] * 2)
def test_heterogenous_suicidal_two(self):
self.check_non_resurrecting_chain(
[SuicidalChained] * 2 + [SimpleChained] * 2)
def test_heterogenous_resurrect_one(self):
self.check_resurrecting_chain([ChainedResurrector, SimpleChained] * 2)
def test_heterogenous_resurrect_two(self):
self.check_resurrecting_chain(
[ChainedResurrector, SimpleChained, SuicidalChained] * 2)
def test_heterogenous_resurrect_three(self):
self.check_resurrecting_chain(
[ChainedResurrector] * 2 + [SimpleChained] * 2 + [SuicidalChained] * 2)
# NOTE: the tp_del slot isn't automatically inherited, so we have to call
# with_tp_del() for each instantiated class.
class LegacyBase(SimpleBase):
def __del__(self):
try:
# Do not invoke side_effect here, since we are now exercising
# the tp_del slot.
if not self._cleaning:
self.del_calls.append(id(self))
self.check_sanity()
except Exception as e:
self.errors.append(e)
def __tp_del__(self):
"""
Legacy (pre-PEP 442) finalizer, mapped to a tp_del slot.
"""
try:
if not self._cleaning:
self.tp_del_calls.append(id(self))
self.check_sanity()
self.side_effect()
except Exception as e:
self.errors.append(e)
@with_tp_del
class Legacy(LegacyBase):
pass
@with_tp_del
class LegacyResurrector(LegacyBase):
def side_effect(self):
"""
Resurrect self by storing self in a class-wide list.
"""
self.survivors.append(self)
@with_tp_del
class LegacySelfCycle(SelfCycleBase, LegacyBase):
pass
@support.cpython_only
class LegacyFinalizationTest(TestBase, unittest.TestCase):
"""
Test finalization of objects with a tp_del.
"""
def tearDown(self):
# These tests need to clean up a bit more, since they create
# uncollectable objects.
gc.garbage.clear()
gc.collect()
super().tearDown()
def test_legacy(self):
with SimpleBase.test():
s = Legacy()
ids = [id(s)]
wr = weakref.ref(s)
del s
gc.collect()
self.assert_del_calls(ids)
self.assert_tp_del_calls(ids)
self.assert_survivors([])
self.assertIs(wr(), None)
gc.collect()
self.assert_del_calls(ids)
self.assert_tp_del_calls(ids)
def test_legacy_resurrect(self):
with SimpleBase.test():
s = LegacyResurrector()
ids = [id(s)]
wr = weakref.ref(s)
del s
gc.collect()
self.assert_del_calls(ids)
self.assert_tp_del_calls(ids)
self.assert_survivors(ids)
# weakrefs are cleared before tp_del is called.
self.assertIs(wr(), None)
self.clear_survivors()
gc.collect()
self.assert_del_calls(ids)
self.assert_tp_del_calls(ids * 2)
self.assert_survivors(ids)
self.assertIs(wr(), None)
def test_legacy_self_cycle(self):
# Self-cycles with legacy finalizers end up in gc.garbage.
with SimpleBase.test():
s = LegacySelfCycle()
ids = [id(s)]
wr = weakref.ref(s)
del s
gc.collect()
self.assert_del_calls([])
self.assert_tp_del_calls([])
self.assert_survivors([])
self.assert_garbage(ids)
self.assertIsNot(wr(), None)
# Break the cycle to allow collection
gc.garbage[0].ref = None
self.assert_garbage([])
self.assertIs(wr(), None)
if __name__ == "__main__":
unittest.main()
| 14,502 | 520 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_collections.py | """Unit tests for collections.py."""
import collections
import copy
import doctest
import inspect
import keyword
import operator
import pickle
from random import choice, randrange
import re
import string
import sys
from test import support
import types
import unittest
from collections import namedtuple, Counter, OrderedDict, _count_elements
from collections import UserDict, UserString, UserList
from collections import ChainMap
from collections import deque
from collections.abc import Awaitable, Coroutine
from collections.abc import AsyncIterator, AsyncIterable, AsyncGenerator
from collections.abc import Hashable, Iterable, Iterator, Generator, Reversible
from collections.abc import Sized, Container, Callable, Collection
from collections.abc import Set, MutableSet
from collections.abc import Mapping, MutableMapping, KeysView, ItemsView, ValuesView
from collections.abc import Sequence, MutableSequence
from collections.abc import ByteString
class TestUserObjects(unittest.TestCase):
def _superset_test(self, a, b):
self.assertGreaterEqual(
set(dir(a)),
set(dir(b)),
'{a} should have all the methods of {b}'.format(
a=a.__name__,
b=b.__name__,
),
)
def test_str_protocol(self):
self._superset_test(UserString, str)
def test_list_protocol(self):
self._superset_test(UserList, list)
def test_dict_protocol(self):
self._superset_test(UserDict, dict)
################################################################################
### ChainMap (helper class for configparser and the string module)
################################################################################
class TestChainMap(unittest.TestCase):
def test_basics(self):
c = ChainMap()
c['a'] = 1
c['b'] = 2
d = c.new_child()
d['b'] = 20
d['c'] = 30
self.assertEqual(d.maps, [{'b':20, 'c':30}, {'a':1, 'b':2}]) # check internal state
self.assertEqual(d.items(), dict(a=1, b=20, c=30).items()) # check items/iter/getitem
self.assertEqual(len(d), 3) # check len
for key in 'abc': # check contains
self.assertIn(key, d)
for k, v in dict(a=1, b=20, c=30, z=100).items(): # check get
self.assertEqual(d.get(k, 100), v)
del d['b'] # unmask a value
self.assertEqual(d.maps, [{'c':30}, {'a':1, 'b':2}]) # check internal state
self.assertEqual(d.items(), dict(a=1, b=2, c=30).items()) # check items/iter/getitem
self.assertEqual(len(d), 3) # check len
for key in 'abc': # check contains
self.assertIn(key, d)
for k, v in dict(a=1, b=2, c=30, z=100).items(): # check get
self.assertEqual(d.get(k, 100), v)
self.assertIn(repr(d), [ # check repr
type(d).__name__ + "({'c': 30}, {'a': 1, 'b': 2})",
type(d).__name__ + "({'c': 30}, {'b': 2, 'a': 1})"
])
for e in d.copy(), copy.copy(d): # check shallow copies
self.assertEqual(d, e)
self.assertEqual(d.maps, e.maps)
self.assertIsNot(d, e)
self.assertIsNot(d.maps[0], e.maps[0])
for m1, m2 in zip(d.maps[1:], e.maps[1:]):
self.assertIs(m1, m2)
# check deep copies
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
e = pickle.loads(pickle.dumps(d, proto))
self.assertEqual(d, e)
self.assertEqual(d.maps, e.maps)
self.assertIsNot(d, e)
for m1, m2 in zip(d.maps, e.maps):
self.assertIsNot(m1, m2, e)
for e in [copy.deepcopy(d),
eval(repr(d))
]:
self.assertEqual(d, e)
self.assertEqual(d.maps, e.maps)
self.assertIsNot(d, e)
for m1, m2 in zip(d.maps, e.maps):
self.assertIsNot(m1, m2, e)
f = d.new_child()
f['b'] = 5
self.assertEqual(f.maps, [{'b': 5}, {'c':30}, {'a':1, 'b':2}])
self.assertEqual(f.parents.maps, [{'c':30}, {'a':1, 'b':2}]) # check parents
self.assertEqual(f['b'], 5) # find first in chain
self.assertEqual(f.parents['b'], 2) # look beyond maps[0]
def test_constructor(self):
self.assertEqual(ChainMap().maps, [{}]) # no-args --> one new dict
self.assertEqual(ChainMap({1:2}).maps, [{1:2}]) # 1 arg --> list
def test_bool(self):
self.assertFalse(ChainMap())
self.assertFalse(ChainMap({}, {}))
self.assertTrue(ChainMap({1:2}, {}))
self.assertTrue(ChainMap({}, {1:2}))
def test_missing(self):
class DefaultChainMap(ChainMap):
def __missing__(self, key):
return 999
d = DefaultChainMap(dict(a=1, b=2), dict(b=20, c=30))
for k, v in dict(a=1, b=2, c=30, d=999).items():
self.assertEqual(d[k], v) # check __getitem__ w/missing
for k, v in dict(a=1, b=2, c=30, d=77).items():
self.assertEqual(d.get(k, 77), v) # check get() w/ missing
for k, v in dict(a=True, b=True, c=True, d=False).items():
self.assertEqual(k in d, v) # check __contains__ w/missing
self.assertEqual(d.pop('a', 1001), 1, d)
self.assertEqual(d.pop('a', 1002), 1002) # check pop() w/missing
self.assertEqual(d.popitem(), ('b', 2)) # check popitem() w/missing
with self.assertRaises(KeyError):
d.popitem()
def test_dict_coercion(self):
d = ChainMap(dict(a=1, b=2), dict(b=20, c=30))
self.assertEqual(dict(d), dict(a=1, b=2, c=30))
self.assertEqual(dict(d.items()), dict(a=1, b=2, c=30))
def test_new_child(self):
'Tests for changes for issue #16613.'
c = ChainMap()
c['a'] = 1
c['b'] = 2
m = {'b':20, 'c': 30}
d = c.new_child(m)
self.assertEqual(d.maps, [{'b':20, 'c':30}, {'a':1, 'b':2}]) # check internal state
self.assertIs(m, d.maps[0])
# Use a different map than a dict
class lowerdict(dict):
def __getitem__(self, key):
if isinstance(key, str):
key = key.lower()
return dict.__getitem__(self, key)
def __contains__(self, key):
if isinstance(key, str):
key = key.lower()
return dict.__contains__(self, key)
c = ChainMap()
c['a'] = 1
c['b'] = 2
m = lowerdict(b=20, c=30)
d = c.new_child(m)
self.assertIs(m, d.maps[0])
for key in 'abc': # check contains
self.assertIn(key, d)
for k, v in dict(a=1, B=20, C=30, z=100).items(): # check get
self.assertEqual(d.get(k, 100), v)
################################################################################
### Named Tuples
################################################################################
TestNT = namedtuple('TestNT', 'x y z') # type used for pickle tests
class TestNamedTuple(unittest.TestCase):
def test_factory(self):
Point = namedtuple('Point', 'x y')
self.assertEqual(Point.__name__, 'Point')
self.assertEqual(Point.__slots__, ())
self.assertEqual(Point.__module__, __name__)
self.assertEqual(Point.__getitem__, tuple.__getitem__)
self.assertEqual(Point._fields, ('x', 'y'))
self.assertIn('class Point(tuple)', Point._source)
self.assertRaises(ValueError, namedtuple, 'abc%', 'efg ghi') # type has non-alpha char
self.assertRaises(ValueError, namedtuple, 'class', 'efg ghi') # type has keyword
self.assertRaises(ValueError, namedtuple, '9abc', 'efg ghi') # type starts with digit
self.assertRaises(ValueError, namedtuple, 'abc', 'efg g%hi') # field with non-alpha char
self.assertRaises(ValueError, namedtuple, 'abc', 'abc class') # field has keyword
self.assertRaises(ValueError, namedtuple, 'abc', '8efg 9ghi') # field starts with digit
self.assertRaises(ValueError, namedtuple, 'abc', '_efg ghi') # field with leading underscore
self.assertRaises(ValueError, namedtuple, 'abc', 'efg efg ghi') # duplicate field
namedtuple('Point0', 'x1 y2') # Verify that numbers are allowed in names
namedtuple('_', 'a b c') # Test leading underscores in a typename
nt = namedtuple('nt', 'the quick brown fox') # check unicode input
self.assertNotIn("u'", repr(nt._fields))
nt = namedtuple('nt', ('the', 'quick')) # check unicode input
self.assertNotIn("u'", repr(nt._fields))
self.assertRaises(TypeError, Point._make, [11]) # catch too few args
self.assertRaises(TypeError, Point._make, [11, 22, 33]) # catch too many args
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
def test_factory_doc_attr(self):
Point = namedtuple('Point', 'x y')
self.assertEqual(Point.__doc__, 'Point(x, y)')
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
def test_doc_writable(self):
Point = namedtuple('Point', 'x y')
self.assertEqual(Point.x.__doc__, 'Alias for field number 0')
Point.x.__doc__ = 'docstring for Point.x'
self.assertEqual(Point.x.__doc__, 'docstring for Point.x')
def test_name_fixer(self):
for spec, renamed in [
[('efg', 'g%hi'), ('efg', '_1')], # field with non-alpha char
[('abc', 'class'), ('abc', '_1')], # field has keyword
[('8efg', '9ghi'), ('_0', '_1')], # field starts with digit
[('abc', '_efg'), ('abc', '_1')], # field with leading underscore
[('abc', 'efg', 'efg', 'ghi'), ('abc', 'efg', '_2', 'ghi')], # duplicate field
[('abc', '', 'x'), ('abc', '_1', 'x')], # fieldname is a space
]:
self.assertEqual(namedtuple('NT', spec, rename=True)._fields, renamed)
def test_module_parameter(self):
NT = namedtuple('NT', ['x', 'y'], module=collections)
self.assertEqual(NT.__module__, collections)
def test_instance(self):
Point = namedtuple('Point', 'x y')
p = Point(11, 22)
self.assertEqual(p, Point(x=11, y=22))
self.assertEqual(p, Point(11, y=22))
self.assertEqual(p, Point(y=22, x=11))
self.assertEqual(p, Point(*(11, 22)))
self.assertEqual(p, Point(**dict(x=11, y=22)))
self.assertRaises(TypeError, Point, 1) # too few args
self.assertRaises(TypeError, Point, 1, 2, 3) # too many args
self.assertRaises(TypeError, eval, 'Point(XXX=1, y=2)', locals()) # wrong keyword argument
self.assertRaises(TypeError, eval, 'Point(x=1)', locals()) # missing keyword argument
self.assertEqual(repr(p), 'Point(x=11, y=22)')
self.assertNotIn('__weakref__', dir(p))
self.assertEqual(p, Point._make([11, 22])) # test _make classmethod
self.assertEqual(p._fields, ('x', 'y')) # test _fields attribute
self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method
self.assertEqual(p._asdict(), dict(x=11, y=22)) # test _asdict method
try:
p._replace(x=1, error=2)
except ValueError:
pass
else:
self._fail('Did not detect an incorrect fieldname')
# verify that field string can have commas
Point = namedtuple('Point', 'x, y')
p = Point(x=11, y=22)
self.assertEqual(repr(p), 'Point(x=11, y=22)')
# verify that fieldspec can be a non-string sequence
Point = namedtuple('Point', ('x', 'y'))
p = Point(x=11, y=22)
self.assertEqual(repr(p), 'Point(x=11, y=22)')
def test_tupleness(self):
Point = namedtuple('Point', 'x y')
p = Point(11, 22)
self.assertIsInstance(p, tuple)
self.assertEqual(p, (11, 22)) # matches a real tuple
self.assertEqual(tuple(p), (11, 22)) # coercable to a real tuple
self.assertEqual(list(p), [11, 22]) # coercable to a list
self.assertEqual(max(p), 22) # iterable
self.assertEqual(max(*p), 22) # star-able
x, y = p
self.assertEqual(p, (x, y)) # unpacks like a tuple
self.assertEqual((p[0], p[1]), (11, 22)) # indexable like a tuple
self.assertRaises(IndexError, p.__getitem__, 3)
self.assertEqual(p.x, x)
self.assertEqual(p.y, y)
self.assertRaises(AttributeError, eval, 'p.z', locals())
def test_odd_sizes(self):
Zero = namedtuple('Zero', '')
self.assertEqual(Zero(), ())
self.assertEqual(Zero._make([]), ())
self.assertEqual(repr(Zero()), 'Zero()')
self.assertEqual(Zero()._asdict(), {})
self.assertEqual(Zero()._fields, ())
Dot = namedtuple('Dot', 'd')
self.assertEqual(Dot(1), (1,))
self.assertEqual(Dot._make([1]), (1,))
self.assertEqual(Dot(1).d, 1)
self.assertEqual(repr(Dot(1)), 'Dot(d=1)')
self.assertEqual(Dot(1)._asdict(), {'d':1})
self.assertEqual(Dot(1)._replace(d=999), (999,))
self.assertEqual(Dot(1)._fields, ('d',))
# n = 5000
n = 254 # SyntaxError: more than 255 arguments:
names = list(set(''.join([choice(string.ascii_letters)
for j in range(10)]) for i in range(n)))
n = len(names)
Big = namedtuple('Big', names)
b = Big(*range(n))
self.assertEqual(b, tuple(range(n)))
self.assertEqual(Big._make(range(n)), tuple(range(n)))
for pos, name in enumerate(names):
self.assertEqual(getattr(b, name), pos)
repr(b) # make sure repr() doesn't blow-up
d = b._asdict()
d_expected = dict(zip(names, range(n)))
self.assertEqual(d, d_expected)
b2 = b._replace(**dict([(names[1], 999),(names[-5], 42)]))
b2_expected = list(range(n))
b2_expected[1] = 999
b2_expected[-5] = 42
self.assertEqual(b2, tuple(b2_expected))
self.assertEqual(b._fields, tuple(names))
def test_pickle(self):
p = TestNT(x=10, y=20, z=30)
for module in (pickle,):
loads = getattr(module, 'loads')
dumps = getattr(module, 'dumps')
for protocol in range(-1, module.HIGHEST_PROTOCOL + 1):
q = loads(dumps(p, protocol))
self.assertEqual(p, q)
self.assertEqual(p._fields, q._fields)
self.assertNotIn(b'OrderedDict', dumps(p, protocol))
def test_copy(self):
p = TestNT(x=10, y=20, z=30)
for copier in copy.copy, copy.deepcopy:
q = copier(p)
self.assertEqual(p, q)
self.assertEqual(p._fields, q._fields)
def test_name_conflicts(self):
# Some names like "self", "cls", "tuple", "itemgetter", and "property"
# failed when used as field names. Test to make sure these now work.
T = namedtuple('T', 'itemgetter property self cls tuple')
t = T(1, 2, 3, 4, 5)
self.assertEqual(t, (1,2,3,4,5))
newt = t._replace(itemgetter=10, property=20, self=30, cls=40, tuple=50)
self.assertEqual(newt, (10,20,30,40,50))
# Broader test of all interesting names in a template
with support.captured_stdout() as template:
T = namedtuple('T', 'x', verbose=True)
words = set(re.findall('[A-Za-z]+', template.getvalue()))
words -= set(keyword.kwlist)
T = namedtuple('T', words)
# test __new__
values = tuple(range(len(words)))
t = T(*values)
self.assertEqual(t, values)
t = T(**dict(zip(T._fields, values)))
self.assertEqual(t, values)
# test _make
t = T._make(values)
self.assertEqual(t, values)
# exercise __repr__
repr(t)
# test _asdict
self.assertEqual(t._asdict(), dict(zip(T._fields, values)))
# test _replace
t = T._make(values)
newvalues = tuple(v*10 for v in values)
newt = t._replace(**dict(zip(T._fields, newvalues)))
self.assertEqual(newt, newvalues)
# test _fields
self.assertEqual(T._fields, tuple(words))
# test __getnewargs__
self.assertEqual(t.__getnewargs__(), values)
def test_repr(self):
with support.captured_stdout() as template:
A = namedtuple('A', 'x', verbose=True)
self.assertEqual(repr(A(1)), 'A(x=1)')
# repr should show the name of the subclass
class B(A):
pass
self.assertEqual(repr(B(1)), 'B(x=1)')
def test_source(self):
# verify that _source can be run through exec()
tmp = namedtuple('NTColor', 'red green blue')
globals().pop('NTColor', None) # remove artifacts from other tests
exec(tmp._source, globals())
self.assertIn('NTColor', globals())
c = NTColor(10, 20, 30)
self.assertEqual((c.red, c.green, c.blue), (10, 20, 30))
self.assertEqual(NTColor._fields, ('red', 'green', 'blue'))
globals().pop('NTColor', None) # clean-up after this test
def test_keyword_only_arguments(self):
# See issue 25628
with support.captured_stdout() as template:
NT = namedtuple('NT', ['x', 'y'], verbose=True)
self.assertIn('class NT', NT._source)
with self.assertRaises(TypeError):
NT = namedtuple('NT', ['x', 'y'], True)
NT = namedtuple('NT', ['abc', 'def'], rename=True)
self.assertEqual(NT._fields, ('abc', '_1'))
with self.assertRaises(TypeError):
NT = namedtuple('NT', ['abc', 'def'], False, True)
def test_namedtuple_subclass_issue_24931(self):
class Point(namedtuple('_Point', ['x', 'y'])):
pass
a = Point(3, 4)
self.assertEqual(a._asdict(), OrderedDict([('x', 3), ('y', 4)]))
a.w = 5
self.assertEqual(a.__dict__, {'w': 5})
################################################################################
### Abstract Base Classes
################################################################################
class ABCTestCase(unittest.TestCase):
def validate_abstract_methods(self, abc, *names):
methodstubs = dict.fromkeys(names, lambda s, *args: 0)
# everything should work will all required methods are present
C = type('C', (abc,), methodstubs)
C()
# instantiation should fail if a required method is missing
for name in names:
stubs = methodstubs.copy()
del stubs[name]
C = type('C', (abc,), stubs)
self.assertRaises(TypeError, C, name)
def validate_isinstance(self, abc, name):
stub = lambda s, *args: 0
C = type('C', (object,), {'__hash__': None})
setattr(C, name, stub)
self.assertIsInstance(C(), abc)
self.assertTrue(issubclass(C, abc))
C = type('C', (object,), {'__hash__': None})
self.assertNotIsInstance(C(), abc)
self.assertFalse(issubclass(C, abc))
def validate_comparison(self, instance):
ops = ['lt', 'gt', 'le', 'ge', 'ne', 'or', 'and', 'xor', 'sub']
operators = {}
for op in ops:
name = '__' + op + '__'
operators[name] = getattr(operator, name)
class Other:
def __init__(self):
self.right_side = False
def __eq__(self, other):
self.right_side = True
return True
__lt__ = __eq__
__gt__ = __eq__
__le__ = __eq__
__ge__ = __eq__
__ne__ = __eq__
__ror__ = __eq__
__rand__ = __eq__
__rxor__ = __eq__
__rsub__ = __eq__
for name, op in operators.items():
if not hasattr(instance, name):
continue
other = Other()
op(instance, other)
self.assertTrue(other.right_side,'Right side not called for %s.%s'
% (type(instance), name))
def _test_gen():
yield
class TestOneTrickPonyABCs(ABCTestCase):
def test_Awaitable(self):
def gen():
yield
@types.coroutine
def coro():
yield
async def new_coro():
pass
class Bar:
def __await__(self):
yield
class MinimalCoro(Coroutine):
def send(self, value):
return value
def throw(self, typ, val=None, tb=None):
super().throw(typ, val, tb)
def __await__(self):
yield
non_samples = [None, int(), gen(), object()]
for x in non_samples:
self.assertNotIsInstance(x, Awaitable)
self.assertFalse(issubclass(type(x), Awaitable), repr(type(x)))
samples = [Bar(), MinimalCoro()]
for x in samples:
self.assertIsInstance(x, Awaitable)
self.assertTrue(issubclass(type(x), Awaitable))
c = coro()
# Iterable coroutines (generators with CO_ITERABLE_COROUTINE
# flag don't have '__await__' method, hence can't be instances
# of Awaitable. Use inspect.isawaitable to detect them.
self.assertNotIsInstance(c, Awaitable)
c = new_coro()
self.assertIsInstance(c, Awaitable)
c.close() # avoid RuntimeWarning that coro() was not awaited
class CoroLike: pass
Coroutine.register(CoroLike)
self.assertTrue(isinstance(CoroLike(), Awaitable))
self.assertTrue(issubclass(CoroLike, Awaitable))
CoroLike = None
support.gc_collect() # Kill CoroLike to clean-up ABCMeta cache
def test_Coroutine(self):
def gen():
yield
@types.coroutine
def coro():
yield
async def new_coro():
pass
class Bar:
def __await__(self):
yield
class MinimalCoro(Coroutine):
def send(self, value):
return value
def throw(self, typ, val=None, tb=None):
super().throw(typ, val, tb)
def __await__(self):
yield
non_samples = [None, int(), gen(), object(), Bar()]
for x in non_samples:
self.assertNotIsInstance(x, Coroutine)
self.assertFalse(issubclass(type(x), Coroutine), repr(type(x)))
samples = [MinimalCoro()]
for x in samples:
self.assertIsInstance(x, Awaitable)
self.assertTrue(issubclass(type(x), Awaitable))
c = coro()
# Iterable coroutines (generators with CO_ITERABLE_COROUTINE
# flag don't have '__await__' method, hence can't be instances
# of Coroutine. Use inspect.isawaitable to detect them.
self.assertNotIsInstance(c, Coroutine)
c = new_coro()
self.assertIsInstance(c, Coroutine)
c.close() # avoid RuntimeWarning that coro() was not awaited
class CoroLike:
def send(self, value):
pass
def throw(self, typ, val=None, tb=None):
pass
def close(self):
pass
def __await__(self):
pass
self.assertTrue(isinstance(CoroLike(), Coroutine))
self.assertTrue(issubclass(CoroLike, Coroutine))
class CoroLike:
def send(self, value):
pass
def close(self):
pass
def __await__(self):
pass
self.assertFalse(isinstance(CoroLike(), Coroutine))
self.assertFalse(issubclass(CoroLike, Coroutine))
def test_Hashable(self):
# Check some non-hashables
non_samples = [bytearray(), list(), set(), dict()]
for x in non_samples:
self.assertNotIsInstance(x, Hashable)
self.assertFalse(issubclass(type(x), Hashable), repr(type(x)))
# Check some hashables
samples = [None,
int(), float(), complex(),
str(),
tuple(), frozenset(),
int, list, object, type, bytes()
]
for x in samples:
self.assertIsInstance(x, Hashable)
self.assertTrue(issubclass(type(x), Hashable), repr(type(x)))
self.assertRaises(TypeError, Hashable)
# Check direct subclassing
class H(Hashable):
def __hash__(self):
return super().__hash__()
self.assertEqual(hash(H()), 0)
self.assertFalse(issubclass(int, H))
self.validate_abstract_methods(Hashable, '__hash__')
self.validate_isinstance(Hashable, '__hash__')
def test_AsyncIterable(self):
class AI:
async def __aiter__(self):
return self
self.assertTrue(isinstance(AI(), AsyncIterable))
self.assertTrue(issubclass(AI, AsyncIterable))
# Check some non-iterables
non_samples = [None, object, []]
for x in non_samples:
self.assertNotIsInstance(x, AsyncIterable)
self.assertFalse(issubclass(type(x), AsyncIterable), repr(type(x)))
self.validate_abstract_methods(AsyncIterable, '__aiter__')
self.validate_isinstance(AsyncIterable, '__aiter__')
def test_AsyncIterator(self):
class AI:
async def __aiter__(self):
return self
async def __anext__(self):
raise StopAsyncIteration
self.assertTrue(isinstance(AI(), AsyncIterator))
self.assertTrue(issubclass(AI, AsyncIterator))
non_samples = [None, object, []]
# Check some non-iterables
for x in non_samples:
self.assertNotIsInstance(x, AsyncIterator)
self.assertFalse(issubclass(type(x), AsyncIterator), repr(type(x)))
# Similarly to regular iterators (see issue 10565)
class AnextOnly:
async def __anext__(self):
raise StopAsyncIteration
self.assertNotIsInstance(AnextOnly(), AsyncIterator)
self.validate_abstract_methods(AsyncIterator, '__anext__', '__aiter__')
def test_Iterable(self):
# Check some non-iterables
non_samples = [None, 42, 3.14, 1j]
for x in non_samples:
self.assertNotIsInstance(x, Iterable)
self.assertFalse(issubclass(type(x), Iterable), repr(type(x)))
# Check some iterables
samples = [bytes(), str(),
tuple(), list(), set(), frozenset(), dict(),
dict().keys(), dict().items(), dict().values(),
_test_gen(),
(x for x in []),
]
for x in samples:
self.assertIsInstance(x, Iterable)
self.assertTrue(issubclass(type(x), Iterable), repr(type(x)))
# Check direct subclassing
class I(Iterable):
def __iter__(self):
return super().__iter__()
self.assertEqual(list(I()), [])
self.assertFalse(issubclass(str, I))
self.validate_abstract_methods(Iterable, '__iter__')
self.validate_isinstance(Iterable, '__iter__')
# Check None blocking
class It:
def __iter__(self): return iter([])
class ItBlocked(It):
__iter__ = None
self.assertTrue(issubclass(It, Iterable))
self.assertTrue(isinstance(It(), Iterable))
self.assertFalse(issubclass(ItBlocked, Iterable))
self.assertFalse(isinstance(ItBlocked(), Iterable))
def test_Reversible(self):
# Check some non-reversibles
non_samples = [None, 42, 3.14, 1j, dict(), set(), frozenset()]
for x in non_samples:
self.assertNotIsInstance(x, Reversible)
self.assertFalse(issubclass(type(x), Reversible), repr(type(x)))
# Check some non-reversible iterables
non_reversibles = [dict().keys(), dict().items(), dict().values(),
Counter(), Counter().keys(), Counter().items(),
Counter().values(), _test_gen(),
(x for x in []), iter([]), reversed([])]
for x in non_reversibles:
self.assertNotIsInstance(x, Reversible)
self.assertFalse(issubclass(type(x), Reversible), repr(type(x)))
# Check some reversible iterables
samples = [bytes(), str(), tuple(), list(), OrderedDict(),
OrderedDict().keys(), OrderedDict().items(),
OrderedDict().values()]
for x in samples:
self.assertIsInstance(x, Reversible)
self.assertTrue(issubclass(type(x), Reversible), repr(type(x)))
# Check also Mapping, MutableMapping, and Sequence
self.assertTrue(issubclass(Sequence, Reversible), repr(Sequence))
self.assertFalse(issubclass(Mapping, Reversible), repr(Mapping))
self.assertFalse(issubclass(MutableMapping, Reversible), repr(MutableMapping))
# Check direct subclassing
class R(Reversible):
def __iter__(self):
return iter(list())
def __reversed__(self):
return iter(list())
self.assertEqual(list(reversed(R())), [])
self.assertFalse(issubclass(float, R))
self.validate_abstract_methods(Reversible, '__reversed__', '__iter__')
# Check reversible non-iterable (which is not Reversible)
class RevNoIter:
def __reversed__(self): return reversed([])
class RevPlusIter(RevNoIter):
def __iter__(self): return iter([])
self.assertFalse(issubclass(RevNoIter, Reversible))
self.assertFalse(isinstance(RevNoIter(), Reversible))
self.assertTrue(issubclass(RevPlusIter, Reversible))
self.assertTrue(isinstance(RevPlusIter(), Reversible))
# Check None blocking
class Rev:
def __iter__(self): return iter([])
def __reversed__(self): return reversed([])
class RevItBlocked(Rev):
__iter__ = None
class RevRevBlocked(Rev):
__reversed__ = None
self.assertTrue(issubclass(Rev, Reversible))
self.assertTrue(isinstance(Rev(), Reversible))
self.assertFalse(issubclass(RevItBlocked, Reversible))
self.assertFalse(isinstance(RevItBlocked(), Reversible))
self.assertFalse(issubclass(RevRevBlocked, Reversible))
self.assertFalse(isinstance(RevRevBlocked(), Reversible))
def test_Collection(self):
# Check some non-collections
non_collections = [None, 42, 3.14, 1j, lambda x: 2*x]
for x in non_collections:
self.assertNotIsInstance(x, Collection)
self.assertFalse(issubclass(type(x), Collection), repr(type(x)))
# Check some non-collection iterables
non_col_iterables = [_test_gen(), iter(b''), iter(bytearray()),
(x for x in []), dict().values()]
for x in non_col_iterables:
self.assertNotIsInstance(x, Collection)
self.assertFalse(issubclass(type(x), Collection), repr(type(x)))
# Check some collections
samples = [set(), frozenset(), dict(), bytes(), str(), tuple(),
list(), dict().keys(), dict().items()]
for x in samples:
self.assertIsInstance(x, Collection)
self.assertTrue(issubclass(type(x), Collection), repr(type(x)))
# Check also Mapping, MutableMapping, etc.
self.assertTrue(issubclass(Sequence, Collection), repr(Sequence))
self.assertTrue(issubclass(Mapping, Collection), repr(Mapping))
self.assertTrue(issubclass(MutableMapping, Collection),
repr(MutableMapping))
self.assertTrue(issubclass(Set, Collection), repr(Set))
self.assertTrue(issubclass(MutableSet, Collection), repr(MutableSet))
self.assertTrue(issubclass(Sequence, Collection), repr(MutableSet))
# Check direct subclassing
class Col(Collection):
def __iter__(self):
return iter(list())
def __len__(self):
return 0
def __contains__(self, item):
return False
class DerCol(Col): pass
self.assertEqual(list(iter(Col())), [])
self.assertFalse(issubclass(list, Col))
self.assertFalse(issubclass(set, Col))
self.assertFalse(issubclass(float, Col))
self.assertEqual(list(iter(DerCol())), [])
self.assertFalse(issubclass(list, DerCol))
self.assertFalse(issubclass(set, DerCol))
self.assertFalse(issubclass(float, DerCol))
self.validate_abstract_methods(Collection, '__len__', '__iter__',
'__contains__')
# Check sized container non-iterable (which is not Collection) etc.
class ColNoIter:
def __len__(self): return 0
def __contains__(self, item): return False
class ColNoSize:
def __iter__(self): return iter([])
def __contains__(self, item): return False
class ColNoCont:
def __iter__(self): return iter([])
def __len__(self): return 0
self.assertFalse(issubclass(ColNoIter, Collection))
self.assertFalse(isinstance(ColNoIter(), Collection))
self.assertFalse(issubclass(ColNoSize, Collection))
self.assertFalse(isinstance(ColNoSize(), Collection))
self.assertFalse(issubclass(ColNoCont, Collection))
self.assertFalse(isinstance(ColNoCont(), Collection))
# Check None blocking
class SizeBlock:
def __iter__(self): return iter([])
def __contains__(self): return False
__len__ = None
class IterBlock:
def __len__(self): return 0
def __contains__(self): return True
__iter__ = None
self.assertFalse(issubclass(SizeBlock, Collection))
self.assertFalse(isinstance(SizeBlock(), Collection))
self.assertFalse(issubclass(IterBlock, Collection))
self.assertFalse(isinstance(IterBlock(), Collection))
# Check None blocking in subclass
class ColImpl:
def __iter__(self):
return iter(list())
def __len__(self):
return 0
def __contains__(self, item):
return False
class NonCol(ColImpl):
__contains__ = None
self.assertFalse(issubclass(NonCol, Collection))
self.assertFalse(isinstance(NonCol(), Collection))
def test_Iterator(self):
non_samples = [None, 42, 3.14, 1j, b"", "", (), [], {}, set()]
for x in non_samples:
self.assertNotIsInstance(x, Iterator)
self.assertFalse(issubclass(type(x), Iterator), repr(type(x)))
samples = [iter(bytes()), iter(str()),
iter(tuple()), iter(list()), iter(dict()),
iter(set()), iter(frozenset()),
iter(dict().keys()), iter(dict().items()),
iter(dict().values()),
_test_gen(),
(x for x in []),
]
for x in samples:
self.assertIsInstance(x, Iterator)
self.assertTrue(issubclass(type(x), Iterator), repr(type(x)))
self.validate_abstract_methods(Iterator, '__next__', '__iter__')
# Issue 10565
class NextOnly:
def __next__(self):
yield 1
return
self.assertNotIsInstance(NextOnly(), Iterator)
def test_Generator(self):
class NonGen1:
def __iter__(self): return self
def __next__(self): return None
def close(self): pass
def throw(self, typ, val=None, tb=None): pass
class NonGen2:
def __iter__(self): return self
def __next__(self): return None
def close(self): pass
def send(self, value): return value
class NonGen3:
def close(self): pass
def send(self, value): return value
def throw(self, typ, val=None, tb=None): pass
non_samples = [
None, 42, 3.14, 1j, b"", "", (), [], {}, set(),
iter(()), iter([]), NonGen1(), NonGen2(), NonGen3()]
for x in non_samples:
self.assertNotIsInstance(x, Generator)
self.assertFalse(issubclass(type(x), Generator), repr(type(x)))
class Gen:
def __iter__(self): return self
def __next__(self): return None
def close(self): pass
def send(self, value): return value
def throw(self, typ, val=None, tb=None): pass
class MinimalGen(Generator):
def send(self, value):
return value
def throw(self, typ, val=None, tb=None):
super().throw(typ, val, tb)
def gen():
yield 1
samples = [gen(), (lambda: (yield))(), Gen(), MinimalGen()]
for x in samples:
self.assertIsInstance(x, Iterator)
self.assertIsInstance(x, Generator)
self.assertTrue(issubclass(type(x), Generator), repr(type(x)))
self.validate_abstract_methods(Generator, 'send', 'throw')
# mixin tests
mgen = MinimalGen()
self.assertIs(mgen, iter(mgen))
self.assertIs(mgen.send(None), next(mgen))
self.assertEqual(2, mgen.send(2))
self.assertIsNone(mgen.close())
self.assertRaises(ValueError, mgen.throw, ValueError)
self.assertRaisesRegex(ValueError, "^huhu$",
mgen.throw, ValueError, ValueError("huhu"))
self.assertRaises(StopIteration, mgen.throw, StopIteration())
class FailOnClose(Generator):
def send(self, value): return value
def throw(self, *args): raise ValueError
self.assertRaises(ValueError, FailOnClose().close)
class IgnoreGeneratorExit(Generator):
def send(self, value): return value
def throw(self, *args): pass
self.assertRaises(RuntimeError, IgnoreGeneratorExit().close)
def test_AsyncGenerator(self):
class NonAGen1:
def __aiter__(self): return self
def __anext__(self): return None
def aclose(self): pass
def athrow(self, typ, val=None, tb=None): pass
class NonAGen2:
def __aiter__(self): return self
def __anext__(self): return None
def aclose(self): pass
def asend(self, value): return value
class NonAGen3:
def aclose(self): pass
def asend(self, value): return value
def athrow(self, typ, val=None, tb=None): pass
non_samples = [
None, 42, 3.14, 1j, b"", "", (), [], {}, set(),
iter(()), iter([]), NonAGen1(), NonAGen2(), NonAGen3()]
for x in non_samples:
self.assertNotIsInstance(x, AsyncGenerator)
self.assertFalse(issubclass(type(x), AsyncGenerator), repr(type(x)))
class Gen:
def __aiter__(self): return self
async def __anext__(self): return None
async def aclose(self): pass
async def asend(self, value): return value
async def athrow(self, typ, val=None, tb=None): pass
class MinimalAGen(AsyncGenerator):
async def asend(self, value):
return value
async def athrow(self, typ, val=None, tb=None):
await super().athrow(typ, val, tb)
async def gen():
yield 1
samples = [gen(), Gen(), MinimalAGen()]
for x in samples:
self.assertIsInstance(x, AsyncIterator)
self.assertIsInstance(x, AsyncGenerator)
self.assertTrue(issubclass(type(x), AsyncGenerator), repr(type(x)))
self.validate_abstract_methods(AsyncGenerator, 'asend', 'athrow')
def run_async(coro):
result = None
while True:
try:
coro.send(None)
except StopIteration as ex:
result = ex.args[0] if ex.args else None
break
return result
# mixin tests
mgen = MinimalAGen()
self.assertIs(mgen, mgen.__aiter__())
self.assertIs(run_async(mgen.asend(None)), run_async(mgen.__anext__()))
self.assertEqual(2, run_async(mgen.asend(2)))
self.assertIsNone(run_async(mgen.aclose()))
with self.assertRaises(ValueError):
run_async(mgen.athrow(ValueError))
class FailOnClose(AsyncGenerator):
async def asend(self, value): return value
async def athrow(self, *args): raise ValueError
with self.assertRaises(ValueError):
run_async(FailOnClose().aclose())
class IgnoreGeneratorExit(AsyncGenerator):
async def asend(self, value): return value
async def athrow(self, *args): pass
with self.assertRaises(RuntimeError):
run_async(IgnoreGeneratorExit().aclose())
def test_Sized(self):
non_samples = [None, 42, 3.14, 1j,
_test_gen(),
(x for x in []),
]
for x in non_samples:
self.assertNotIsInstance(x, Sized)
self.assertFalse(issubclass(type(x), Sized), repr(type(x)))
samples = [bytes(), str(),
tuple(), list(), set(), frozenset(), dict(),
dict().keys(), dict().items(), dict().values(),
]
for x in samples:
self.assertIsInstance(x, Sized)
self.assertTrue(issubclass(type(x), Sized), repr(type(x)))
self.validate_abstract_methods(Sized, '__len__')
self.validate_isinstance(Sized, '__len__')
def test_Container(self):
non_samples = [None, 42, 3.14, 1j,
_test_gen(),
(x for x in []),
]
for x in non_samples:
self.assertNotIsInstance(x, Container)
self.assertFalse(issubclass(type(x), Container), repr(type(x)))
samples = [bytes(), str(),
tuple(), list(), set(), frozenset(), dict(),
dict().keys(), dict().items(),
]
for x in samples:
self.assertIsInstance(x, Container)
self.assertTrue(issubclass(type(x), Container), repr(type(x)))
self.validate_abstract_methods(Container, '__contains__')
self.validate_isinstance(Container, '__contains__')
def test_Callable(self):
non_samples = [None, 42, 3.14, 1j,
"", b"", (), [], {}, set(),
_test_gen(),
(x for x in []),
]
for x in non_samples:
self.assertNotIsInstance(x, Callable)
self.assertFalse(issubclass(type(x), Callable), repr(type(x)))
samples = [lambda: None,
type, int, object,
len,
list.append, [].append,
]
for x in samples:
self.assertIsInstance(x, Callable)
self.assertTrue(issubclass(type(x), Callable), repr(type(x)))
self.validate_abstract_methods(Callable, '__call__')
self.validate_isinstance(Callable, '__call__')
def test_direct_subclassing(self):
for B in Hashable, Iterable, Iterator, Reversible, Sized, Container, Callable:
class C(B):
pass
self.assertTrue(issubclass(C, B))
self.assertFalse(issubclass(int, C))
def test_registration(self):
for B in Hashable, Iterable, Iterator, Reversible, Sized, Container, Callable:
class C:
__hash__ = None # Make sure it isn't hashable by default
self.assertFalse(issubclass(C, B), B.__name__)
B.register(C)
self.assertTrue(issubclass(C, B))
class WithSet(MutableSet):
def __init__(self, it=()):
self.data = set(it)
def __len__(self):
return len(self.data)
def __iter__(self):
return iter(self.data)
def __contains__(self, item):
return item in self.data
def add(self, item):
self.data.add(item)
def discard(self, item):
self.data.discard(item)
class TestCollectionABCs(ABCTestCase):
# XXX For now, we only test some virtual inheritance properties.
# We should also test the proper behavior of the collection ABCs
# as real base classes or mix-in classes.
def test_Set(self):
for sample in [set, frozenset]:
self.assertIsInstance(sample(), Set)
self.assertTrue(issubclass(sample, Set))
self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__')
class MySet(Set):
def __contains__(self, x):
return False
def __len__(self):
return 0
def __iter__(self):
return iter([])
self.validate_comparison(MySet())
def test_hash_Set(self):
class OneTwoThreeSet(Set):
def __init__(self):
self.contents = [1, 2, 3]
def __contains__(self, x):
return x in self.contents
def __len__(self):
return len(self.contents)
def __iter__(self):
return iter(self.contents)
def __hash__(self):
return self._hash()
a, b = OneTwoThreeSet(), OneTwoThreeSet()
self.assertTrue(hash(a) == hash(b))
def test_isdisjoint_Set(self):
class MySet(Set):
def __init__(self, itr):
self.contents = itr
def __contains__(self, x):
return x in self.contents
def __iter__(self):
return iter(self.contents)
def __len__(self):
return len([x for x in self.contents])
s1 = MySet((1, 2, 3))
s2 = MySet((4, 5, 6))
s3 = MySet((1, 5, 6))
self.assertTrue(s1.isdisjoint(s2))
self.assertFalse(s1.isdisjoint(s3))
def test_equality_Set(self):
class MySet(Set):
def __init__(self, itr):
self.contents = itr
def __contains__(self, x):
return x in self.contents
def __iter__(self):
return iter(self.contents)
def __len__(self):
return len([x for x in self.contents])
s1 = MySet((1,))
s2 = MySet((1, 2))
s3 = MySet((3, 4))
s4 = MySet((3, 4))
self.assertTrue(s2 > s1)
self.assertTrue(s1 < s2)
self.assertFalse(s2 <= s1)
self.assertFalse(s2 <= s3)
self.assertFalse(s1 >= s2)
self.assertEqual(s3, s4)
self.assertNotEqual(s2, s3)
def test_arithmetic_Set(self):
class MySet(Set):
def __init__(self, itr):
self.contents = itr
def __contains__(self, x):
return x in self.contents
def __iter__(self):
return iter(self.contents)
def __len__(self):
return len([x for x in self.contents])
s1 = MySet((1, 2, 3))
s2 = MySet((3, 4, 5))
s3 = s1 & s2
self.assertEqual(s3, MySet((3,)))
def test_MutableSet(self):
self.assertIsInstance(set(), MutableSet)
self.assertTrue(issubclass(set, MutableSet))
self.assertNotIsInstance(frozenset(), MutableSet)
self.assertFalse(issubclass(frozenset, MutableSet))
self.validate_abstract_methods(MutableSet, '__contains__', '__iter__', '__len__',
'add', 'discard')
def test_issue_5647(self):
# MutableSet.__iand__ mutated the set during iteration
s = WithSet('abcd')
s &= WithSet('cdef') # This used to fail
self.assertEqual(set(s), set('cd'))
def test_issue_4920(self):
# MutableSet.pop() method did not work
class MySet(MutableSet):
__slots__=['__s']
def __init__(self,items=None):
if items is None:
items=[]
self.__s=set(items)
def __contains__(self,v):
return v in self.__s
def __iter__(self):
return iter(self.__s)
def __len__(self):
return len(self.__s)
def add(self,v):
result=v not in self.__s
self.__s.add(v)
return result
def discard(self,v):
result=v in self.__s
self.__s.discard(v)
return result
def __repr__(self):
return "MySet(%s)" % repr(list(self))
s = MySet([5,43,2,1])
self.assertEqual(s.pop(), 1)
def test_issue8750(self):
empty = WithSet()
full = WithSet(range(10))
s = WithSet(full)
s -= s
self.assertEqual(s, empty)
s = WithSet(full)
s ^= s
self.assertEqual(s, empty)
s = WithSet(full)
s &= s
self.assertEqual(s, full)
s |= s
self.assertEqual(s, full)
def test_issue16373(self):
# Recursion error comparing comparable and noncomparable
# Set instances
class MyComparableSet(Set):
def __contains__(self, x):
return False
def __len__(self):
return 0
def __iter__(self):
return iter([])
class MyNonComparableSet(Set):
def __contains__(self, x):
return False
def __len__(self):
return 0
def __iter__(self):
return iter([])
def __le__(self, x):
return NotImplemented
def __lt__(self, x):
return NotImplemented
cs = MyComparableSet()
ncs = MyNonComparableSet()
self.assertFalse(ncs < cs)
self.assertTrue(ncs <= cs)
self.assertFalse(ncs > cs)
self.assertTrue(ncs >= cs)
def test_issue26915(self):
# Container membership test should check identity first
class CustomEqualObject:
def __eq__(self, other):
return False
class CustomSequence(Sequence):
def __init__(self, seq):
self._seq = seq
def __getitem__(self, index):
return self._seq[index]
def __len__(self):
return len(self._seq)
nan = float('nan')
obj = CustomEqualObject()
seq = CustomSequence([nan, obj, nan])
containers = [
seq,
ItemsView({1: nan, 2: obj}),
ValuesView({1: nan, 2: obj})
]
for container in containers:
for elem in container:
self.assertIn(elem, container)
self.assertEqual(seq.index(nan), 0)
self.assertEqual(seq.index(obj), 1)
self.assertEqual(seq.count(nan), 2)
self.assertEqual(seq.count(obj), 1)
def assertSameSet(self, s1, s2):
# coerce both to a real set then check equality
self.assertSetEqual(set(s1), set(s2))
def test_Set_interoperability_with_real_sets(self):
# Issue: 8743
class ListSet(Set):
def __init__(self, elements=()):
self.data = []
for elem in elements:
if elem not in self.data:
self.data.append(elem)
def __contains__(self, elem):
return elem in self.data
def __iter__(self):
return iter(self.data)
def __len__(self):
return len(self.data)
def __repr__(self):
return 'Set({!r})'.format(self.data)
r1 = set('abc')
r2 = set('bcd')
r3 = set('abcde')
f1 = ListSet('abc')
f2 = ListSet('bcd')
f3 = ListSet('abcde')
l1 = list('abccba')
l2 = list('bcddcb')
l3 = list('abcdeedcba')
target = r1 & r2
self.assertSameSet(f1 & f2, target)
self.assertSameSet(f1 & r2, target)
self.assertSameSet(r2 & f1, target)
self.assertSameSet(f1 & l2, target)
target = r1 | r2
self.assertSameSet(f1 | f2, target)
self.assertSameSet(f1 | r2, target)
self.assertSameSet(r2 | f1, target)
self.assertSameSet(f1 | l2, target)
fwd_target = r1 - r2
rev_target = r2 - r1
self.assertSameSet(f1 - f2, fwd_target)
self.assertSameSet(f2 - f1, rev_target)
self.assertSameSet(f1 - r2, fwd_target)
self.assertSameSet(f2 - r1, rev_target)
self.assertSameSet(r1 - f2, fwd_target)
self.assertSameSet(r2 - f1, rev_target)
self.assertSameSet(f1 - l2, fwd_target)
self.assertSameSet(f2 - l1, rev_target)
target = r1 ^ r2
self.assertSameSet(f1 ^ f2, target)
self.assertSameSet(f1 ^ r2, target)
self.assertSameSet(r2 ^ f1, target)
self.assertSameSet(f1 ^ l2, target)
# Don't change the following to use assertLess or other
# "more specific" unittest assertions. The current
# assertTrue/assertFalse style makes the pattern of test
# case combinations clear and allows us to know for sure
# the exact operator being invoked.
# proper subset
self.assertTrue(f1 < f3)
self.assertFalse(f1 < f1)
self.assertFalse(f1 < f2)
self.assertTrue(r1 < f3)
self.assertFalse(r1 < f1)
self.assertFalse(r1 < f2)
self.assertTrue(r1 < r3)
self.assertFalse(r1 < r1)
self.assertFalse(r1 < r2)
with self.assertRaises(TypeError):
f1 < l3
with self.assertRaises(TypeError):
f1 < l1
with self.assertRaises(TypeError):
f1 < l2
# any subset
self.assertTrue(f1 <= f3)
self.assertTrue(f1 <= f1)
self.assertFalse(f1 <= f2)
self.assertTrue(r1 <= f3)
self.assertTrue(r1 <= f1)
self.assertFalse(r1 <= f2)
self.assertTrue(r1 <= r3)
self.assertTrue(r1 <= r1)
self.assertFalse(r1 <= r2)
with self.assertRaises(TypeError):
f1 <= l3
with self.assertRaises(TypeError):
f1 <= l1
with self.assertRaises(TypeError):
f1 <= l2
# proper superset
self.assertTrue(f3 > f1)
self.assertFalse(f1 > f1)
self.assertFalse(f2 > f1)
self.assertTrue(r3 > r1)
self.assertFalse(f1 > r1)
self.assertFalse(f2 > r1)
self.assertTrue(r3 > r1)
self.assertFalse(r1 > r1)
self.assertFalse(r2 > r1)
with self.assertRaises(TypeError):
f1 > l3
with self.assertRaises(TypeError):
f1 > l1
with self.assertRaises(TypeError):
f1 > l2
# any superset
self.assertTrue(f3 >= f1)
self.assertTrue(f1 >= f1)
self.assertFalse(f2 >= f1)
self.assertTrue(r3 >= r1)
self.assertTrue(f1 >= r1)
self.assertFalse(f2 >= r1)
self.assertTrue(r3 >= r1)
self.assertTrue(r1 >= r1)
self.assertFalse(r2 >= r1)
with self.assertRaises(TypeError):
f1 >= l3
with self.assertRaises(TypeError):
f1 >=l1
with self.assertRaises(TypeError):
f1 >= l2
# equality
self.assertTrue(f1 == f1)
self.assertTrue(r1 == f1)
self.assertTrue(f1 == r1)
self.assertFalse(f1 == f3)
self.assertFalse(r1 == f3)
self.assertFalse(f1 == r3)
self.assertFalse(f1 == l3)
self.assertFalse(f1 == l1)
self.assertFalse(f1 == l2)
# inequality
self.assertFalse(f1 != f1)
self.assertFalse(r1 != f1)
self.assertFalse(f1 != r1)
self.assertTrue(f1 != f3)
self.assertTrue(r1 != f3)
self.assertTrue(f1 != r3)
self.assertTrue(f1 != l3)
self.assertTrue(f1 != l1)
self.assertTrue(f1 != l2)
def test_Mapping(self):
for sample in [dict]:
self.assertIsInstance(sample(), Mapping)
self.assertTrue(issubclass(sample, Mapping))
self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__',
'__getitem__')
class MyMapping(Mapping):
def __len__(self):
return 0
def __getitem__(self, i):
raise IndexError
def __iter__(self):
return iter(())
self.validate_comparison(MyMapping())
self.assertRaises(TypeError, reversed, MyMapping())
def test_MutableMapping(self):
for sample in [dict]:
self.assertIsInstance(sample(), MutableMapping)
self.assertTrue(issubclass(sample, MutableMapping))
self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__', '__len__',
'__getitem__', '__setitem__', '__delitem__')
def test_MutableMapping_subclass(self):
# Test issue 9214
mymap = UserDict()
mymap['red'] = 5
self.assertIsInstance(mymap.keys(), Set)
self.assertIsInstance(mymap.keys(), KeysView)
self.assertIsInstance(mymap.items(), Set)
self.assertIsInstance(mymap.items(), ItemsView)
mymap = UserDict()
mymap['red'] = 5
z = mymap.keys() | {'orange'}
self.assertIsInstance(z, set)
list(z)
mymap['blue'] = 7 # Shouldn't affect 'z'
self.assertEqual(sorted(z), ['orange', 'red'])
mymap = UserDict()
mymap['red'] = 5
z = mymap.items() | {('orange', 3)}
self.assertIsInstance(z, set)
list(z)
mymap['blue'] = 7 # Shouldn't affect 'z'
self.assertEqual(sorted(z), [('orange', 3), ('red', 5)])
def test_Sequence(self):
for sample in [tuple, list, bytes, str]:
self.assertIsInstance(sample(), Sequence)
self.assertTrue(issubclass(sample, Sequence))
self.assertIsInstance(range(10), Sequence)
self.assertTrue(issubclass(range, Sequence))
self.assertIsInstance(memoryview(b""), Sequence)
self.assertTrue(issubclass(memoryview, Sequence))
self.assertTrue(issubclass(str, Sequence))
self.validate_abstract_methods(Sequence, '__contains__', '__iter__', '__len__',
'__getitem__')
def test_Sequence_mixins(self):
class SequenceSubclass(Sequence):
def __init__(self, seq=()):
self.seq = seq
def __getitem__(self, index):
return self.seq[index]
def __len__(self):
return len(self.seq)
# Compare Sequence.index() behavior to (list|str).index() behavior
def assert_index_same(seq1, seq2, index_args):
try:
expected = seq1.index(*index_args)
except ValueError:
with self.assertRaises(ValueError):
seq2.index(*index_args)
else:
actual = seq2.index(*index_args)
self.assertEqual(
actual, expected, '%r.index%s' % (seq1, index_args))
for ty in list, str:
nativeseq = ty('abracadabra')
indexes = [-10000, -9999] + list(range(-3, len(nativeseq) + 3))
seqseq = SequenceSubclass(nativeseq)
for letter in set(nativeseq) | {'z'}:
assert_index_same(nativeseq, seqseq, (letter,))
for start in range(-3, len(nativeseq) + 3):
assert_index_same(nativeseq, seqseq, (letter, start))
for stop in range(-3, len(nativeseq) + 3):
assert_index_same(
nativeseq, seqseq, (letter, start, stop))
def test_ByteString(self):
for sample in [bytes, bytearray]:
self.assertIsInstance(sample(), ByteString)
self.assertTrue(issubclass(sample, ByteString))
for sample in [str, list, tuple]:
self.assertNotIsInstance(sample(), ByteString)
self.assertFalse(issubclass(sample, ByteString))
self.assertNotIsInstance(memoryview(b""), ByteString)
self.assertFalse(issubclass(memoryview, ByteString))
def test_MutableSequence(self):
for sample in [tuple, str, bytes]:
self.assertNotIsInstance(sample(), MutableSequence)
self.assertFalse(issubclass(sample, MutableSequence))
for sample in [list, bytearray, deque]:
self.assertIsInstance(sample(), MutableSequence)
self.assertTrue(issubclass(sample, MutableSequence))
self.assertFalse(issubclass(str, MutableSequence))
self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__',
'__len__', '__getitem__', '__setitem__', '__delitem__', 'insert')
def test_MutableSequence_mixins(self):
# Test the mixins of MutableSequence by creating a minimal concrete
# class inherited from it.
class MutableSequenceSubclass(MutableSequence):
def __init__(self):
self.lst = []
def __setitem__(self, index, value):
self.lst[index] = value
def __getitem__(self, index):
return self.lst[index]
def __len__(self):
return len(self.lst)
def __delitem__(self, index):
del self.lst[index]
def insert(self, index, value):
self.lst.insert(index, value)
mss = MutableSequenceSubclass()
mss.append(0)
mss.extend((1, 2, 3, 4))
self.assertEqual(len(mss), 5)
self.assertEqual(mss[3], 3)
mss.reverse()
self.assertEqual(mss[3], 1)
mss.pop()
self.assertEqual(len(mss), 4)
mss.remove(3)
self.assertEqual(len(mss), 3)
mss += (10, 20, 30)
self.assertEqual(len(mss), 6)
self.assertEqual(mss[-1], 30)
mss.clear()
self.assertEqual(len(mss), 0)
################################################################################
### Counter
################################################################################
class CounterSubclassWithSetItem(Counter):
# Test a counter subclass that overrides __setitem__
def __init__(self, *args, **kwds):
self.called = False
Counter.__init__(self, *args, **kwds)
def __setitem__(self, key, value):
self.called = True
Counter.__setitem__(self, key, value)
class CounterSubclassWithGet(Counter):
# Test a counter subclass that overrides get()
def __init__(self, *args, **kwds):
self.called = False
Counter.__init__(self, *args, **kwds)
def get(self, key, default):
self.called = True
return Counter.get(self, key, default)
class TestCounter(unittest.TestCase):
def test_basics(self):
c = Counter('abcaba')
self.assertEqual(c, Counter({'a':3 , 'b': 2, 'c': 1}))
self.assertEqual(c, Counter(a=3, b=2, c=1))
self.assertIsInstance(c, dict)
self.assertIsInstance(c, Mapping)
self.assertTrue(issubclass(Counter, dict))
self.assertTrue(issubclass(Counter, Mapping))
self.assertEqual(len(c), 3)
self.assertEqual(sum(c.values()), 6)
self.assertEqual(sorted(c.values()), [1, 2, 3])
self.assertEqual(sorted(c.keys()), ['a', 'b', 'c'])
self.assertEqual(sorted(c), ['a', 'b', 'c'])
self.assertEqual(sorted(c.items()),
[('a', 3), ('b', 2), ('c', 1)])
self.assertEqual(c['b'], 2)
self.assertEqual(c['z'], 0)
self.assertEqual(c.__contains__('c'), True)
self.assertEqual(c.__contains__('z'), False)
self.assertEqual(c.get('b', 10), 2)
self.assertEqual(c.get('z', 10), 10)
self.assertEqual(c, dict(a=3, b=2, c=1))
self.assertEqual(repr(c), "Counter({'a': 3, 'b': 2, 'c': 1})")
self.assertEqual(c.most_common(), [('a', 3), ('b', 2), ('c', 1)])
for i in range(5):
self.assertEqual(c.most_common(i),
[('a', 3), ('b', 2), ('c', 1)][:i])
self.assertEqual(''.join(sorted(c.elements())), 'aaabbc')
c['a'] += 1 # increment an existing value
c['b'] -= 2 # sub existing value to zero
del c['c'] # remove an entry
del c['c'] # make sure that del doesn't raise KeyError
c['d'] -= 2 # sub from a missing value
c['e'] = -5 # directly assign a missing value
c['f'] += 4 # add to a missing value
self.assertEqual(c, dict(a=4, b=0, d=-2, e=-5, f=4))
self.assertEqual(''.join(sorted(c.elements())), 'aaaaffff')
self.assertEqual(c.pop('f'), 4)
self.assertNotIn('f', c)
for i in range(3):
elem, cnt = c.popitem()
self.assertNotIn(elem, c)
c.clear()
self.assertEqual(c, {})
self.assertEqual(repr(c), 'Counter()')
self.assertRaises(NotImplementedError, Counter.fromkeys, 'abc')
self.assertRaises(TypeError, hash, c)
c.update(dict(a=5, b=3))
c.update(c=1)
c.update(Counter('a' * 50 + 'b' * 30))
c.update() # test case with no args
c.__init__('a' * 500 + 'b' * 300)
c.__init__('cdc')
c.__init__()
self.assertEqual(c, dict(a=555, b=333, c=3, d=1))
self.assertEqual(c.setdefault('d', 5), 1)
self.assertEqual(c['d'], 1)
self.assertEqual(c.setdefault('e', 5), 5)
self.assertEqual(c['e'], 5)
def test_init(self):
self.assertEqual(list(Counter(self=42).items()), [('self', 42)])
self.assertEqual(list(Counter(iterable=42).items()), [('iterable', 42)])
self.assertEqual(list(Counter(iterable=None).items()), [('iterable', None)])
self.assertRaises(TypeError, Counter, 42)
self.assertRaises(TypeError, Counter, (), ())
self.assertRaises(TypeError, Counter.__init__)
def test_update(self):
c = Counter()
c.update(self=42)
self.assertEqual(list(c.items()), [('self', 42)])
c = Counter()
c.update(iterable=42)
self.assertEqual(list(c.items()), [('iterable', 42)])
c = Counter()
c.update(iterable=None)
self.assertEqual(list(c.items()), [('iterable', None)])
self.assertRaises(TypeError, Counter().update, 42)
self.assertRaises(TypeError, Counter().update, {}, {})
self.assertRaises(TypeError, Counter.update)
def test_copying(self):
# Check that counters are copyable, deepcopyable, picklable, and
#have a repr/eval round-trip
words = Counter('which witch had which witches wrist watch'.split())
def check(dup):
msg = "\ncopy: %s\nwords: %s" % (dup, words)
self.assertIsNot(dup, words, msg)
self.assertEqual(dup, words)
check(words.copy())
check(copy.copy(words))
check(copy.deepcopy(words))
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
with self.subTest(proto=proto):
check(pickle.loads(pickle.dumps(words, proto)))
check(eval(repr(words)))
update_test = Counter()
update_test.update(words)
check(update_test)
check(Counter(words))
def test_copy_subclass(self):
class MyCounter(Counter):
pass
c = MyCounter('slartibartfast')
d = c.copy()
self.assertEqual(d, c)
self.assertEqual(len(d), len(c))
self.assertEqual(type(d), type(c))
def test_conversions(self):
# Convert to: set, list, dict
s = 'she sells sea shells by the sea shore'
self.assertEqual(sorted(Counter(s).elements()), sorted(s))
self.assertEqual(sorted(Counter(s)), sorted(set(s)))
self.assertEqual(dict(Counter(s)), dict(Counter(s).items()))
self.assertEqual(set(Counter(s)), set(s))
def test_invariant_for_the_in_operator(self):
c = Counter(a=10, b=-2, c=0)
for elem in c:
self.assertTrue(elem in c)
self.assertIn(elem, c)
def test_multiset_operations(self):
# Verify that adding a zero counter will strip zeros and negatives
c = Counter(a=10, b=-2, c=0) + Counter()
self.assertEqual(dict(c), dict(a=10))
elements = 'abcd'
for i in range(1000):
# test random pairs of multisets
p = Counter(dict((elem, randrange(-2,4)) for elem in elements))
p.update(e=1, f=-1, g=0)
q = Counter(dict((elem, randrange(-2,4)) for elem in elements))
q.update(h=1, i=-1, j=0)
for counterop, numberop in [
(Counter.__add__, lambda x, y: max(0, x+y)),
(Counter.__sub__, lambda x, y: max(0, x-y)),
(Counter.__or__, lambda x, y: max(0,x,y)),
(Counter.__and__, lambda x, y: max(0, min(x,y))),
]:
result = counterop(p, q)
for x in elements:
self.assertEqual(numberop(p[x], q[x]), result[x],
(counterop, x, p, q))
# verify that results exclude non-positive counts
self.assertTrue(x>0 for x in result.values())
elements = 'abcdef'
for i in range(100):
# verify that random multisets with no repeats are exactly like sets
p = Counter(dict((elem, randrange(0, 2)) for elem in elements))
q = Counter(dict((elem, randrange(0, 2)) for elem in elements))
for counterop, setop in [
(Counter.__sub__, set.__sub__),
(Counter.__or__, set.__or__),
(Counter.__and__, set.__and__),
]:
counter_result = counterop(p, q)
set_result = setop(set(p.elements()), set(q.elements()))
self.assertEqual(counter_result, dict.fromkeys(set_result, 1))
def test_inplace_operations(self):
elements = 'abcd'
for i in range(1000):
# test random pairs of multisets
p = Counter(dict((elem, randrange(-2,4)) for elem in elements))
p.update(e=1, f=-1, g=0)
q = Counter(dict((elem, randrange(-2,4)) for elem in elements))
q.update(h=1, i=-1, j=0)
for inplace_op, regular_op in [
(Counter.__iadd__, Counter.__add__),
(Counter.__isub__, Counter.__sub__),
(Counter.__ior__, Counter.__or__),
(Counter.__iand__, Counter.__and__),
]:
c = p.copy()
c_id = id(c)
regular_result = regular_op(c, q)
inplace_result = inplace_op(c, q)
self.assertEqual(inplace_result, regular_result)
self.assertEqual(id(inplace_result), c_id)
def test_subtract(self):
c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40)
c.subtract(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50)
self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50))
c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40)
c.subtract(Counter(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50))
self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50))
c = Counter('aaabbcd')
c.subtract('aaaabbcce')
self.assertEqual(c, Counter(a=-1, b=0, c=-1, d=1, e=-1))
c = Counter()
c.subtract(self=42)
self.assertEqual(list(c.items()), [('self', -42)])
c = Counter()
c.subtract(iterable=42)
self.assertEqual(list(c.items()), [('iterable', -42)])
self.assertRaises(TypeError, Counter().subtract, 42)
self.assertRaises(TypeError, Counter().subtract, {}, {})
self.assertRaises(TypeError, Counter.subtract)
def test_unary(self):
c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40)
self.assertEqual(dict(+c), dict(c=5, d=10, e=15, g=40))
self.assertEqual(dict(-c), dict(a=5))
def test_repr_nonsortable(self):
c = Counter(a=2, b=None)
r = repr(c)
self.assertIn("'a': 2", r)
self.assertIn("'b': None", r)
def test_helper_function(self):
# two paths, one for real dicts and one for other mappings
elems = list('abracadabra')
d = dict()
_count_elements(d, elems)
self.assertEqual(d, {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1})
m = OrderedDict()
_count_elements(m, elems)
self.assertEqual(m,
OrderedDict([('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]))
# test fidelity to the pure python version
c = CounterSubclassWithSetItem('abracadabra')
self.assertTrue(c.called)
self.assertEqual(dict(c), {'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r':2 })
c = CounterSubclassWithGet('abracadabra')
self.assertTrue(c.called)
self.assertEqual(dict(c), {'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r':2 })
################################################################################
### Run tests
################################################################################
def test_main(verbose=None):
NamedTupleDocs = doctest.DocTestSuite(module=collections)
test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs,
TestCollectionABCs, TestCounter, TestChainMap,
TestUserObjects,
]
support.run_unittest(*test_classes)
support.run_doctest(collections, verbose)
if __name__ == "__main__":
test_main(verbose=True)
| 75,906 | 1,927 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_dbm_ndbm.py | from test import support
support.import_module("dbm.ndbm") #skip if not supported
import os
import unittest
import dbm.ndbm
from dbm.ndbm import error
class DbmTestCase(unittest.TestCase):
def setUp(self):
self.filename = support.TESTFN
self.d = dbm.ndbm.open(self.filename, 'c')
self.d.close()
def tearDown(self):
for suffix in ['', '.pag', '.dir', '.db']:
support.unlink(self.filename + suffix)
def test_keys(self):
self.d = dbm.ndbm.open(self.filename, 'c')
self.assertEqual(self.d.keys(), [])
self.d['a'] = 'b'
self.d[b'bytes'] = b'data'
self.d['12345678910'] = '019237410982340912840198242'
self.d.keys()
self.assertIn('a', self.d)
self.assertIn(b'a', self.d)
self.assertEqual(self.d[b'bytes'], b'data')
# get() and setdefault() work as in the dict interface
self.assertEqual(self.d.get(b'a'), b'b')
self.assertIsNone(self.d.get(b'xxx'))
self.assertEqual(self.d.get(b'xxx', b'foo'), b'foo')
with self.assertRaises(KeyError):
self.d['xxx']
self.assertEqual(self.d.setdefault(b'xxx', b'foo'), b'foo')
self.assertEqual(self.d[b'xxx'], b'foo')
self.d.close()
def test_empty_value(self):
if dbm.ndbm.library == 'Berkeley DB':
self.skipTest("Berkeley DB doesn't distinguish the empty value "
"from the absent one")
self.d = dbm.ndbm.open(self.filename, 'c')
self.assertEqual(self.d.keys(), [])
self.d['empty'] = ''
self.assertEqual(self.d.keys(), [b'empty'])
self.assertIn(b'empty', self.d)
self.assertEqual(self.d[b'empty'], b'')
self.assertEqual(self.d.get(b'empty'), b'')
self.assertEqual(self.d.setdefault(b'empty'), b'')
self.d.close()
def test_modes(self):
for mode in ['r', 'rw', 'w', 'n']:
try:
self.d = dbm.ndbm.open(self.filename, mode)
self.d.close()
except error:
self.fail()
def test_context_manager(self):
with dbm.ndbm.open(self.filename, 'c') as db:
db["ndbm context manager"] = "context manager"
with dbm.ndbm.open(self.filename, 'r') as db:
self.assertEqual(list(db.keys()), [b"ndbm context manager"])
with self.assertRaises(dbm.ndbm.error) as cm:
db.keys()
self.assertEqual(str(cm.exception),
"DBM object has already been closed")
def test_bytes(self):
with dbm.ndbm.open(self.filename, 'c') as db:
db[b'bytes key \xbd'] = b'bytes value \xbd'
with dbm.ndbm.open(self.filename, 'r') as db:
self.assertEqual(list(db.keys()), [b'bytes key \xbd'])
self.assertTrue(b'bytes key \xbd' in db)
self.assertEqual(db[b'bytes key \xbd'], b'bytes value \xbd')
def test_unicode(self):
with dbm.ndbm.open(self.filename, 'c') as db:
db['Unicode key \U0001f40d'] = 'Unicode value \U0001f40d'
with dbm.ndbm.open(self.filename, 'r') as db:
self.assertEqual(list(db.keys()), ['Unicode key \U0001f40d'.encode()])
self.assertTrue('Unicode key \U0001f40d'.encode() in db)
self.assertTrue('Unicode key \U0001f40d' in db)
self.assertEqual(db['Unicode key \U0001f40d'.encode()],
'Unicode value \U0001f40d'.encode())
self.assertEqual(db['Unicode key \U0001f40d'],
'Unicode value \U0001f40d'.encode())
@unittest.skipUnless(support.TESTFN_NONASCII,
'requires OS support of non-ASCII encodings')
def test_nonascii_filename(self):
filename = support.TESTFN_NONASCII
for suffix in ['', '.pag', '.dir', '.db']:
self.addCleanup(support.unlink, filename + suffix)
with dbm.ndbm.open(filename, 'c') as db:
db[b'key'] = b'value'
self.assertTrue(any(os.path.exists(filename + suffix)
for suffix in ['', '.pag', '.dir', '.db']))
with dbm.ndbm.open(filename, 'r') as db:
self.assertEqual(list(db.keys()), [b'key'])
self.assertTrue(b'key' in db)
self.assertEqual(db[b'key'], b'value')
if __name__ == '__main__':
unittest.main()
| 4,409 | 112 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_numeric_tower.py | # test interactions between int, float, Decimal and Fraction
import unittest
import random
import math
import sys
import operator
from decimal import Decimal as D
from fractions import Fraction as F
# Constants related to the hash implementation; hash(x) is based
# on the reduction of x modulo the prime _PyHASH_MODULUS.
_PyHASH_MODULUS = sys.hash_info.modulus
_PyHASH_INF = sys.hash_info.inf
class HashTest(unittest.TestCase):
def check_equal_hash(self, x, y):
# check both that x and y are equal and that their hashes are equal
self.assertEqual(hash(x), hash(y),
"got different hashes for {!r} and {!r}".format(x, y))
self.assertEqual(x, y)
def test_bools(self):
self.check_equal_hash(False, 0)
self.check_equal_hash(True, 1)
def test_integers(self):
# check that equal values hash equal
# exact integers
for i in range(-1000, 1000):
self.check_equal_hash(i, float(i))
self.check_equal_hash(i, D(i))
self.check_equal_hash(i, F(i))
# the current hash is based on reduction modulo 2**n-1 for some
# n, so pay special attention to numbers of the form 2**n and 2**n-1.
for i in range(100):
n = 2**i - 1
if n == int(float(n)):
self.check_equal_hash(n, float(n))
self.check_equal_hash(-n, -float(n))
self.check_equal_hash(n, D(n))
self.check_equal_hash(n, F(n))
self.check_equal_hash(-n, D(-n))
self.check_equal_hash(-n, F(-n))
n = 2**i
self.check_equal_hash(n, float(n))
self.check_equal_hash(-n, -float(n))
self.check_equal_hash(n, D(n))
self.check_equal_hash(n, F(n))
self.check_equal_hash(-n, D(-n))
self.check_equal_hash(-n, F(-n))
# random values of various sizes
for _ in range(1000):
e = random.randrange(300)
n = random.randrange(-10**e, 10**e)
self.check_equal_hash(n, D(n))
self.check_equal_hash(n, F(n))
if n == int(float(n)):
self.check_equal_hash(n, float(n))
def test_binary_floats(self):
# check that floats hash equal to corresponding Fractions and Decimals
# floats that are distinct but numerically equal should hash the same
self.check_equal_hash(0.0, -0.0)
# zeros
self.check_equal_hash(0.0, D(0))
self.check_equal_hash(-0.0, D(0))
self.check_equal_hash(-0.0, D('-0.0'))
self.check_equal_hash(0.0, F(0))
# infinities and nans
self.check_equal_hash(float('inf'), D('inf'))
self.check_equal_hash(float('-inf'), D('-inf'))
for _ in range(1000):
x = random.random() * math.exp(random.random()*200.0 - 100.0)
self.check_equal_hash(x, D.from_float(x))
self.check_equal_hash(x, F.from_float(x))
def test_complex(self):
# complex numbers with zero imaginary part should hash equal to
# the corresponding float
test_values = [0.0, -0.0, 1.0, -1.0, 0.40625, -5136.5,
float('inf'), float('-inf')]
for zero in -0.0, 0.0:
for value in test_values:
self.check_equal_hash(value, complex(value, zero))
def test_decimals(self):
# check that Decimal instances that have different representations
# but equal values give the same hash
zeros = ['0', '-0', '0.0', '-0.0e10', '000e-10']
for zero in zeros:
self.check_equal_hash(D(zero), D(0))
self.check_equal_hash(D('1.00'), D(1))
self.check_equal_hash(D('1.00000'), D(1))
self.check_equal_hash(D('-1.00'), D(-1))
self.check_equal_hash(D('-1.00000'), D(-1))
self.check_equal_hash(D('123e2'), D(12300))
self.check_equal_hash(D('1230e1'), D(12300))
self.check_equal_hash(D('12300'), D(12300))
self.check_equal_hash(D('12300.0'), D(12300))
self.check_equal_hash(D('12300.00'), D(12300))
self.check_equal_hash(D('12300.000'), D(12300))
def test_fractions(self):
# check special case for fractions where either the numerator
# or the denominator is a multiple of _PyHASH_MODULUS
self.assertEqual(hash(F(1, _PyHASH_MODULUS)), _PyHASH_INF)
self.assertEqual(hash(F(-1, 3*_PyHASH_MODULUS)), -_PyHASH_INF)
self.assertEqual(hash(F(7*_PyHASH_MODULUS, 1)), 0)
self.assertEqual(hash(F(-_PyHASH_MODULUS, 1)), 0)
def test_hash_normalization(self):
# Test for a bug encountered while changing long_hash.
#
# Given objects x and y, it should be possible for y's
# __hash__ method to return hash(x) in order to ensure that
# hash(x) == hash(y). But hash(x) is not exactly equal to the
# result of x.__hash__(): there's some internal normalization
# to make sure that the result fits in a C long, and is not
# equal to the invalid hash value -1. This internal
# normalization must therefore not change the result of
# hash(x) for any x.
class HalibutProxy:
def __hash__(self):
return hash('halibut')
def __eq__(self, other):
return other == 'halibut'
x = {'halibut', HalibutProxy()}
self.assertEqual(len(x), 1)
class ComparisonTest(unittest.TestCase):
def test_mixed_comparisons(self):
# ordered list of distinct test values of various types:
# int, float, Fraction, Decimal
test_values = [
float('-inf'),
D('-1e425000000'),
-1e308,
F(-22, 7),
-3.14,
-2,
0.0,
1e-320,
True,
F('1.2'),
D('1.3'),
float('1.4'),
F(275807, 195025),
D('1.414213562373095048801688724'),
F(114243, 80782),
F(473596569, 84615),
7e200,
D('infinity'),
]
for i, first in enumerate(test_values):
for second in test_values[i+1:]:
self.assertLess(first, second)
self.assertLessEqual(first, second)
self.assertGreater(second, first)
self.assertGreaterEqual(second, first)
def test_complex(self):
# comparisons with complex are special: equality and inequality
# comparisons should always succeed, but order comparisons should
# raise TypeError.
z = 1.0 + 0j
w = -3.14 + 2.7j
for v in 1, 1.0, F(1), D(1), complex(1):
self.assertEqual(z, v)
self.assertEqual(v, z)
for v in 2, 2.0, F(2), D(2), complex(2):
self.assertNotEqual(z, v)
self.assertNotEqual(v, z)
self.assertNotEqual(w, v)
self.assertNotEqual(v, w)
for v in (1, 1.0, F(1), D(1), complex(1),
2, 2.0, F(2), D(2), complex(2), w):
for op in operator.le, operator.lt, operator.ge, operator.gt:
self.assertRaises(TypeError, op, z, v)
self.assertRaises(TypeError, op, v, z)
if __name__ == '__main__':
unittest.main()
| 7,352 | 203 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_multiprocessing_spawn.py | import unittest
import test._test_multiprocessing
from test import support
if support.PGO:
raise unittest.SkipTest("test is not helpful for PGO")
test._test_multiprocessing.install_tests_in_module_dict(globals(), 'spawn')
if __name__ == '__main__':
unittest.main()
| 277 | 13 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_nis.py | from test import support
import unittest
# Skip test if nis module does not exist.
nis = support.import_module('nis')
class NisTests(unittest.TestCase):
def test_maps(self):
try:
maps = nis.maps()
except nis.error as msg:
# NIS is probably not active, so this test isn't useful
self.skipTest(str(msg))
try:
# On some systems, this map is only accessible to the
# super user
maps.remove("passwd.adjunct.byname")
except ValueError:
pass
done = 0
for nismap in maps:
mapping = nis.cat(nismap)
for k, v in mapping.items():
if not k:
continue
if nis.match(k, nismap) != v:
self.fail("NIS match failed for key `%s' in map `%s'" % (k, nismap))
else:
# just test the one key, otherwise this test could take a
# very long time
done = 1
break
if done:
break
if __name__ == '__main__':
unittest.main()
| 1,156 | 40 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_operator.py | import unittest
import pickle
import sys
from test import support
py_operator = support.import_fresh_module('operator', blocked=['_operator'])
c_operator = support.import_fresh_module('operator', fresh=['_operator'])
class Seq1:
def __init__(self, lst):
self.lst = lst
def __len__(self):
return len(self.lst)
def __getitem__(self, i):
return self.lst[i]
def __add__(self, other):
return self.lst + other.lst
def __mul__(self, other):
return self.lst * other
def __rmul__(self, other):
return other * self.lst
class Seq2(object):
def __init__(self, lst):
self.lst = lst
def __len__(self):
return len(self.lst)
def __getitem__(self, i):
return self.lst[i]
def __add__(self, other):
return self.lst + other.lst
def __mul__(self, other):
return self.lst * other
def __rmul__(self, other):
return other * self.lst
class OperatorTestCase:
def test_lt(self):
operator = self.module
self.assertRaises(TypeError, operator.lt)
self.assertRaises(TypeError, operator.lt, 1j, 2j)
self.assertFalse(operator.lt(1, 0))
self.assertFalse(operator.lt(1, 0.0))
self.assertFalse(operator.lt(1, 1))
self.assertFalse(operator.lt(1, 1.0))
self.assertTrue(operator.lt(1, 2))
self.assertTrue(operator.lt(1, 2.0))
def test_le(self):
operator = self.module
self.assertRaises(TypeError, operator.le)
self.assertRaises(TypeError, operator.le, 1j, 2j)
self.assertFalse(operator.le(1, 0))
self.assertFalse(operator.le(1, 0.0))
self.assertTrue(operator.le(1, 1))
self.assertTrue(operator.le(1, 1.0))
self.assertTrue(operator.le(1, 2))
self.assertTrue(operator.le(1, 2.0))
def test_eq(self):
operator = self.module
class C(object):
def __eq__(self, other):
raise SyntaxError
self.assertRaises(TypeError, operator.eq)
self.assertRaises(SyntaxError, operator.eq, C(), C())
self.assertFalse(operator.eq(1, 0))
self.assertFalse(operator.eq(1, 0.0))
self.assertTrue(operator.eq(1, 1))
self.assertTrue(operator.eq(1, 1.0))
self.assertFalse(operator.eq(1, 2))
self.assertFalse(operator.eq(1, 2.0))
def test_ne(self):
operator = self.module
class C(object):
def __ne__(self, other):
raise SyntaxError
self.assertRaises(TypeError, operator.ne)
self.assertRaises(SyntaxError, operator.ne, C(), C())
self.assertTrue(operator.ne(1, 0))
self.assertTrue(operator.ne(1, 0.0))
self.assertFalse(operator.ne(1, 1))
self.assertFalse(operator.ne(1, 1.0))
self.assertTrue(operator.ne(1, 2))
self.assertTrue(operator.ne(1, 2.0))
def test_ge(self):
operator = self.module
self.assertRaises(TypeError, operator.ge)
self.assertRaises(TypeError, operator.ge, 1j, 2j)
self.assertTrue(operator.ge(1, 0))
self.assertTrue(operator.ge(1, 0.0))
self.assertTrue(operator.ge(1, 1))
self.assertTrue(operator.ge(1, 1.0))
self.assertFalse(operator.ge(1, 2))
self.assertFalse(operator.ge(1, 2.0))
def test_gt(self):
operator = self.module
self.assertRaises(TypeError, operator.gt)
self.assertRaises(TypeError, operator.gt, 1j, 2j)
self.assertTrue(operator.gt(1, 0))
self.assertTrue(operator.gt(1, 0.0))
self.assertFalse(operator.gt(1, 1))
self.assertFalse(operator.gt(1, 1.0))
self.assertFalse(operator.gt(1, 2))
self.assertFalse(operator.gt(1, 2.0))
def test_abs(self):
operator = self.module
self.assertRaises(TypeError, operator.abs)
self.assertRaises(TypeError, operator.abs, None)
self.assertEqual(operator.abs(-1), 1)
self.assertEqual(operator.abs(1), 1)
def test_add(self):
operator = self.module
self.assertRaises(TypeError, operator.add)
self.assertRaises(TypeError, operator.add, None, None)
self.assertEqual(operator.add(3, 4), 7)
def test_bitwise_and(self):
operator = self.module
self.assertRaises(TypeError, operator.and_)
self.assertRaises(TypeError, operator.and_, None, None)
self.assertEqual(operator.and_(0xf, 0xa), 0xa)
def test_concat(self):
operator = self.module
self.assertRaises(TypeError, operator.concat)
self.assertRaises(TypeError, operator.concat, None, None)
self.assertEqual(operator.concat('py', 'thon'), 'python')
self.assertEqual(operator.concat([1, 2], [3, 4]), [1, 2, 3, 4])
self.assertEqual(operator.concat(Seq1([5, 6]), Seq1([7])), [5, 6, 7])
self.assertEqual(operator.concat(Seq2([5, 6]), Seq2([7])), [5, 6, 7])
self.assertRaises(TypeError, operator.concat, 13, 29)
def test_countOf(self):
operator = self.module
self.assertRaises(TypeError, operator.countOf)
self.assertRaises(TypeError, operator.countOf, None, None)
self.assertEqual(operator.countOf([1, 2, 1, 3, 1, 4], 3), 1)
self.assertEqual(operator.countOf([1, 2, 1, 3, 1, 4], 5), 0)
def test_delitem(self):
operator = self.module
a = [4, 3, 2, 1]
self.assertRaises(TypeError, operator.delitem, a)
self.assertRaises(TypeError, operator.delitem, a, None)
self.assertIsNone(operator.delitem(a, 1))
self.assertEqual(a, [4, 2, 1])
def test_floordiv(self):
operator = self.module
self.assertRaises(TypeError, operator.floordiv, 5)
self.assertRaises(TypeError, operator.floordiv, None, None)
self.assertEqual(operator.floordiv(5, 2), 2)
def test_truediv(self):
operator = self.module
self.assertRaises(TypeError, operator.truediv, 5)
self.assertRaises(TypeError, operator.truediv, None, None)
self.assertEqual(operator.truediv(5, 2), 2.5)
def test_getitem(self):
operator = self.module
a = range(10)
self.assertRaises(TypeError, operator.getitem)
self.assertRaises(TypeError, operator.getitem, a, None)
self.assertEqual(operator.getitem(a, 2), 2)
def test_indexOf(self):
operator = self.module
self.assertRaises(TypeError, operator.indexOf)
self.assertRaises(TypeError, operator.indexOf, None, None)
self.assertEqual(operator.indexOf([4, 3, 2, 1], 3), 1)
self.assertRaises(ValueError, operator.indexOf, [4, 3, 2, 1], 0)
def test_invert(self):
operator = self.module
self.assertRaises(TypeError, operator.invert)
self.assertRaises(TypeError, operator.invert, None)
self.assertEqual(operator.inv(4), -5)
def test_lshift(self):
operator = self.module
self.assertRaises(TypeError, operator.lshift)
self.assertRaises(TypeError, operator.lshift, None, 42)
self.assertEqual(operator.lshift(5, 1), 10)
self.assertEqual(operator.lshift(5, 0), 5)
self.assertRaises(ValueError, operator.lshift, 2, -1)
def test_mod(self):
operator = self.module
self.assertRaises(TypeError, operator.mod)
self.assertRaises(TypeError, operator.mod, None, 42)
self.assertEqual(operator.mod(5, 2), 1)
def test_mul(self):
operator = self.module
self.assertRaises(TypeError, operator.mul)
self.assertRaises(TypeError, operator.mul, None, None)
self.assertEqual(operator.mul(5, 2), 10)
def test_matmul(self):
operator = self.module
self.assertRaises(TypeError, operator.matmul)
self.assertRaises(TypeError, operator.matmul, 42, 42)
class M:
def __matmul__(self, other):
return other - 1
self.assertEqual(M() @ 42, 41)
def test_neg(self):
operator = self.module
self.assertRaises(TypeError, operator.neg)
self.assertRaises(TypeError, operator.neg, None)
self.assertEqual(operator.neg(5), -5)
self.assertEqual(operator.neg(-5), 5)
self.assertEqual(operator.neg(0), 0)
self.assertEqual(operator.neg(-0), 0)
def test_bitwise_or(self):
operator = self.module
self.assertRaises(TypeError, operator.or_)
self.assertRaises(TypeError, operator.or_, None, None)
self.assertEqual(operator.or_(0xa, 0x5), 0xf)
def test_pos(self):
operator = self.module
self.assertRaises(TypeError, operator.pos)
self.assertRaises(TypeError, operator.pos, None)
self.assertEqual(operator.pos(5), 5)
self.assertEqual(operator.pos(-5), -5)
self.assertEqual(operator.pos(0), 0)
self.assertEqual(operator.pos(-0), 0)
def test_pow(self):
operator = self.module
self.assertRaises(TypeError, operator.pow)
self.assertRaises(TypeError, operator.pow, None, None)
self.assertEqual(operator.pow(3,5), 3**5)
self.assertRaises(TypeError, operator.pow, 1)
self.assertRaises(TypeError, operator.pow, 1, 2, 3)
def test_rshift(self):
operator = self.module
self.assertRaises(TypeError, operator.rshift)
self.assertRaises(TypeError, operator.rshift, None, 42)
self.assertEqual(operator.rshift(5, 1), 2)
self.assertEqual(operator.rshift(5, 0), 5)
self.assertRaises(ValueError, operator.rshift, 2, -1)
def test_contains(self):
operator = self.module
self.assertRaises(TypeError, operator.contains)
self.assertRaises(TypeError, operator.contains, None, None)
self.assertTrue(operator.contains(range(4), 2))
self.assertFalse(operator.contains(range(4), 5))
def test_setitem(self):
operator = self.module
a = list(range(3))
self.assertRaises(TypeError, operator.setitem, a)
self.assertRaises(TypeError, operator.setitem, a, None, None)
self.assertIsNone(operator.setitem(a, 0, 2))
self.assertEqual(a, [2, 1, 2])
self.assertRaises(IndexError, operator.setitem, a, 4, 2)
def test_sub(self):
operator = self.module
self.assertRaises(TypeError, operator.sub)
self.assertRaises(TypeError, operator.sub, None, None)
self.assertEqual(operator.sub(5, 2), 3)
def test_truth(self):
operator = self.module
class C(object):
def __bool__(self):
raise SyntaxError
self.assertRaises(TypeError, operator.truth)
self.assertRaises(SyntaxError, operator.truth, C())
self.assertTrue(operator.truth(5))
self.assertTrue(operator.truth([0]))
self.assertFalse(operator.truth(0))
self.assertFalse(operator.truth([]))
def test_bitwise_xor(self):
operator = self.module
self.assertRaises(TypeError, operator.xor)
self.assertRaises(TypeError, operator.xor, None, None)
self.assertEqual(operator.xor(0xb, 0xc), 0x7)
def test_is(self):
operator = self.module
a = b = 'xyzpdq'
c = a[:3] + b[3:]
self.assertRaises(TypeError, operator.is_)
self.assertTrue(operator.is_(a, b))
self.assertFalse(operator.is_(a,c))
def test_is_not(self):
operator = self.module
a = b = 'xyzpdq'
c = a[:3] + b[3:]
self.assertRaises(TypeError, operator.is_not)
self.assertFalse(operator.is_not(a, b))
self.assertTrue(operator.is_not(a,c))
def test_attrgetter(self):
operator = self.module
class A:
pass
a = A()
a.name = 'arthur'
f = operator.attrgetter('name')
self.assertEqual(f(a), 'arthur')
self.assertRaises(TypeError, f)
self.assertRaises(TypeError, f, a, 'dent')
self.assertRaises(TypeError, f, a, surname='dent')
f = operator.attrgetter('rank')
self.assertRaises(AttributeError, f, a)
self.assertRaises(TypeError, operator.attrgetter, 2)
self.assertRaises(TypeError, operator.attrgetter)
# multiple gets
record = A()
record.x = 'X'
record.y = 'Y'
record.z = 'Z'
self.assertEqual(operator.attrgetter('x','z','y')(record), ('X', 'Z', 'Y'))
self.assertRaises(TypeError, operator.attrgetter, ('x', (), 'y'))
class C(object):
def __getattr__(self, name):
raise SyntaxError
self.assertRaises(SyntaxError, operator.attrgetter('foo'), C())
# recursive gets
a = A()
a.name = 'arthur'
a.child = A()
a.child.name = 'thomas'
f = operator.attrgetter('child.name')
self.assertEqual(f(a), 'thomas')
self.assertRaises(AttributeError, f, a.child)
f = operator.attrgetter('name', 'child.name')
self.assertEqual(f(a), ('arthur', 'thomas'))
f = operator.attrgetter('name', 'child.name', 'child.child.name')
self.assertRaises(AttributeError, f, a)
f = operator.attrgetter('child.')
self.assertRaises(AttributeError, f, a)
f = operator.attrgetter('.child')
self.assertRaises(AttributeError, f, a)
a.child.child = A()
a.child.child.name = 'johnson'
f = operator.attrgetter('child.child.name')
self.assertEqual(f(a), 'johnson')
f = operator.attrgetter('name', 'child.name', 'child.child.name')
self.assertEqual(f(a), ('arthur', 'thomas', 'johnson'))
def test_itemgetter(self):
operator = self.module
a = 'ABCDE'
f = operator.itemgetter(2)
self.assertEqual(f(a), 'C')
self.assertRaises(TypeError, f)
self.assertRaises(TypeError, f, a, 3)
self.assertRaises(TypeError, f, a, size=3)
f = operator.itemgetter(10)
self.assertRaises(IndexError, f, a)
class C(object):
def __getitem__(self, name):
raise SyntaxError
self.assertRaises(SyntaxError, operator.itemgetter(42), C())
f = operator.itemgetter('name')
self.assertRaises(TypeError, f, a)
self.assertRaises(TypeError, operator.itemgetter)
d = dict(key='val')
f = operator.itemgetter('key')
self.assertEqual(f(d), 'val')
f = operator.itemgetter('nonkey')
self.assertRaises(KeyError, f, d)
# example used in the docs
inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
getcount = operator.itemgetter(1)
self.assertEqual(list(map(getcount, inventory)), [3, 2, 5, 1])
self.assertEqual(sorted(inventory, key=getcount),
[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)])
# multiple gets
data = list(map(str, range(20)))
self.assertEqual(operator.itemgetter(2,10,5)(data), ('2', '10', '5'))
self.assertRaises(TypeError, operator.itemgetter(2, 'x', 5), data)
def test_methodcaller(self):
operator = self.module
self.assertRaises(TypeError, operator.methodcaller)
self.assertRaises(TypeError, operator.methodcaller, 12)
class A:
def foo(self, *args, **kwds):
return args[0] + args[1]
def bar(self, f=42):
return f
def baz(*args, **kwds):
return kwds['name'], kwds['self']
a = A()
f = operator.methodcaller('foo')
self.assertRaises(IndexError, f, a)
f = operator.methodcaller('foo', 1, 2)
self.assertEqual(f(a), 3)
self.assertRaises(TypeError, f)
self.assertRaises(TypeError, f, a, 3)
self.assertRaises(TypeError, f, a, spam=3)
f = operator.methodcaller('bar')
self.assertEqual(f(a), 42)
self.assertRaises(TypeError, f, a, a)
f = operator.methodcaller('bar', f=5)
self.assertEqual(f(a), 5)
f = operator.methodcaller('baz', name='spam', self='eggs')
self.assertEqual(f(a), ('spam', 'eggs'))
def test_inplace(self):
operator = self.module
class C(object):
def __iadd__ (self, other): return "iadd"
def __iand__ (self, other): return "iand"
def __ifloordiv__(self, other): return "ifloordiv"
def __ilshift__ (self, other): return "ilshift"
def __imod__ (self, other): return "imod"
def __imul__ (self, other): return "imul"
def __imatmul__ (self, other): return "imatmul"
def __ior__ (self, other): return "ior"
def __ipow__ (self, other): return "ipow"
def __irshift__ (self, other): return "irshift"
def __isub__ (self, other): return "isub"
def __itruediv__ (self, other): return "itruediv"
def __ixor__ (self, other): return "ixor"
def __getitem__(self, other): return 5 # so that C is a sequence
c = C()
self.assertEqual(operator.iadd (c, 5), "iadd")
self.assertEqual(operator.iand (c, 5), "iand")
self.assertEqual(operator.ifloordiv(c, 5), "ifloordiv")
self.assertEqual(operator.ilshift (c, 5), "ilshift")
self.assertEqual(operator.imod (c, 5), "imod")
self.assertEqual(operator.imul (c, 5), "imul")
self.assertEqual(operator.imatmul (c, 5), "imatmul")
self.assertEqual(operator.ior (c, 5), "ior")
self.assertEqual(operator.ipow (c, 5), "ipow")
self.assertEqual(operator.irshift (c, 5), "irshift")
self.assertEqual(operator.isub (c, 5), "isub")
self.assertEqual(operator.itruediv (c, 5), "itruediv")
self.assertEqual(operator.ixor (c, 5), "ixor")
self.assertEqual(operator.iconcat (c, c), "iadd")
def test_length_hint(self):
operator = self.module
class X(object):
def __init__(self, value):
self.value = value
def __length_hint__(self):
if type(self.value) is type:
raise self.value
else:
return self.value
self.assertEqual(operator.length_hint([], 2), 0)
self.assertEqual(operator.length_hint(iter([1, 2, 3])), 3)
self.assertEqual(operator.length_hint(X(2)), 2)
self.assertEqual(operator.length_hint(X(NotImplemented), 4), 4)
self.assertEqual(operator.length_hint(X(TypeError), 12), 12)
with self.assertRaises(TypeError):
operator.length_hint(X("abc"))
with self.assertRaises(ValueError):
operator.length_hint(X(-2))
with self.assertRaises(LookupError):
operator.length_hint(X(LookupError))
def test_dunder_is_original(self):
operator = self.module
names = [name for name in dir(operator) if not name.startswith('_')]
for name in names:
orig = getattr(operator, name)
dunder = getattr(operator, '__' + name.strip('_') + '__', None)
if dunder:
self.assertIs(dunder, orig)
@unittest.skipIf(c_operator, "skip pure-python test if C impl is present")
class PyOperatorTestCase(OperatorTestCase, unittest.TestCase):
module = py_operator
@unittest.skipUnless(c_operator, 'requires _operator')
class COperatorTestCase(OperatorTestCase, unittest.TestCase):
module = c_operator
class OperatorPickleTestCase:
def copy(self, obj, proto):
with support.swap_item(sys.modules, 'operator', self.module):
pickled = pickle.dumps(obj, proto)
with support.swap_item(sys.modules, 'operator', self.module2):
return pickle.loads(pickled)
def test_attrgetter(self):
attrgetter = self.module.attrgetter
class A:
pass
a = A()
a.x = 'X'
a.y = 'Y'
a.z = 'Z'
a.t = A()
a.t.u = A()
a.t.u.v = 'V'
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
with self.subTest(proto=proto):
f = attrgetter('x')
f2 = self.copy(f, proto)
self.assertEqual(repr(f2), repr(f))
self.assertEqual(f2(a), f(a))
# multiple gets
f = attrgetter('x', 'y', 'z')
f2 = self.copy(f, proto)
self.assertEqual(repr(f2), repr(f))
self.assertEqual(f2(a), f(a))
# recursive gets
f = attrgetter('t.u.v')
f2 = self.copy(f, proto)
self.assertEqual(repr(f2), repr(f))
self.assertEqual(f2(a), f(a))
def test_itemgetter(self):
itemgetter = self.module.itemgetter
a = 'ABCDE'
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
with self.subTest(proto=proto):
f = itemgetter(2)
f2 = self.copy(f, proto)
self.assertEqual(repr(f2), repr(f))
self.assertEqual(f2(a), f(a))
# multiple gets
f = itemgetter(2, 0, 4)
f2 = self.copy(f, proto)
self.assertEqual(repr(f2), repr(f))
self.assertEqual(f2(a), f(a))
def test_methodcaller(self):
methodcaller = self.module.methodcaller
class A:
def foo(self, *args, **kwds):
return args[0] + args[1]
def bar(self, f=42):
return f
def baz(*args, **kwds):
return kwds['name'], kwds['self']
a = A()
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
with self.subTest(proto=proto):
f = methodcaller('bar')
f2 = self.copy(f, proto)
self.assertEqual(repr(f2), repr(f))
self.assertEqual(f2(a), f(a))
# positional args
f = methodcaller('foo', 1, 2)
f2 = self.copy(f, proto)
self.assertEqual(repr(f2), repr(f))
self.assertEqual(f2(a), f(a))
# keyword args
f = methodcaller('bar', f=5)
f2 = self.copy(f, proto)
self.assertEqual(repr(f2), repr(f))
self.assertEqual(f2(a), f(a))
f = methodcaller('baz', self='eggs', name='spam')
f2 = self.copy(f, proto)
# Can't test repr consistently with multiple keyword args
self.assertEqual(f2(a), f(a))
class PyPyOperatorPickleTestCase(OperatorPickleTestCase, unittest.TestCase):
module = py_operator
module2 = py_operator
@unittest.skipUnless(c_operator, 'requires _operator')
class PyCOperatorPickleTestCase(OperatorPickleTestCase, unittest.TestCase):
module = py_operator
module2 = c_operator
@unittest.skipUnless(c_operator, 'requires _operator')
class CPyOperatorPickleTestCase(OperatorPickleTestCase, unittest.TestCase):
module = c_operator
module2 = py_operator
@unittest.skipUnless(c_operator, 'requires _operator')
class CCOperatorPickleTestCase(OperatorPickleTestCase, unittest.TestCase):
module = c_operator
module2 = c_operator
if __name__ == "__main__":
unittest.main()
| 23,365 | 611 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_binhex.py | """Test script for the binhex C module
Uses the mechanism of the python binhex module
Based on an original test by Roger E. Masse.
"""
import sys
import binhex
import unittest
from test import support
class BinHexTestCase(unittest.TestCase):
def setUp(self):
self.fname1 = support.TESTFN + "1"
self.fname2 = support.TESTFN + "2"
self.fname3 = support.TESTFN + "very_long_filename__very_long_filename__very_long_filename__very_long_filename__"
def tearDown(self):
support.unlink(self.fname1)
support.unlink(self.fname2)
support.unlink(self.fname3)
DATA = b'Jack is my hero'
def test_binhex(self):
f = open(self.fname1, 'wb')
f.write(self.DATA)
f.close()
binhex.binhex(self.fname1, self.fname2)
binhex.hexbin(self.fname2, self.fname1)
f = open(self.fname1, 'rb')
finish = f.readline()
f.close()
self.assertEqual(self.DATA, finish)
def test_binhex_error_on_long_filename(self):
"""
The testcase fails if no exception is raised when a filename parameter provided to binhex.binhex()
is too long, or if the exception raised in binhex.binhex() is not an instance of binhex.Error.
"""
f3 = open(self.fname3, 'wb')
f3.close()
self.assertRaises(binhex.Error, binhex.binhex, self.fname3, self.fname2)
def test_main():
support.run_unittest(BinHexTestCase)
if __name__ == "__main__":
test_main()
| 1,509 | 57 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_genericpath.py | """
Tests common to genericpath, macpath, ntpath and posixpath
"""
import genericpath
import os
import sys
import unittest
import warnings
from test import support
from test.support.script_helper import assert_python_ok
from test.support import FakePath
def create_file(filename, data=b'foo'):
with open(filename, 'xb', 0) as fp:
fp.write(data)
class GenericTest:
common_attributes = ['commonprefix', 'getsize', 'getatime', 'getctime',
'getmtime', 'exists', 'isdir', 'isfile']
attributes = []
def test_no_argument(self):
for attr in self.common_attributes + self.attributes:
with self.assertRaises(TypeError):
getattr(self.pathmodule, attr)()
raise self.fail("{}.{}() did not raise a TypeError"
.format(self.pathmodule.__name__, attr))
def test_commonprefix(self):
commonprefix = self.pathmodule.commonprefix
self.assertEqual(
commonprefix([]),
""
)
self.assertEqual(
commonprefix(["/home/swenson/spam", "/home/swen/spam"]),
"/home/swen"
)
self.assertEqual(
commonprefix(["/home/swen/spam", "/home/swen/eggs"]),
"/home/swen/"
)
self.assertEqual(
commonprefix(["/home/swen/spam", "/home/swen/spam"]),
"/home/swen/spam"
)
self.assertEqual(
commonprefix(["home:swenson:spam", "home:swen:spam"]),
"home:swen"
)
self.assertEqual(
commonprefix([":home:swen:spam", ":home:swen:eggs"]),
":home:swen:"
)
self.assertEqual(
commonprefix([":home:swen:spam", ":home:swen:spam"]),
":home:swen:spam"
)
self.assertEqual(
commonprefix([b"/home/swenson/spam", b"/home/swen/spam"]),
b"/home/swen"
)
self.assertEqual(
commonprefix([b"/home/swen/spam", b"/home/swen/eggs"]),
b"/home/swen/"
)
self.assertEqual(
commonprefix([b"/home/swen/spam", b"/home/swen/spam"]),
b"/home/swen/spam"
)
self.assertEqual(
commonprefix([b"home:swenson:spam", b"home:swen:spam"]),
b"home:swen"
)
self.assertEqual(
commonprefix([b":home:swen:spam", b":home:swen:eggs"]),
b":home:swen:"
)
self.assertEqual(
commonprefix([b":home:swen:spam", b":home:swen:spam"]),
b":home:swen:spam"
)
testlist = ['', 'abc', 'Xbcd', 'Xb', 'XY', 'abcd',
'aXc', 'abd', 'ab', 'aX', 'abcX']
for s1 in testlist:
for s2 in testlist:
p = commonprefix([s1, s2])
self.assertTrue(s1.startswith(p))
self.assertTrue(s2.startswith(p))
if s1 != s2:
n = len(p)
self.assertNotEqual(s1[n:n+1], s2[n:n+1])
def test_getsize(self):
filename = support.TESTFN
self.addCleanup(support.unlink, filename)
create_file(filename, b'Hello')
self.assertEqual(self.pathmodule.getsize(filename), 5)
os.remove(filename)
create_file(filename, b'Hello World!')
self.assertEqual(self.pathmodule.getsize(filename), 12)
def test_filetime(self):
filename = support.TESTFN
self.addCleanup(support.unlink, filename)
create_file(filename, b'foo')
with open(filename, "ab", 0) as f:
f.write(b"bar")
with open(filename, "rb", 0) as f:
data = f.read()
self.assertEqual(data, b"foobar")
self.assertLessEqual(
self.pathmodule.getctime(filename),
self.pathmodule.getmtime(filename)
)
def test_exists(self):
filename = support.TESTFN
bfilename = os.fsencode(filename)
self.addCleanup(support.unlink, filename)
self.assertIs(self.pathmodule.exists(filename), False)
self.assertIs(self.pathmodule.exists(bfilename), False)
create_file(filename)
self.assertIs(self.pathmodule.exists(filename), True)
self.assertIs(self.pathmodule.exists(bfilename), True)
if self.pathmodule is not genericpath:
self.assertIs(self.pathmodule.lexists(filename), True)
self.assertIs(self.pathmodule.lexists(bfilename), True)
@unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
def test_exists_fd(self):
r, w = os.pipe()
try:
self.assertTrue(self.pathmodule.exists(r))
finally:
os.close(r)
os.close(w)
self.assertFalse(self.pathmodule.exists(r))
def test_isdir(self):
filename = support.TESTFN
bfilename = os.fsencode(filename)
self.assertIs(self.pathmodule.isdir(filename), False)
self.assertIs(self.pathmodule.isdir(bfilename), False)
try:
create_file(filename)
self.assertIs(self.pathmodule.isdir(filename), False)
self.assertIs(self.pathmodule.isdir(bfilename), False)
finally:
support.unlink(filename)
try:
os.mkdir(filename)
self.assertIs(self.pathmodule.isdir(filename), True)
self.assertIs(self.pathmodule.isdir(bfilename), True)
finally:
support.rmdir(filename)
def test_isfile(self):
filename = support.TESTFN
bfilename = os.fsencode(filename)
self.assertIs(self.pathmodule.isfile(filename), False)
self.assertIs(self.pathmodule.isfile(bfilename), False)
try:
create_file(filename)
self.assertIs(self.pathmodule.isfile(filename), True)
self.assertIs(self.pathmodule.isfile(bfilename), True)
finally:
support.unlink(filename)
try:
os.mkdir(filename)
self.assertIs(self.pathmodule.isfile(filename), False)
self.assertIs(self.pathmodule.isfile(bfilename), False)
finally:
support.rmdir(filename)
def test_samefile(self):
file1 = support.TESTFN
file2 = support.TESTFN + "2"
self.addCleanup(support.unlink, file1)
self.addCleanup(support.unlink, file2)
create_file(file1)
self.assertTrue(self.pathmodule.samefile(file1, file1))
create_file(file2)
self.assertFalse(self.pathmodule.samefile(file1, file2))
self.assertRaises(TypeError, self.pathmodule.samefile)
def _test_samefile_on_link_func(self, func):
test_fn1 = support.TESTFN
test_fn2 = support.TESTFN + "2"
self.addCleanup(support.unlink, test_fn1)
self.addCleanup(support.unlink, test_fn2)
create_file(test_fn1)
func(os.path.abspath(test_fn1), os.path.abspath(test_fn2))
self.assertTrue(self.pathmodule.samefile(test_fn1, test_fn2))
os.remove(test_fn2)
create_file(test_fn2)
self.assertFalse(self.pathmodule.samefile(test_fn1, test_fn2))
@support.skip_unless_symlink
def test_samefile_on_symlink(self):
self._test_samefile_on_link_func(os.symlink)
def test_samefile_on_link(self):
try:
self._test_samefile_on_link_func(os.link)
except PermissionError as e:
self.skipTest('os.link(): %s' % e)
def test_samestat(self):
test_fn1 = support.TESTFN
test_fn2 = support.TESTFN + "2"
self.addCleanup(support.unlink, test_fn1)
self.addCleanup(support.unlink, test_fn2)
create_file(test_fn1)
stat1 = os.stat(test_fn1)
self.assertTrue(self.pathmodule.samestat(stat1, os.stat(test_fn1)))
create_file(test_fn2)
stat2 = os.stat(test_fn2)
self.assertFalse(self.pathmodule.samestat(stat1, stat2))
self.assertRaises(TypeError, self.pathmodule.samestat)
def _test_samestat_on_link_func(self, func):
test_fn1 = support.TESTFN + "1"
test_fn2 = support.TESTFN + "2"
self.addCleanup(support.unlink, test_fn1)
self.addCleanup(support.unlink, test_fn2)
create_file(test_fn1)
func(os.path.abspath(test_fn1), os.path.abspath(test_fn2))
self.assertTrue(self.pathmodule.samestat(os.stat(test_fn1),
os.stat(test_fn2)))
os.remove(test_fn2)
create_file(test_fn2)
self.assertFalse(self.pathmodule.samestat(os.stat(test_fn1),
os.stat(test_fn2)))
@support.skip_unless_symlink
def test_samestat_on_symlink(self):
self._test_samestat_on_link_func(os.symlink)
def test_samestat_on_link(self):
try:
self._test_samestat_on_link_func(os.link)
except PermissionError as e:
self.skipTest('os.link(): %s' % e)
def test_sameopenfile(self):
filename = support.TESTFN
self.addCleanup(support.unlink, filename)
create_file(filename)
with open(filename, "rb", 0) as fp1:
fd1 = fp1.fileno()
with open(filename, "rb", 0) as fp2:
fd2 = fp2.fileno()
self.assertTrue(self.pathmodule.sameopenfile(fd1, fd2))
class TestGenericTest(GenericTest, unittest.TestCase):
# Issue 16852: GenericTest can't inherit from unittest.TestCase
# for test discovery purposes; CommonTest inherits from GenericTest
# and is only meant to be inherited by others.
pathmodule = genericpath
def test_invalid_paths(self):
for attr in GenericTest.common_attributes:
# os.path.commonprefix doesn't raise ValueError
if attr == 'commonprefix':
continue
func = getattr(self.pathmodule, attr)
with self.subTest(attr=attr):
try:
func('/tmp\udfffabcds')
except (OSError, UnicodeEncodeError):
pass
try:
func(b'/tmp\xffabcds')
except (OSError, UnicodeDecodeError):
pass
with self.assertRaisesRegex(ValueError, 'embedded null'):
func('/tmp\x00abcds')
with self.assertRaisesRegex(ValueError, 'embedded null'):
func(b'/tmp\x00abcds')
# Following TestCase is not supposed to be run from test_genericpath.
# It is inherited by other test modules (macpath, ntpath, posixpath).
class CommonTest(GenericTest):
common_attributes = GenericTest.common_attributes + [
# Properties
'curdir', 'pardir', 'extsep', 'sep',
'pathsep', 'defpath', 'altsep', 'devnull',
# Methods
'normcase', 'splitdrive', 'expandvars', 'normpath', 'abspath',
'join', 'split', 'splitext', 'isabs', 'basename', 'dirname',
'lexists', 'islink', 'ismount', 'expanduser', 'normpath', 'realpath',
]
def test_normcase(self):
normcase = self.pathmodule.normcase
# check that normcase() is idempotent
for p in ["FoO/./BaR", b"FoO/./BaR"]:
p = normcase(p)
self.assertEqual(p, normcase(p))
self.assertEqual(normcase(''), '')
self.assertEqual(normcase(b''), b'')
# check that normcase raises a TypeError for invalid types
for path in (None, True, 0, 2.5, [], bytearray(b''), {'o','o'}):
self.assertRaises(TypeError, normcase, path)
def test_splitdrive(self):
# splitdrive for non-NT paths
splitdrive = self.pathmodule.splitdrive
self.assertEqual(splitdrive("/foo/bar"), ("", "/foo/bar"))
self.assertEqual(splitdrive("foo:bar"), ("", "foo:bar"))
self.assertEqual(splitdrive(":foo:bar"), ("", ":foo:bar"))
self.assertEqual(splitdrive(b"/foo/bar"), (b"", b"/foo/bar"))
self.assertEqual(splitdrive(b"foo:bar"), (b"", b"foo:bar"))
self.assertEqual(splitdrive(b":foo:bar"), (b"", b":foo:bar"))
def test_expandvars(self):
if self.pathmodule.__name__ == 'macpath':
self.skipTest('macpath.expandvars is a stub')
expandvars = self.pathmodule.expandvars
with support.EnvironmentVarGuard() as env:
env.clear()
env["foo"] = "bar"
env["{foo"] = "baz1"
env["{foo}"] = "baz2"
self.assertEqual(expandvars("foo"), "foo")
self.assertEqual(expandvars("$foo bar"), "bar bar")
self.assertEqual(expandvars("${foo}bar"), "barbar")
self.assertEqual(expandvars("$[foo]bar"), "$[foo]bar")
self.assertEqual(expandvars("$bar bar"), "$bar bar")
self.assertEqual(expandvars("$?bar"), "$?bar")
self.assertEqual(expandvars("$foo}bar"), "bar}bar")
self.assertEqual(expandvars("${foo"), "${foo")
self.assertEqual(expandvars("${{foo}}"), "baz1}")
self.assertEqual(expandvars("$foo$foo"), "barbar")
self.assertEqual(expandvars("$bar$bar"), "$bar$bar")
self.assertEqual(expandvars(b"foo"), b"foo")
self.assertEqual(expandvars(b"$foo bar"), b"bar bar")
self.assertEqual(expandvars(b"${foo}bar"), b"barbar")
self.assertEqual(expandvars(b"$[foo]bar"), b"$[foo]bar")
self.assertEqual(expandvars(b"$bar bar"), b"$bar bar")
self.assertEqual(expandvars(b"$?bar"), b"$?bar")
self.assertEqual(expandvars(b"$foo}bar"), b"bar}bar")
self.assertEqual(expandvars(b"${foo"), b"${foo")
self.assertEqual(expandvars(b"${{foo}}"), b"baz1}")
self.assertEqual(expandvars(b"$foo$foo"), b"barbar")
self.assertEqual(expandvars(b"$bar$bar"), b"$bar$bar")
@unittest.skipUnless(support.FS_NONASCII, 'need support.FS_NONASCII')
def test_expandvars_nonascii(self):
if self.pathmodule.__name__ == 'macpath':
self.skipTest('macpath.expandvars is a stub')
expandvars = self.pathmodule.expandvars
def check(value, expected):
self.assertEqual(expandvars(value), expected)
with support.EnvironmentVarGuard() as env:
env.clear()
nonascii = support.FS_NONASCII
env['spam'] = nonascii
env[nonascii] = 'ham' + nonascii
check(nonascii, nonascii)
check('$spam bar', '%s bar' % nonascii)
check('${spam}bar', '%sbar' % nonascii)
check('${%s}bar' % nonascii, 'ham%sbar' % nonascii)
check('$bar%s bar' % nonascii, '$bar%s bar' % nonascii)
check('$spam}bar', '%s}bar' % nonascii)
check(os.fsencode(nonascii), os.fsencode(nonascii))
check(b'$spam bar', os.fsencode('%s bar' % nonascii))
check(b'${spam}bar', os.fsencode('%sbar' % nonascii))
check(os.fsencode('${%s}bar' % nonascii),
os.fsencode('ham%sbar' % nonascii))
check(os.fsencode('$bar%s bar' % nonascii),
os.fsencode('$bar%s bar' % nonascii))
check(b'$spam}bar', os.fsencode('%s}bar' % nonascii))
def test_abspath(self):
self.assertIn("foo", self.pathmodule.abspath("foo"))
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
self.assertIn(b"foo", self.pathmodule.abspath(b"foo"))
# avoid UnicodeDecodeError on Windows
undecodable_path = b'' if sys.platform == 'win32' else b'f\xf2\xf2'
# Abspath returns bytes when the arg is bytes
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
for path in (b'', b'foo', undecodable_path, b'/foo', b'C:\\'):
self.assertIsInstance(self.pathmodule.abspath(path), bytes)
def test_realpath(self):
self.assertIn("foo", self.pathmodule.realpath("foo"))
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
self.assertIn(b"foo", self.pathmodule.realpath(b"foo"))
def test_normpath_issue5827(self):
# Make sure normpath preserves unicode
for path in ('', '.', '/', '\\', '///foo/.//bar//'):
self.assertIsInstance(self.pathmodule.normpath(path), str)
def test_abspath_issue3426(self):
# Check that abspath returns unicode when the arg is unicode
# with both ASCII and non-ASCII cwds.
abspath = self.pathmodule.abspath
for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'):
self.assertIsInstance(abspath(path), str)
unicwd = '\xe7w\xf0'
try:
os.fsencode(unicwd)
except (AttributeError, UnicodeEncodeError):
# FS encoding is probably ASCII
pass
else:
with support.temp_cwd(unicwd):
for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'):
self.assertIsInstance(abspath(path), str)
def test_nonascii_abspath(self):
if (support.TESTFN_UNDECODABLE
# Mac OS X denies the creation of a directory with an invalid
# UTF-8 name. Windows allows creating a directory with an
# arbitrary bytes name, but fails to enter this directory
# (when the bytes name is used).
and sys.platform not in ('win32', 'darwin')):
name = support.TESTFN_UNDECODABLE
elif support.TESTFN_NONASCII:
name = support.TESTFN_NONASCII
else:
self.skipTest("need support.TESTFN_NONASCII")
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
with support.temp_cwd(name):
self.test_abspath()
def test_join_errors(self):
# Check join() raises friendly TypeErrors.
with support.check_warnings(('', BytesWarning), quiet=True):
errmsg = "Can't mix strings and bytes in path components"
with self.assertRaisesRegex(TypeError, errmsg):
self.pathmodule.join(b'bytes', 'str')
with self.assertRaisesRegex(TypeError, errmsg):
self.pathmodule.join('str', b'bytes')
# regression, see #15377
with self.assertRaisesRegex(TypeError, 'int'):
self.pathmodule.join(42, 'str')
with self.assertRaisesRegex(TypeError, 'int'):
self.pathmodule.join('str', 42)
with self.assertRaisesRegex(TypeError, 'int'):
self.pathmodule.join(42)
with self.assertRaisesRegex(TypeError, 'list'):
self.pathmodule.join([])
with self.assertRaisesRegex(TypeError, 'bytearray'):
self.pathmodule.join(bytearray(b'foo'), bytearray(b'bar'))
def test_relpath_errors(self):
# Check relpath() raises friendly TypeErrors.
with support.check_warnings(('', (BytesWarning, DeprecationWarning)),
quiet=True):
errmsg = "Can't mix strings and bytes in path components"
with self.assertRaisesRegex(TypeError, errmsg):
self.pathmodule.relpath(b'bytes', 'str')
with self.assertRaisesRegex(TypeError, errmsg):
self.pathmodule.relpath('str', b'bytes')
with self.assertRaisesRegex(TypeError, 'int'):
self.pathmodule.relpath(42, 'str')
with self.assertRaisesRegex(TypeError, 'int'):
self.pathmodule.relpath('str', 42)
with self.assertRaisesRegex(TypeError, 'bytearray'):
self.pathmodule.relpath(bytearray(b'foo'), bytearray(b'bar'))
def test_import(self):
assert_python_ok('-S', '-c', 'import ' + self.pathmodule.__name__)
class PathLikeTests(unittest.TestCase):
def setUp(self):
self.file_name = support.TESTFN.lower()
self.file_path = FakePath(support.TESTFN)
self.addCleanup(support.unlink, self.file_name)
create_file(self.file_name, b"test_genericpath.PathLikeTests")
def assertPathEqual(self, func):
self.assertEqual(func(self.file_path), func(self.file_name))
def test_path_exists(self):
self.assertPathEqual(os.path.exists)
def test_path_isfile(self):
self.assertPathEqual(os.path.isfile)
def test_path_isdir(self):
self.assertPathEqual(os.path.isdir)
def test_path_commonprefix(self):
self.assertEqual(os.path.commonprefix([self.file_path, self.file_name]),
self.file_name)
def test_path_getsize(self):
self.assertPathEqual(os.path.getsize)
def test_path_getmtime(self):
self.assertPathEqual(os.path.getatime)
def test_path_getctime(self):
self.assertPathEqual(os.path.getctime)
def test_path_samefile(self):
self.assertTrue(os.path.samefile(self.file_path, self.file_name))
if __name__ == "__main__":
unittest.main()
| 21,101 | 555 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_poplib.py | """Test script for poplib module."""
# Modified by Giampaolo Rodola' to give poplib.POP3 and poplib.POP3_SSL
# a real test suite
import poplib
import asyncore
import asynchat
import socket
import os
import errno
from unittest import TestCase, skipUnless
from test import support as test_support
threading = test_support.import_module('threading')
HOST = test_support.HOST
PORT = 0
SUPPORTS_SSL = False
if hasattr(poplib, 'POP3_SSL'):
try:
import ssl
except ImportError:
assert False
SUPPORTS_SSL = True
CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert3.pem")
CAFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "pycacert.pem")
requires_ssl = skipUnless(SUPPORTS_SSL, 'SSL not supported')
# the dummy data returned by server when LIST and RETR commands are issued
LIST_RESP = b'1 1\r\n2 2\r\n3 3\r\n4 4\r\n5 5\r\n.\r\n'
RETR_RESP = b"""From: [email protected]\
\r\nContent-Type: text/plain\r\n\
MIME-Version: 1.0\r\n\
Subject: Dummy\r\n\
\r\n\
line1\r\n\
line2\r\n\
line3\r\n\
.\r\n"""
class DummyPOP3Handler(asynchat.async_chat):
CAPAS = {'UIDL': [], 'IMPLEMENTATION': ['python-testlib-pop-server']}
enable_UTF8 = False
def __init__(self, conn):
asynchat.async_chat.__init__(self, conn)
self.set_terminator(b"\r\n")
self.in_buffer = []
self.push('+OK dummy pop3 server ready. <timestamp>')
self.tls_active = False
self.tls_starting = False
def collect_incoming_data(self, data):
self.in_buffer.append(data)
def found_terminator(self):
line = b''.join(self.in_buffer)
line = str(line, 'ISO-8859-1')
self.in_buffer = []
cmd = line.split(' ')[0].lower()
space = line.find(' ')
if space != -1:
arg = line[space + 1:]
else:
arg = ""
if hasattr(self, 'cmd_' + cmd):
method = getattr(self, 'cmd_' + cmd)
method(arg)
else:
self.push('-ERR unrecognized POP3 command "%s".' %cmd)
def handle_error(self):
raise
def push(self, data):
asynchat.async_chat.push(self, data.encode("ISO-8859-1") + b'\r\n')
def cmd_echo(self, arg):
# sends back the received string (used by the test suite)
self.push(arg)
def cmd_user(self, arg):
if arg != "guido":
self.push("-ERR no such user")
self.push('+OK password required')
def cmd_pass(self, arg):
if arg != "python":
self.push("-ERR wrong password")
self.push('+OK 10 messages')
def cmd_stat(self, arg):
self.push('+OK 10 100')
def cmd_list(self, arg):
if arg:
self.push('+OK %s %s' % (arg, arg))
else:
self.push('+OK')
asynchat.async_chat.push(self, LIST_RESP)
cmd_uidl = cmd_list
def cmd_retr(self, arg):
self.push('+OK %s bytes' %len(RETR_RESP))
asynchat.async_chat.push(self, RETR_RESP)
cmd_top = cmd_retr
def cmd_dele(self, arg):
self.push('+OK message marked for deletion.')
def cmd_noop(self, arg):
self.push('+OK done nothing.')
def cmd_rpop(self, arg):
self.push('+OK done nothing.')
def cmd_apop(self, arg):
self.push('+OK done nothing.')
def cmd_quit(self, arg):
self.push('+OK closing.')
self.close_when_done()
def _get_capas(self):
_capas = dict(self.CAPAS)
if not self.tls_active and SUPPORTS_SSL:
_capas['STLS'] = []
return _capas
def cmd_capa(self, arg):
self.push('+OK Capability list follows')
if self._get_capas():
for cap, params in self._get_capas().items():
_ln = [cap]
if params:
_ln.extend(params)
self.push(' '.join(_ln))
self.push('.')
def cmd_utf8(self, arg):
self.push('+OK I know RFC6856'
if self.enable_UTF8
else '-ERR What is UTF8?!')
if SUPPORTS_SSL:
def cmd_stls(self, arg):
if self.tls_active is False:
self.push('+OK Begin TLS negotiation')
context = ssl.SSLContext()
context.load_cert_chain(CERTFILE)
tls_sock = context.wrap_socket(self.socket,
server_side=True,
do_handshake_on_connect=False,
suppress_ragged_eofs=False)
self.del_channel()
self.set_socket(tls_sock)
self.tls_active = True
self.tls_starting = True
self.in_buffer = []
self._do_tls_handshake()
else:
self.push('-ERR Command not permitted when TLS active')
def _do_tls_handshake(self):
try:
self.socket.do_handshake()
except ssl.SSLError as err:
if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
ssl.SSL_ERROR_WANT_WRITE):
return
elif err.args[0] == ssl.SSL_ERROR_EOF:
return self.handle_close()
raise
except OSError as err:
if err.args[0] == errno.ECONNABORTED:
return self.handle_close()
else:
self.tls_active = True
self.tls_starting = False
def handle_read(self):
if self.tls_starting:
self._do_tls_handshake()
else:
try:
asynchat.async_chat.handle_read(self)
except ssl.SSLEOFError:
self.handle_close()
class DummyPOP3Server(asyncore.dispatcher, threading.Thread):
handler = DummyPOP3Handler
def __init__(self, address, af=socket.AF_INET):
threading.Thread.__init__(self)
asyncore.dispatcher.__init__(self)
self.create_socket(af, socket.SOCK_STREAM)
self.bind(address)
self.listen(5)
self.active = False
self.active_lock = threading.Lock()
self.host, self.port = self.socket.getsockname()[:2]
self.handler_instance = None
def start(self):
assert not self.active
self.__flag = threading.Event()
threading.Thread.start(self)
self.__flag.wait()
def run(self):
self.active = True
self.__flag.set()
try:
while self.active and asyncore.socket_map:
with self.active_lock:
asyncore.loop(timeout=0.1, count=1)
finally:
asyncore.close_all(ignore_all=True)
def stop(self):
assert self.active
self.active = False
self.join()
def handle_accepted(self, conn, addr):
self.handler_instance = self.handler(conn)
def handle_connect(self):
self.close()
handle_read = handle_connect
def writable(self):
return 0
def handle_error(self):
raise
class TestPOP3Class(TestCase):
def assertOK(self, resp):
self.assertTrue(resp.startswith(b"+OK"))
def setUp(self):
self.server = DummyPOP3Server((HOST, PORT))
self.server.start()
self.client = poplib.POP3(self.server.host, self.server.port, timeout=3)
def tearDown(self):
self.client.close()
self.server.stop()
# Explicitly clear the attribute to prevent dangling thread
self.server = None
def test_getwelcome(self):
self.assertEqual(self.client.getwelcome(),
b'+OK dummy pop3 server ready. <timestamp>')
def test_exceptions(self):
self.assertRaises(poplib.error_proto, self.client._shortcmd, 'echo -err')
def test_user(self):
self.assertOK(self.client.user('guido'))
self.assertRaises(poplib.error_proto, self.client.user, 'invalid')
def test_pass_(self):
self.assertOK(self.client.pass_('python'))
self.assertRaises(poplib.error_proto, self.client.user, 'invalid')
def test_stat(self):
self.assertEqual(self.client.stat(), (10, 100))
def test_list(self):
self.assertEqual(self.client.list()[1:],
([b'1 1', b'2 2', b'3 3', b'4 4', b'5 5'],
25))
self.assertTrue(self.client.list('1').endswith(b"OK 1 1"))
def test_retr(self):
expected = (b'+OK 116 bytes',
[b'From: [email protected]', b'Content-Type: text/plain',
b'MIME-Version: 1.0', b'Subject: Dummy',
b'', b'line1', b'line2', b'line3'],
113)
foo = self.client.retr('foo')
self.assertEqual(foo, expected)
def test_too_long_lines(self):
self.assertRaises(poplib.error_proto, self.client._shortcmd,
'echo +%s' % ((poplib._MAXLINE + 10) * 'a'))
def test_dele(self):
self.assertOK(self.client.dele('foo'))
def test_noop(self):
self.assertOK(self.client.noop())
def test_rpop(self):
self.assertOK(self.client.rpop('foo'))
def test_apop_normal(self):
self.assertOK(self.client.apop('foo', 'dummypassword'))
def test_apop_REDOS(self):
# Replace welcome with very long evil welcome.
# NB The upper bound on welcome length is currently 2048.
# At this length, evil input makes each apop call take
# on the order of milliseconds instead of microseconds.
evil_welcome = b'+OK' + (b'<' * 1000000)
with test_support.swap_attr(self.client, 'welcome', evil_welcome):
# The evil welcome is invalid, so apop should throw.
self.assertRaises(poplib.error_proto, self.client.apop, 'a', 'kb')
def test_top(self):
expected = (b'+OK 116 bytes',
[b'From: [email protected]', b'Content-Type: text/plain',
b'MIME-Version: 1.0', b'Subject: Dummy', b'',
b'line1', b'line2', b'line3'],
113)
self.assertEqual(self.client.top(1, 1), expected)
def test_uidl(self):
self.client.uidl()
self.client.uidl('foo')
def test_utf8_raises_if_unsupported(self):
self.server.handler.enable_UTF8 = False
self.assertRaises(poplib.error_proto, self.client.utf8)
def test_utf8(self):
self.server.handler.enable_UTF8 = True
expected = b'+OK I know RFC6856'
result = self.client.utf8()
self.assertEqual(result, expected)
def test_capa(self):
capa = self.client.capa()
self.assertTrue('IMPLEMENTATION' in capa.keys())
def test_quit(self):
resp = self.client.quit()
self.assertTrue(resp)
self.assertIsNone(self.client.sock)
self.assertIsNone(self.client.file)
@requires_ssl
def test_stls_capa(self):
capa = self.client.capa()
self.assertTrue('STLS' in capa.keys())
@requires_ssl
def test_stls(self):
expected = b'+OK Begin TLS negotiation'
resp = self.client.stls()
self.assertEqual(resp, expected)
@requires_ssl
def test_stls_context(self):
expected = b'+OK Begin TLS negotiation'
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS)
ctx.load_verify_locations(CAFILE)
ctx.verify_mode = ssl.CERT_REQUIRED
ctx.check_hostname = True
with self.assertRaises(ssl.CertificateError):
resp = self.client.stls(context=ctx)
self.client = poplib.POP3("localhost", self.server.port, timeout=3)
resp = self.client.stls(context=ctx)
self.assertEqual(resp, expected)
if SUPPORTS_SSL:
from test.test_ftplib import SSLConnection
class DummyPOP3_SSLHandler(SSLConnection, DummyPOP3Handler):
def __init__(self, conn):
asynchat.async_chat.__init__(self, conn)
self.secure_connection()
self.set_terminator(b"\r\n")
self.in_buffer = []
self.push('+OK dummy pop3 server ready. <timestamp>')
self.tls_active = True
self.tls_starting = False
@requires_ssl
class TestPOP3_SSLClass(TestPOP3Class):
# repeat previous tests by using poplib.POP3_SSL
def setUp(self):
self.server = DummyPOP3Server((HOST, PORT))
self.server.handler = DummyPOP3_SSLHandler
self.server.start()
self.client = poplib.POP3_SSL(self.server.host, self.server.port)
def test__all__(self):
self.assertIn('POP3_SSL', poplib.__all__)
def test_context(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS)
self.assertRaises(ValueError, poplib.POP3_SSL, self.server.host,
self.server.port, keyfile=CERTFILE, context=ctx)
self.assertRaises(ValueError, poplib.POP3_SSL, self.server.host,
self.server.port, certfile=CERTFILE, context=ctx)
self.assertRaises(ValueError, poplib.POP3_SSL, self.server.host,
self.server.port, keyfile=CERTFILE,
certfile=CERTFILE, context=ctx)
self.client.quit()
self.client = poplib.POP3_SSL(self.server.host, self.server.port,
context=ctx)
self.assertIsInstance(self.client.sock, ssl.SSLSocket)
self.assertIs(self.client.sock.context, ctx)
self.assertTrue(self.client.noop().startswith(b'+OK'))
def test_stls(self):
self.assertRaises(poplib.error_proto, self.client.stls)
test_stls_context = test_stls
def test_stls_capa(self):
capa = self.client.capa()
self.assertFalse('STLS' in capa.keys())
@requires_ssl
class TestPOP3_TLSClass(TestPOP3Class):
# repeat previous tests by using poplib.POP3.stls()
def setUp(self):
self.server = DummyPOP3Server((HOST, PORT))
self.server.start()
self.client = poplib.POP3(self.server.host, self.server.port, timeout=3)
self.client.stls()
def tearDown(self):
if self.client.file is not None and self.client.sock is not None:
try:
self.client.quit()
except poplib.error_proto:
# happens in the test_too_long_lines case; the overlong
# response will be treated as response to QUIT and raise
# this exception
self.client.close()
self.server.stop()
# Explicitly clear the attribute to prevent dangling thread
self.server = None
def test_stls(self):
self.assertRaises(poplib.error_proto, self.client.stls)
test_stls_context = test_stls
def test_stls_capa(self):
capa = self.client.capa()
self.assertFalse(b'STLS' in capa.keys())
class TestTimeouts(TestCase):
def setUp(self):
self.evt = threading.Event()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(60) # Safety net. Look issue 11812
self.port = test_support.bind_port(self.sock)
self.thread = threading.Thread(target=self.server, args=(self.evt,self.sock))
self.thread.setDaemon(True)
self.thread.start()
self.evt.wait()
def tearDown(self):
self.thread.join()
# Explicitly clear the attribute to prevent dangling thread
self.thread = None
def server(self, evt, serv):
serv.listen()
evt.set()
try:
conn, addr = serv.accept()
conn.send(b"+ Hola mundo\n")
conn.close()
except socket.timeout:
pass
finally:
serv.close()
def testTimeoutDefault(self):
self.assertIsNone(socket.getdefaulttimeout())
socket.setdefaulttimeout(30)
try:
pop = poplib.POP3(HOST, self.port)
finally:
socket.setdefaulttimeout(None)
self.assertEqual(pop.sock.gettimeout(), 30)
pop.close()
def testTimeoutNone(self):
self.assertIsNone(socket.getdefaulttimeout())
socket.setdefaulttimeout(30)
try:
pop = poplib.POP3(HOST, self.port, timeout=None)
finally:
socket.setdefaulttimeout(None)
self.assertIsNone(pop.sock.gettimeout())
pop.close()
def testTimeoutValue(self):
pop = poplib.POP3(HOST, self.port, timeout=30)
self.assertEqual(pop.sock.gettimeout(), 30)
pop.close()
def test_main():
tests = [TestPOP3Class, TestTimeouts,
TestPOP3_SSLClass, TestPOP3_TLSClass]
thread_info = test_support.threading_setup()
try:
test_support.run_unittest(*tests)
finally:
test_support.threading_cleanup(*thread_info)
if __name__ == '__main__':
test_main()
| 16,978 | 535 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_timeit.py | import cosmo
import timeit
import unittest
import sys
import io
import time
from textwrap import dedent
from test.support import captured_stdout
from test.support import captured_stderr
# timeit's default number of iterations.
DEFAULT_NUMBER = 1000000
# timeit's default number of repetitions.
DEFAULT_REPEAT = 3
# XXX: some tests are commented out that would improve the coverage but take a
# long time to run because they test the default number of loops, which is
# large. The tests could be enabled if there was a way to override the default
# number of loops during testing, but this would require changing the signature
# of some functions that use the default as a default argument.
class FakeTimer:
BASE_TIME = 42.0
def __init__(self, seconds_per_increment=1.0):
self.count = 0
self.setup_calls = 0
self.seconds_per_increment=seconds_per_increment
timeit._fake_timer = self
def __call__(self):
return self.BASE_TIME + self.count * self.seconds_per_increment
def inc(self):
self.count += 1
def setup(self):
self.setup_calls += 1
def wrap_timer(self, timer):
"""Records 'timer' and returns self as callable timer."""
self.saved_timer = timer
return self
class TestTimeit(unittest.TestCase):
def tearDown(self):
try:
del timeit._fake_timer
except AttributeError:
pass
def test_reindent_empty(self):
self.assertEqual(timeit.reindent("", 0), "")
self.assertEqual(timeit.reindent("", 4), "")
def test_reindent_single(self):
self.assertEqual(timeit.reindent("pass", 0), "pass")
self.assertEqual(timeit.reindent("pass", 4), "pass")
def test_reindent_multi_empty(self):
self.assertEqual(timeit.reindent("\n\n", 0), "\n\n")
self.assertEqual(timeit.reindent("\n\n", 4), "\n \n ")
def test_reindent_multi(self):
self.assertEqual(timeit.reindent(
"print()\npass\nbreak", 0),
"print()\npass\nbreak")
self.assertEqual(timeit.reindent(
"print()\npass\nbreak", 4),
"print()\n pass\n break")
def test_timer_invalid_stmt(self):
self.assertRaises(ValueError, timeit.Timer, stmt=None)
self.assertRaises(SyntaxError, timeit.Timer, stmt='return')
self.assertRaises(SyntaxError, timeit.Timer, stmt='yield')
self.assertRaises(SyntaxError, timeit.Timer, stmt='yield from ()')
self.assertRaises(SyntaxError, timeit.Timer, stmt='break')
self.assertRaises(SyntaxError, timeit.Timer, stmt='continue')
self.assertRaises(SyntaxError, timeit.Timer, stmt='from timeit import *')
def test_timer_invalid_setup(self):
self.assertRaises(ValueError, timeit.Timer, setup=None)
self.assertRaises(SyntaxError, timeit.Timer, setup='return')
self.assertRaises(SyntaxError, timeit.Timer, setup='yield')
self.assertRaises(SyntaxError, timeit.Timer, setup='yield from ()')
self.assertRaises(SyntaxError, timeit.Timer, setup='break')
self.assertRaises(SyntaxError, timeit.Timer, setup='continue')
self.assertRaises(SyntaxError, timeit.Timer, setup='from timeit import *')
fake_setup = "import timeit\ntimeit._fake_timer.setup()"
fake_stmt = "import timeit\ntimeit._fake_timer.inc()"
def fake_callable_setup(self):
self.fake_timer.setup()
def fake_callable_stmt(self):
self.fake_timer.inc()
def timeit(self, stmt, setup, number=None, globals=None):
self.fake_timer = FakeTimer()
t = timeit.Timer(stmt=stmt, setup=setup, timer=self.fake_timer,
globals=globals)
kwargs = {}
if number is None:
number = DEFAULT_NUMBER
else:
kwargs['number'] = number
delta_time = t.timeit(**kwargs)
self.assertEqual(self.fake_timer.setup_calls, 1)
self.assertEqual(self.fake_timer.count, number)
self.assertEqual(delta_time, number)
# Takes too long to run in debug build.
#def test_timeit_default_iters(self):
# self.timeit(self.fake_stmt, self.fake_setup)
def test_timeit_zero_iters(self):
self.timeit(self.fake_stmt, self.fake_setup, number=0)
def test_timeit_few_iters(self):
self.timeit(self.fake_stmt, self.fake_setup, number=3)
def test_timeit_callable_stmt(self):
self.timeit(self.fake_callable_stmt, self.fake_setup, number=3)
def test_timeit_callable_setup(self):
self.timeit(self.fake_stmt, self.fake_callable_setup, number=3)
def test_timeit_callable_stmt_and_setup(self):
self.timeit(self.fake_callable_stmt,
self.fake_callable_setup, number=3)
# Takes too long to run in debug build.
#def test_timeit_function(self):
# delta_time = timeit.timeit(self.fake_stmt, self.fake_setup,
# timer=FakeTimer())
# self.assertEqual(delta_time, DEFAULT_NUMBER)
def test_timeit_function_zero_iters(self):
delta_time = timeit.timeit(self.fake_stmt, self.fake_setup, number=0,
timer=FakeTimer())
self.assertEqual(delta_time, 0)
def test_timeit_globals_args(self):
global _global_timer
_global_timer = FakeTimer()
t = timeit.Timer(stmt='_global_timer.inc()', timer=_global_timer)
self.assertRaises(NameError, t.timeit, number=3)
timeit.timeit(stmt='_global_timer.inc()', timer=_global_timer,
globals=globals(), number=3)
local_timer = FakeTimer()
timeit.timeit(stmt='local_timer.inc()', timer=local_timer,
globals=locals(), number=3)
def repeat(self, stmt, setup, repeat=None, number=None):
self.fake_timer = FakeTimer()
t = timeit.Timer(stmt=stmt, setup=setup, timer=self.fake_timer)
kwargs = {}
if repeat is None:
repeat = DEFAULT_REPEAT
else:
kwargs['repeat'] = repeat
if number is None:
number = DEFAULT_NUMBER
else:
kwargs['number'] = number
delta_times = t.repeat(**kwargs)
self.assertEqual(self.fake_timer.setup_calls, repeat)
self.assertEqual(self.fake_timer.count, repeat * number)
self.assertEqual(delta_times, repeat * [float(number)])
# Takes too long to run in debug build.
#def test_repeat_default(self):
# self.repeat(self.fake_stmt, self.fake_setup)
def test_repeat_zero_reps(self):
self.repeat(self.fake_stmt, self.fake_setup, repeat=0)
def test_repeat_zero_iters(self):
self.repeat(self.fake_stmt, self.fake_setup, number=0)
def test_repeat_few_reps_and_iters(self):
self.repeat(self.fake_stmt, self.fake_setup, repeat=3, number=5)
def test_repeat_callable_stmt(self):
self.repeat(self.fake_callable_stmt, self.fake_setup,
repeat=3, number=5)
def test_repeat_callable_setup(self):
self.repeat(self.fake_stmt, self.fake_callable_setup,
repeat=3, number=5)
def test_repeat_callable_stmt_and_setup(self):
self.repeat(self.fake_callable_stmt, self.fake_callable_setup,
repeat=3, number=5)
# Takes too long to run in debug build.
#def test_repeat_function(self):
# delta_times = timeit.repeat(self.fake_stmt, self.fake_setup,
# timer=FakeTimer())
# self.assertEqual(delta_times, DEFAULT_REPEAT * [float(DEFAULT_NUMBER)])
def test_repeat_function_zero_reps(self):
delta_times = timeit.repeat(self.fake_stmt, self.fake_setup, repeat=0,
timer=FakeTimer())
self.assertEqual(delta_times, [])
def test_repeat_function_zero_iters(self):
delta_times = timeit.repeat(self.fake_stmt, self.fake_setup, number=0,
timer=FakeTimer())
self.assertEqual(delta_times, DEFAULT_REPEAT * [0.0])
def assert_exc_string(self, exc_string, expected_exc_name):
exc_lines = exc_string.splitlines()
self.assertGreater(len(exc_lines), 2)
self.assertTrue(exc_lines[0].startswith('Traceback'))
self.assertTrue(exc_lines[-1].startswith(expected_exc_name))
def test_print_exc(self):
s = io.StringIO()
t = timeit.Timer("1/0")
try:
t.timeit()
except:
t.print_exc(s)
self.assert_exc_string(s.getvalue(), 'ZeroDivisionError')
MAIN_DEFAULT_OUTPUT = "10 loops, best of 3: 1 sec per loop\n"
def run_main(self, seconds_per_increment=1.0, switches=None, timer=None):
if timer is None:
timer = FakeTimer(seconds_per_increment=seconds_per_increment)
if switches is None:
args = []
else:
args = switches[:]
args.append(self.fake_stmt)
# timeit.main() modifies sys.path, so save and restore it.
orig_sys_path = sys.path[:]
with captured_stdout() as s:
timeit.main(args=args, _wrap_timer=timer.wrap_timer)
sys.path[:] = orig_sys_path[:]
return s.getvalue()
def test_main_bad_switch(self):
s = self.run_main(switches=['--bad-switch'])
self.assertEqual(s, dedent("""\
option --bad-switch not recognized
use -h/--help for command line help
"""))
def test_main_seconds(self):
s = self.run_main(seconds_per_increment=5.5)
self.assertEqual(s, "10 loops, best of 3: 5.5 sec per loop\n")
def test_main_milliseconds(self):
s = self.run_main(seconds_per_increment=0.0055)
self.assertEqual(s, "100 loops, best of 3: 5.5 msec per loop\n")
def test_main_microseconds(self):
s = self.run_main(seconds_per_increment=0.0000025, switches=['-n100'])
self.assertEqual(s, "100 loops, best of 3: 2.5 usec per loop\n")
def test_main_fixed_iters(self):
s = self.run_main(seconds_per_increment=2.0, switches=['-n35'])
self.assertEqual(s, "35 loops, best of 3: 2 sec per loop\n")
def test_main_setup(self):
s = self.run_main(seconds_per_increment=2.0,
switches=['-n35', '-s', 'print("CustomSetup")'])
self.assertEqual(s, "CustomSetup\n" * 3 +
"35 loops, best of 3: 2 sec per loop\n")
def test_main_multiple_setups(self):
s = self.run_main(seconds_per_increment=2.0,
switches=['-n35', '-s', 'a = "CustomSetup"', '-s', 'print(a)'])
self.assertEqual(s, "CustomSetup\n" * 3 +
"35 loops, best of 3: 2 sec per loop\n")
def test_main_fixed_reps(self):
s = self.run_main(seconds_per_increment=60.0, switches=['-r9'])
self.assertEqual(s, "10 loops, best of 9: 60 sec per loop\n")
def test_main_negative_reps(self):
s = self.run_main(seconds_per_increment=60.0, switches=['-r-5'])
self.assertEqual(s, "10 loops, best of 1: 60 sec per loop\n")
@unittest.skipIf(cosmo.MODE in ('tiny', 'rel'),
"No docstrings in MODE=tiny/rel")
@unittest.skipIf(sys.flags.optimize >= 2, "need __doc__")
def test_main_help(self):
s = self.run_main(switches=['-h'])
# Note: It's not clear that the trailing space was intended as part of
# the help text, but since it's there, check for it.
self.assertEqual(s, timeit.__doc__ + ' ')
def test_main_using_time(self):
fake_timer = FakeTimer()
s = self.run_main(switches=['-t'], timer=fake_timer)
self.assertEqual(s, self.MAIN_DEFAULT_OUTPUT)
self.assertIs(fake_timer.saved_timer, time.time)
def test_main_using_clock(self):
fake_timer = FakeTimer()
s = self.run_main(switches=['-c'], timer=fake_timer)
self.assertEqual(s, self.MAIN_DEFAULT_OUTPUT)
self.assertIs(fake_timer.saved_timer, time.clock)
def test_main_verbose(self):
s = self.run_main(switches=['-v'])
self.assertEqual(s, dedent("""\
10 loops -> 10 secs
raw times: 10 10 10
10 loops, best of 3: 1 sec per loop
"""))
def test_main_very_verbose(self):
s = self.run_main(seconds_per_increment=0.000050, switches=['-vv'])
self.assertEqual(s, dedent("""\
10 loops -> 0.0005 secs
100 loops -> 0.005 secs
1000 loops -> 0.05 secs
10000 loops -> 0.5 secs
raw times: 0.5 0.5 0.5
10000 loops, best of 3: 50 usec per loop
"""))
def test_main_with_time_unit(self):
unit_sec = self.run_main(seconds_per_increment=0.002,
switches=['-u', 'sec'])
self.assertEqual(unit_sec,
"1000 loops, best of 3: 0.002 sec per loop\n")
unit_msec = self.run_main(seconds_per_increment=0.002,
switches=['-u', 'msec'])
self.assertEqual(unit_msec,
"1000 loops, best of 3: 2 msec per loop\n")
unit_usec = self.run_main(seconds_per_increment=0.002,
switches=['-u', 'usec'])
self.assertEqual(unit_usec,
"1000 loops, best of 3: 2e+03 usec per loop\n")
# Test invalid unit input
with captured_stderr() as error_stringio:
invalid = self.run_main(seconds_per_increment=0.002,
switches=['-u', 'parsec'])
self.assertEqual(error_stringio.getvalue(),
"Unrecognized unit. Please select usec, msec, or sec.\n")
def test_main_exception(self):
with captured_stderr() as error_stringio:
s = self.run_main(switches=['1/0'])
self.assert_exc_string(error_stringio.getvalue(), 'ZeroDivisionError')
def test_main_exception_fixed_reps(self):
with captured_stderr() as error_stringio:
s = self.run_main(switches=['-n1', '1/0'])
self.assert_exc_string(error_stringio.getvalue(), 'ZeroDivisionError')
def autorange(self, callback=None):
timer = FakeTimer(seconds_per_increment=0.001)
t = timeit.Timer(stmt=self.fake_stmt, setup=self.fake_setup, timer=timer)
return t.autorange(callback)
def test_autorange(self):
num_loops, time_taken = self.autorange()
self.assertEqual(num_loops, 1000)
self.assertEqual(time_taken, 1.0)
def test_autorange_with_callback(self):
def callback(a, b):
print("{} {:.3f}".format(a, b))
with captured_stdout() as s:
num_loops, time_taken = self.autorange(callback)
self.assertEqual(num_loops, 1000)
self.assertEqual(time_taken, 1.0)
expected = ('10 0.010\n'
'100 0.100\n'
'1000 1.000\n')
self.assertEqual(s.getvalue(), expected)
if __name__ == '__main__':
unittest.main()
| 14,884 | 385 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_augassign.py | # Augmented assignment test.
import unittest
class AugAssignTest(unittest.TestCase):
def testBasic(self):
x = 2
x += 1
x *= 2
x **= 2
x -= 8
x //= 5
x %= 3
x &= 2
x |= 5
x ^= 1
x /= 2
self.assertEqual(x, 3.0)
def test_with_unpacking(self):
self.assertRaises(SyntaxError, compile, "x, b += 3", "<test>", "exec")
def testInList(self):
x = [2]
x[0] += 1
x[0] *= 2
x[0] **= 2
x[0] -= 8
x[0] //= 5
x[0] %= 3
x[0] &= 2
x[0] |= 5
x[0] ^= 1
x[0] /= 2
self.assertEqual(x[0], 3.0)
def testInDict(self):
x = {0: 2}
x[0] += 1
x[0] *= 2
x[0] **= 2
x[0] -= 8
x[0] //= 5
x[0] %= 3
x[0] &= 2
x[0] |= 5
x[0] ^= 1
x[0] /= 2
self.assertEqual(x[0], 3.0)
def testSequences(self):
x = [1,2]
x += [3,4]
x *= 2
self.assertEqual(x, [1, 2, 3, 4, 1, 2, 3, 4])
x = [1, 2, 3]
y = x
x[1:2] *= 2
y[1:2] += [1]
self.assertEqual(x, [1, 2, 1, 2, 3])
self.assertTrue(x is y)
def testCustomMethods1(self):
class aug_test:
def __init__(self, value):
self.val = value
def __radd__(self, val):
return self.val + val
def __add__(self, val):
return aug_test(self.val + val)
class aug_test2(aug_test):
def __iadd__(self, val):
self.val = self.val + val
return self
class aug_test3(aug_test):
def __iadd__(self, val):
return aug_test3(self.val + val)
class aug_test4(aug_test3):
"""Blocks inheritance, and fallback to __add__"""
__iadd__ = None
x = aug_test(1)
y = x
x += 10
self.assertIsInstance(x, aug_test)
self.assertTrue(y is not x)
self.assertEqual(x.val, 11)
x = aug_test2(2)
y = x
x += 10
self.assertTrue(y is x)
self.assertEqual(x.val, 12)
x = aug_test3(3)
y = x
x += 10
self.assertIsInstance(x, aug_test3)
self.assertTrue(y is not x)
self.assertEqual(x.val, 13)
x = aug_test4(4)
with self.assertRaises(TypeError):
x += 10
def testCustomMethods2(test_self):
output = []
class testall:
def __add__(self, val):
output.append("__add__ called")
def __radd__(self, val):
output.append("__radd__ called")
def __iadd__(self, val):
output.append("__iadd__ called")
return self
def __sub__(self, val):
output.append("__sub__ called")
def __rsub__(self, val):
output.append("__rsub__ called")
def __isub__(self, val):
output.append("__isub__ called")
return self
def __mul__(self, val):
output.append("__mul__ called")
def __rmul__(self, val):
output.append("__rmul__ called")
def __imul__(self, val):
output.append("__imul__ called")
return self
def __matmul__(self, val):
output.append("__matmul__ called")
def __rmatmul__(self, val):
output.append("__rmatmul__ called")
def __imatmul__(self, val):
output.append("__imatmul__ called")
return self
def __floordiv__(self, val):
output.append("__floordiv__ called")
return self
def __ifloordiv__(self, val):
output.append("__ifloordiv__ called")
return self
def __rfloordiv__(self, val):
output.append("__rfloordiv__ called")
return self
def __truediv__(self, val):
output.append("__truediv__ called")
return self
def __rtruediv__(self, val):
output.append("__rtruediv__ called")
return self
def __itruediv__(self, val):
output.append("__itruediv__ called")
return self
def __mod__(self, val):
output.append("__mod__ called")
def __rmod__(self, val):
output.append("__rmod__ called")
def __imod__(self, val):
output.append("__imod__ called")
return self
def __pow__(self, val):
output.append("__pow__ called")
def __rpow__(self, val):
output.append("__rpow__ called")
def __ipow__(self, val):
output.append("__ipow__ called")
return self
def __or__(self, val):
output.append("__or__ called")
def __ror__(self, val):
output.append("__ror__ called")
def __ior__(self, val):
output.append("__ior__ called")
return self
def __and__(self, val):
output.append("__and__ called")
def __rand__(self, val):
output.append("__rand__ called")
def __iand__(self, val):
output.append("__iand__ called")
return self
def __xor__(self, val):
output.append("__xor__ called")
def __rxor__(self, val):
output.append("__rxor__ called")
def __ixor__(self, val):
output.append("__ixor__ called")
return self
def __rshift__(self, val):
output.append("__rshift__ called")
def __rrshift__(self, val):
output.append("__rrshift__ called")
def __irshift__(self, val):
output.append("__irshift__ called")
return self
def __lshift__(self, val):
output.append("__lshift__ called")
def __rlshift__(self, val):
output.append("__rlshift__ called")
def __ilshift__(self, val):
output.append("__ilshift__ called")
return self
x = testall()
x + 1
1 + x
x += 1
x - 1
1 - x
x -= 1
x * 1
1 * x
x *= 1
x @ 1
1 @ x
x @= 1
x / 1
1 / x
x /= 1
x // 1
1 // x
x //= 1
x % 1
1 % x
x %= 1
x ** 1
1 ** x
x **= 1
x | 1
1 | x
x |= 1
x & 1
1 & x
x &= 1
x ^ 1
1 ^ x
x ^= 1
x >> 1
1 >> x
x >>= 1
x << 1
1 << x
x <<= 1
test_self.assertEqual(output, '''\
__add__ called
__radd__ called
__iadd__ called
__sub__ called
__rsub__ called
__isub__ called
__mul__ called
__rmul__ called
__imul__ called
__matmul__ called
__rmatmul__ called
__imatmul__ called
__truediv__ called
__rtruediv__ called
__itruediv__ called
__floordiv__ called
__rfloordiv__ called
__ifloordiv__ called
__mod__ called
__rmod__ called
__imod__ called
__pow__ called
__rpow__ called
__ipow__ called
__or__ called
__ror__ called
__ior__ called
__and__ called
__rand__ called
__iand__ called
__xor__ called
__rxor__ called
__ixor__ called
__rshift__ called
__rrshift__ called
__irshift__ called
__lshift__ called
__rlshift__ called
__ilshift__ called
'''.splitlines())
if __name__ == '__main__':
unittest.main()
| 7,868 | 327 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_array.py | """Test the arraymodule.
Roger E. Masse
"""
import unittest
from test import support
import weakref
import pickle
import operator
import struct
import sys
import warnings
import array
from array import _array_reconstructor as array_reconstructor
sizeof_wchar = array.array('u').itemsize
class ArraySubclass(array.array):
pass
class ArraySubclassWithKwargs(array.array):
def __init__(self, typecode, newarg=None):
array.array.__init__(self)
typecodes = 'ubBhHiIlLfdqQ'
class MiscTest(unittest.TestCase):
def test_bad_constructor(self):
self.assertRaises(TypeError, array.array)
self.assertRaises(TypeError, array.array, spam=42)
self.assertRaises(TypeError, array.array, 'xx')
self.assertRaises(ValueError, array.array, 'x')
def test_empty(self):
# Exercise code for handling zero-length arrays
a = array.array('B')
a[:] = a
self.assertEqual(len(a), 0)
self.assertEqual(len(a + a), 0)
self.assertEqual(len(a * 3), 0)
a += a
self.assertEqual(len(a), 0)
# Machine format codes.
#
# Search for "enum machine_format_code" in Modules/arraymodule.c to get the
# authoritative values.
UNKNOWN_FORMAT = -1
UNSIGNED_INT8 = 0
SIGNED_INT8 = 1
UNSIGNED_INT16_LE = 2
UNSIGNED_INT16_BE = 3
SIGNED_INT16_LE = 4
SIGNED_INT16_BE = 5
UNSIGNED_INT32_LE = 6
UNSIGNED_INT32_BE = 7
SIGNED_INT32_LE = 8
SIGNED_INT32_BE = 9
UNSIGNED_INT64_LE = 10
UNSIGNED_INT64_BE = 11
SIGNED_INT64_LE = 12
SIGNED_INT64_BE = 13
IEEE_754_FLOAT_LE = 14
IEEE_754_FLOAT_BE = 15
IEEE_754_DOUBLE_LE = 16
IEEE_754_DOUBLE_BE = 17
UTF16_LE = 18
UTF16_BE = 19
UTF32_LE = 20
UTF32_BE = 21
class ArrayReconstructorTest(unittest.TestCase):
def test_error(self):
self.assertRaises(TypeError, array_reconstructor,
"", "b", 0, b"")
self.assertRaises(TypeError, array_reconstructor,
str, "b", 0, b"")
self.assertRaises(TypeError, array_reconstructor,
array.array, "b", '', b"")
self.assertRaises(TypeError, array_reconstructor,
array.array, "b", 0, "")
self.assertRaises(ValueError, array_reconstructor,
array.array, "?", 0, b"")
self.assertRaises(ValueError, array_reconstructor,
array.array, "b", UNKNOWN_FORMAT, b"")
self.assertRaises(ValueError, array_reconstructor,
array.array, "b", 22, b"")
self.assertRaises(ValueError, array_reconstructor,
array.array, "d", 16, b"a")
def test_numbers(self):
testcases = (
(['B', 'H', 'I', 'L'], UNSIGNED_INT8, '=BBBB',
[0x80, 0x7f, 0, 0xff]),
(['b', 'h', 'i', 'l'], SIGNED_INT8, '=bbb',
[-0x80, 0x7f, 0]),
(['H', 'I', 'L'], UNSIGNED_INT16_LE, '<HHHH',
[0x8000, 0x7fff, 0, 0xffff]),
(['H', 'I', 'L'], UNSIGNED_INT16_BE, '>HHHH',
[0x8000, 0x7fff, 0, 0xffff]),
(['h', 'i', 'l'], SIGNED_INT16_LE, '<hhh',
[-0x8000, 0x7fff, 0]),
(['h', 'i', 'l'], SIGNED_INT16_BE, '>hhh',
[-0x8000, 0x7fff, 0]),
(['I', 'L'], UNSIGNED_INT32_LE, '<IIII',
[1<<31, (1<<31)-1, 0, (1<<32)-1]),
(['I', 'L'], UNSIGNED_INT32_BE, '>IIII',
[1<<31, (1<<31)-1, 0, (1<<32)-1]),
(['i', 'l'], SIGNED_INT32_LE, '<iii',
[-1<<31, (1<<31)-1, 0]),
(['i', 'l'], SIGNED_INT32_BE, '>iii',
[-1<<31, (1<<31)-1, 0]),
(['L'], UNSIGNED_INT64_LE, '<QQQQ',
[1<<31, (1<<31)-1, 0, (1<<32)-1]),
(['L'], UNSIGNED_INT64_BE, '>QQQQ',
[1<<31, (1<<31)-1, 0, (1<<32)-1]),
(['l'], SIGNED_INT64_LE, '<qqq',
[-1<<31, (1<<31)-1, 0]),
(['l'], SIGNED_INT64_BE, '>qqq',
[-1<<31, (1<<31)-1, 0]),
# The following tests for INT64 will raise an OverflowError
# when run on a 32-bit machine. The tests are simply skipped
# in that case.
(['L'], UNSIGNED_INT64_LE, '<QQQQ',
[1<<63, (1<<63)-1, 0, (1<<64)-1]),
(['L'], UNSIGNED_INT64_BE, '>QQQQ',
[1<<63, (1<<63)-1, 0, (1<<64)-1]),
(['l'], SIGNED_INT64_LE, '<qqq',
[-1<<63, (1<<63)-1, 0]),
(['l'], SIGNED_INT64_BE, '>qqq',
[-1<<63, (1<<63)-1, 0]),
(['f'], IEEE_754_FLOAT_LE, '<ffff',
[16711938.0, float('inf'), float('-inf'), -0.0]),
(['f'], IEEE_754_FLOAT_BE, '>ffff',
[16711938.0, float('inf'), float('-inf'), -0.0]),
(['d'], IEEE_754_DOUBLE_LE, '<dddd',
[9006104071832581.0, float('inf'), float('-inf'), -0.0]),
(['d'], IEEE_754_DOUBLE_BE, '>dddd',
[9006104071832581.0, float('inf'), float('-inf'), -0.0])
)
for testcase in testcases:
valid_typecodes, mformat_code, struct_fmt, values = testcase
arraystr = struct.pack(struct_fmt, *values)
for typecode in valid_typecodes:
try:
a = array.array(typecode, values)
except OverflowError:
continue # Skip this test case.
b = array_reconstructor(
array.array, typecode, mformat_code, arraystr)
self.assertEqual(a, b,
msg="{0!r} != {1!r}; testcase={2!r}".format(a, b, testcase))
def test_unicode(self):
return
teststr = "Bonne Journ\xe9e \U0002030a\U00020347"
testcases = (
(UTF16_LE, "UTF-16-LE"),
(UTF16_BE, "UTF-16-BE"),
(UTF32_LE, "UTF-32-LE"),
(UTF32_BE, "UTF-32-BE")
)
for testcase in testcases:
mformat_code, encoding = testcase
a = array.array('u', teststr)
b = array_reconstructor(
array.array, 'u', mformat_code, teststr.encode(encoding))
self.assertEqual(a, b,
msg="{0!r} != {1!r}; testcase={2!r}".format(a, b, testcase))
class BaseTest:
# Required class attributes (provided by subclasses
# typecode: the typecode to test
# example: an initializer usable in the constructor for this type
# smallerexample: the same length as example, but smaller
# biggerexample: the same length as example, but bigger
# outside: An entry that is not in example
# minitemsize: the minimum guaranteed itemsize
def assertEntryEqual(self, entry1, entry2):
self.assertEqual(entry1, entry2)
def badtypecode(self):
# Return a typecode that is different from our own
return typecodes[(typecodes.index(self.typecode)+1) % len(typecodes)]
def test_constructor(self):
a = array.array(self.typecode)
self.assertEqual(a.typecode, self.typecode)
self.assertGreaterEqual(a.itemsize, self.minitemsize)
self.assertRaises(TypeError, array.array, self.typecode, None)
def test_len(self):
a = array.array(self.typecode)
a.append(self.example[0])
self.assertEqual(len(a), 1)
a = array.array(self.typecode, self.example)
self.assertEqual(len(a), len(self.example))
def test_buffer_info(self):
a = array.array(self.typecode, self.example)
self.assertRaises(TypeError, a.buffer_info, 42)
bi = a.buffer_info()
self.assertIsInstance(bi, tuple)
self.assertEqual(len(bi), 2)
self.assertIsInstance(bi[0], int)
self.assertIsInstance(bi[1], int)
self.assertEqual(bi[1], len(a))
def test_byteswap(self):
if self.typecode == 'u':
example = '\U00100100'
else:
example = self.example
a = array.array(self.typecode, example)
self.assertRaises(TypeError, a.byteswap, 42)
if a.itemsize in (1, 2, 4, 8):
b = array.array(self.typecode, example)
b.byteswap()
if a.itemsize==1:
self.assertEqual(a, b)
else:
self.assertNotEqual(a, b)
b.byteswap()
self.assertEqual(a, b)
def test_copy(self):
import copy
a = array.array(self.typecode, self.example)
b = copy.copy(a)
self.assertNotEqual(id(a), id(b))
self.assertEqual(a, b)
def test_deepcopy(self):
import copy
a = array.array(self.typecode, self.example)
b = copy.deepcopy(a)
self.assertNotEqual(id(a), id(b))
self.assertEqual(a, b)
def test_reduce_ex(self):
a = array.array(self.typecode, self.example)
for protocol in range(3):
self.assertIs(a.__reduce_ex__(protocol)[0], array.array)
for protocol in range(3, pickle.HIGHEST_PROTOCOL):
self.assertIs(a.__reduce_ex__(protocol)[0], array_reconstructor)
def test_pickle(self):
for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
a = array.array(self.typecode, self.example)
b = pickle.loads(pickle.dumps(a, protocol))
self.assertNotEqual(id(a), id(b))
self.assertEqual(a, b)
a = ArraySubclass(self.typecode, self.example)
a.x = 10
b = pickle.loads(pickle.dumps(a, protocol))
self.assertNotEqual(id(a), id(b))
self.assertEqual(a, b)
self.assertEqual(a.x, b.x)
self.assertEqual(type(a), type(b))
def test_pickle_for_empty_array(self):
for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
a = array.array(self.typecode)
b = pickle.loads(pickle.dumps(a, protocol))
self.assertNotEqual(id(a), id(b))
self.assertEqual(a, b)
a = ArraySubclass(self.typecode)
a.x = 10
b = pickle.loads(pickle.dumps(a, protocol))
self.assertNotEqual(id(a), id(b))
self.assertEqual(a, b)
self.assertEqual(a.x, b.x)
self.assertEqual(type(a), type(b))
def test_iterator_pickle(self):
orig = array.array(self.typecode, self.example)
data = list(orig)
data2 = data[::-1]
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
# initial iterator
itorig = iter(orig)
d = pickle.dumps((itorig, orig), proto)
it, a = pickle.loads(d)
a.fromlist(data2)
self.assertEqual(type(it), type(itorig))
self.assertEqual(list(it), data + data2)
# running iterator
next(itorig)
d = pickle.dumps((itorig, orig), proto)
it, a = pickle.loads(d)
a.fromlist(data2)
self.assertEqual(type(it), type(itorig))
self.assertEqual(list(it), data[1:] + data2)
# empty iterator
for i in range(1, len(data)):
next(itorig)
d = pickle.dumps((itorig, orig), proto)
it, a = pickle.loads(d)
a.fromlist(data2)
self.assertEqual(type(it), type(itorig))
self.assertEqual(list(it), data2)
# exhausted iterator
self.assertRaises(StopIteration, next, itorig)
d = pickle.dumps((itorig, orig), proto)
it, a = pickle.loads(d)
a.fromlist(data2)
self.assertEqual(list(it), [])
def test_exhausted_iterator(self):
a = array.array(self.typecode, self.example)
self.assertEqual(list(a), list(self.example))
exhit = iter(a)
empit = iter(a)
for x in exhit: # exhaust the iterator
next(empit) # not exhausted
a.append(self.outside)
self.assertEqual(list(exhit), [])
self.assertEqual(list(empit), [self.outside])
self.assertEqual(list(a), list(self.example) + [self.outside])
def test_insert(self):
a = array.array(self.typecode, self.example)
a.insert(0, self.example[0])
self.assertEqual(len(a), 1+len(self.example))
self.assertEqual(a[0], a[1])
self.assertRaises(TypeError, a.insert)
self.assertRaises(TypeError, a.insert, None)
self.assertRaises(TypeError, a.insert, 0, None)
a = array.array(self.typecode, self.example)
a.insert(-1, self.example[0])
self.assertEqual(
a,
array.array(
self.typecode,
self.example[:-1] + self.example[:1] + self.example[-1:]
)
)
a = array.array(self.typecode, self.example)
a.insert(-1000, self.example[0])
self.assertEqual(
a,
array.array(self.typecode, self.example[:1] + self.example)
)
a = array.array(self.typecode, self.example)
a.insert(1000, self.example[0])
self.assertEqual(
a,
array.array(self.typecode, self.example + self.example[:1])
)
def test_tofromfile(self):
a = array.array(self.typecode, 2*self.example)
self.assertRaises(TypeError, a.tofile)
support.unlink(support.TESTFN)
f = open(support.TESTFN, 'wb')
try:
a.tofile(f)
f.close()
b = array.array(self.typecode)
f = open(support.TESTFN, 'rb')
self.assertRaises(TypeError, b.fromfile)
b.fromfile(f, len(self.example))
self.assertEqual(b, array.array(self.typecode, self.example))
self.assertNotEqual(a, b)
self.assertRaises(EOFError, b.fromfile, f, len(self.example)+1)
self.assertEqual(a, b)
f.close()
finally:
if not f.closed:
f.close()
support.unlink(support.TESTFN)
def test_fromfile_ioerror(self):
# Issue #5395: Check if fromfile raises a proper OSError
# instead of EOFError.
a = array.array(self.typecode)
f = open(support.TESTFN, 'wb')
try:
self.assertRaises(OSError, a.fromfile, f, len(self.example))
finally:
f.close()
support.unlink(support.TESTFN)
def test_filewrite(self):
a = array.array(self.typecode, 2*self.example)
f = open(support.TESTFN, 'wb')
try:
f.write(a)
f.close()
b = array.array(self.typecode)
f = open(support.TESTFN, 'rb')
b.fromfile(f, len(self.example))
self.assertEqual(b, array.array(self.typecode, self.example))
self.assertNotEqual(a, b)
b.fromfile(f, len(self.example))
self.assertEqual(a, b)
f.close()
finally:
if not f.closed:
f.close()
support.unlink(support.TESTFN)
def test_tofromlist(self):
a = array.array(self.typecode, 2*self.example)
b = array.array(self.typecode)
self.assertRaises(TypeError, a.tolist, 42)
self.assertRaises(TypeError, b.fromlist)
self.assertRaises(TypeError, b.fromlist, 42)
self.assertRaises(TypeError, b.fromlist, [None])
b.fromlist(a.tolist())
self.assertEqual(a, b)
def test_tofromstring(self):
# Warnings not raised when arguments are incorrect as Argument Clinic
# handles that before the warning can be raised.
nb_warnings = 2
with warnings.catch_warnings(record=True) as r:
warnings.filterwarnings("always",
message=r"(to|from)string\(\) is deprecated",
category=DeprecationWarning)
a = array.array(self.typecode, 2*self.example)
b = array.array(self.typecode)
self.assertRaises(TypeError, a.tostring, 42)
self.assertRaises(TypeError, b.fromstring)
self.assertRaises(TypeError, b.fromstring, 42)
b.fromstring(a.tostring())
self.assertEqual(a, b)
if a.itemsize>1:
self.assertRaises(ValueError, b.fromstring, "x")
nb_warnings += 1
self.assertEqual(len(r), nb_warnings)
def test_tofrombytes(self):
a = array.array(self.typecode, 2*self.example)
b = array.array(self.typecode)
self.assertRaises(TypeError, a.tobytes, 42)
self.assertRaises(TypeError, b.frombytes)
self.assertRaises(TypeError, b.frombytes, 42)
b.frombytes(a.tobytes())
c = array.array(self.typecode, bytearray(a.tobytes()))
self.assertEqual(a, b)
self.assertEqual(a, c)
if a.itemsize>1:
self.assertRaises(ValueError, b.frombytes, b"x")
def test_fromarray(self):
a = array.array(self.typecode, self.example)
b = array.array(self.typecode, a)
self.assertEqual(a, b)
def test_repr(self):
a = array.array(self.typecode, 2*self.example)
self.assertEqual(a, eval(repr(a), {"array": array.array}))
a = array.array(self.typecode)
self.assertEqual(repr(a), "array('%s')" % self.typecode)
def test_str(self):
a = array.array(self.typecode, 2*self.example)
str(a)
def test_cmp(self):
a = array.array(self.typecode, self.example)
self.assertIs(a == 42, False)
self.assertIs(a != 42, True)
self.assertIs(a == a, True)
self.assertIs(a != a, False)
self.assertIs(a < a, False)
self.assertIs(a <= a, True)
self.assertIs(a > a, False)
self.assertIs(a >= a, True)
al = array.array(self.typecode, self.smallerexample)
ab = array.array(self.typecode, self.biggerexample)
self.assertIs(a == 2*a, False)
self.assertIs(a != 2*a, True)
self.assertIs(a < 2*a, True)
self.assertIs(a <= 2*a, True)
self.assertIs(a > 2*a, False)
self.assertIs(a >= 2*a, False)
self.assertIs(a == al, False)
self.assertIs(a != al, True)
self.assertIs(a < al, False)
self.assertIs(a <= al, False)
self.assertIs(a > al, True)
self.assertIs(a >= al, True)
self.assertIs(a == ab, False)
self.assertIs(a != ab, True)
self.assertIs(a < ab, True)
self.assertIs(a <= ab, True)
self.assertIs(a > ab, False)
self.assertIs(a >= ab, False)
def test_add(self):
a = array.array(self.typecode, self.example) \
+ array.array(self.typecode, self.example[::-1])
self.assertEqual(
a,
array.array(self.typecode, self.example + self.example[::-1])
)
b = array.array(self.badtypecode())
self.assertRaises(TypeError, a.__add__, b)
self.assertRaises(TypeError, a.__add__, "bad")
def test_iadd(self):
a = array.array(self.typecode, self.example[::-1])
b = a
a += array.array(self.typecode, 2*self.example)
self.assertIs(a, b)
self.assertEqual(
a,
array.array(self.typecode, self.example[::-1]+2*self.example)
)
a = array.array(self.typecode, self.example)
a += a
self.assertEqual(
a,
array.array(self.typecode, self.example + self.example)
)
b = array.array(self.badtypecode())
self.assertRaises(TypeError, a.__add__, b)
self.assertRaises(TypeError, a.__iadd__, "bad")
def test_mul(self):
a = 5*array.array(self.typecode, self.example)
self.assertEqual(
a,
array.array(self.typecode, 5*self.example)
)
a = array.array(self.typecode, self.example)*5
self.assertEqual(
a,
array.array(self.typecode, self.example*5)
)
a = 0*array.array(self.typecode, self.example)
self.assertEqual(
a,
array.array(self.typecode)
)
a = (-1)*array.array(self.typecode, self.example)
self.assertEqual(
a,
array.array(self.typecode)
)
a = 5 * array.array(self.typecode, self.example[:1])
self.assertEqual(
a,
array.array(self.typecode, [a[0]] * 5)
)
self.assertRaises(TypeError, a.__mul__, "bad")
def test_imul(self):
a = array.array(self.typecode, self.example)
b = a
a *= 5
self.assertIs(a, b)
self.assertEqual(
a,
array.array(self.typecode, 5*self.example)
)
a *= 0
self.assertIs(a, b)
self.assertEqual(a, array.array(self.typecode))
a *= 1000
self.assertIs(a, b)
self.assertEqual(a, array.array(self.typecode))
a *= -1
self.assertIs(a, b)
self.assertEqual(a, array.array(self.typecode))
a = array.array(self.typecode, self.example)
a *= -1
self.assertEqual(a, array.array(self.typecode))
self.assertRaises(TypeError, a.__imul__, "bad")
def test_getitem(self):
a = array.array(self.typecode, self.example)
self.assertEntryEqual(a[0], self.example[0])
self.assertEntryEqual(a[0], self.example[0])
self.assertEntryEqual(a[-1], self.example[-1])
self.assertEntryEqual(a[-1], self.example[-1])
self.assertEntryEqual(a[len(self.example)-1], self.example[-1])
self.assertEntryEqual(a[-len(self.example)], self.example[0])
self.assertRaises(TypeError, a.__getitem__)
self.assertRaises(IndexError, a.__getitem__, len(self.example))
self.assertRaises(IndexError, a.__getitem__, -len(self.example)-1)
def test_setitem(self):
a = array.array(self.typecode, self.example)
a[0] = a[-1]
self.assertEntryEqual(a[0], a[-1])
a = array.array(self.typecode, self.example)
a[0] = a[-1]
self.assertEntryEqual(a[0], a[-1])
a = array.array(self.typecode, self.example)
a[-1] = a[0]
self.assertEntryEqual(a[0], a[-1])
a = array.array(self.typecode, self.example)
a[-1] = a[0]
self.assertEntryEqual(a[0], a[-1])
a = array.array(self.typecode, self.example)
a[len(self.example)-1] = a[0]
self.assertEntryEqual(a[0], a[-1])
a = array.array(self.typecode, self.example)
a[-len(self.example)] = a[-1]
self.assertEntryEqual(a[0], a[-1])
self.assertRaises(TypeError, a.__setitem__)
self.assertRaises(TypeError, a.__setitem__, None)
self.assertRaises(TypeError, a.__setitem__, 0, None)
self.assertRaises(
IndexError,
a.__setitem__,
len(self.example), self.example[0]
)
self.assertRaises(
IndexError,
a.__setitem__,
-len(self.example)-1, self.example[0]
)
def test_delitem(self):
a = array.array(self.typecode, self.example)
del a[0]
self.assertEqual(
a,
array.array(self.typecode, self.example[1:])
)
a = array.array(self.typecode, self.example)
del a[-1]
self.assertEqual(
a,
array.array(self.typecode, self.example[:-1])
)
a = array.array(self.typecode, self.example)
del a[len(self.example)-1]
self.assertEqual(
a,
array.array(self.typecode, self.example[:-1])
)
a = array.array(self.typecode, self.example)
del a[-len(self.example)]
self.assertEqual(
a,
array.array(self.typecode, self.example[1:])
)
self.assertRaises(TypeError, a.__delitem__)
self.assertRaises(TypeError, a.__delitem__, None)
self.assertRaises(IndexError, a.__delitem__, len(self.example))
self.assertRaises(IndexError, a.__delitem__, -len(self.example)-1)
def test_getslice(self):
a = array.array(self.typecode, self.example)
self.assertEqual(a[:], a)
self.assertEqual(
a[1:],
array.array(self.typecode, self.example[1:])
)
self.assertEqual(
a[:1],
array.array(self.typecode, self.example[:1])
)
self.assertEqual(
a[:-1],
array.array(self.typecode, self.example[:-1])
)
self.assertEqual(
a[-1:],
array.array(self.typecode, self.example[-1:])
)
self.assertEqual(
a[-1:-1],
array.array(self.typecode)
)
self.assertEqual(
a[2:1],
array.array(self.typecode)
)
self.assertEqual(
a[1000:],
array.array(self.typecode)
)
self.assertEqual(a[-1000:], a)
self.assertEqual(a[:1000], a)
self.assertEqual(
a[:-1000],
array.array(self.typecode)
)
self.assertEqual(a[-1000:1000], a)
self.assertEqual(
a[2000:1000],
array.array(self.typecode)
)
def test_extended_getslice(self):
# Test extended slicing by comparing with list slicing
# (Assumes list conversion works correctly, too)
a = array.array(self.typecode, self.example)
indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100)
for start in indices:
for stop in indices:
# Everything except the initial 0 (invalid step)
for step in indices[1:]:
self.assertEqual(list(a[start:stop:step]),
list(a)[start:stop:step])
def test_setslice(self):
a = array.array(self.typecode, self.example)
a[:1] = a
self.assertEqual(
a,
array.array(self.typecode, self.example + self.example[1:])
)
a = array.array(self.typecode, self.example)
a[:-1] = a
self.assertEqual(
a,
array.array(self.typecode, self.example + self.example[-1:])
)
a = array.array(self.typecode, self.example)
a[-1:] = a
self.assertEqual(
a,
array.array(self.typecode, self.example[:-1] + self.example)
)
a = array.array(self.typecode, self.example)
a[1:] = a
self.assertEqual(
a,
array.array(self.typecode, self.example[:1] + self.example)
)
a = array.array(self.typecode, self.example)
a[1:-1] = a
self.assertEqual(
a,
array.array(
self.typecode,
self.example[:1] + self.example + self.example[-1:]
)
)
a = array.array(self.typecode, self.example)
a[1000:] = a
self.assertEqual(
a,
array.array(self.typecode, 2*self.example)
)
a = array.array(self.typecode, self.example)
a[-1000:] = a
self.assertEqual(
a,
array.array(self.typecode, self.example)
)
a = array.array(self.typecode, self.example)
a[:1000] = a
self.assertEqual(
a,
array.array(self.typecode, self.example)
)
a = array.array(self.typecode, self.example)
a[:-1000] = a
self.assertEqual(
a,
array.array(self.typecode, 2*self.example)
)
a = array.array(self.typecode, self.example)
a[1:0] = a
self.assertEqual(
a,
array.array(self.typecode, self.example[:1] + self.example + self.example[1:])
)
a = array.array(self.typecode, self.example)
a[2000:1000] = a
self.assertEqual(
a,
array.array(self.typecode, 2*self.example)
)
a = array.array(self.typecode, self.example)
self.assertRaises(TypeError, a.__setitem__, slice(0, 0), None)
self.assertRaises(TypeError, a.__setitem__, slice(0, 1), None)
b = array.array(self.badtypecode())
self.assertRaises(TypeError, a.__setitem__, slice(0, 0), b)
self.assertRaises(TypeError, a.__setitem__, slice(0, 1), b)
def test_extended_set_del_slice(self):
indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100)
for start in indices:
for stop in indices:
# Everything except the initial 0 (invalid step)
for step in indices[1:]:
a = array.array(self.typecode, self.example)
L = list(a)
# Make sure we have a slice of exactly the right length,
# but with (hopefully) different data.
data = L[start:stop:step]
data.reverse()
L[start:stop:step] = data
a[start:stop:step] = array.array(self.typecode, data)
self.assertEqual(a, array.array(self.typecode, L))
del L[start:stop:step]
del a[start:stop:step]
self.assertEqual(a, array.array(self.typecode, L))
def test_index(self):
example = 2*self.example
a = array.array(self.typecode, example)
self.assertRaises(TypeError, a.index)
for x in example:
self.assertEqual(a.index(x), example.index(x))
self.assertRaises(ValueError, a.index, None)
self.assertRaises(ValueError, a.index, self.outside)
def test_count(self):
example = 2*self.example
a = array.array(self.typecode, example)
self.assertRaises(TypeError, a.count)
for x in example:
self.assertEqual(a.count(x), example.count(x))
self.assertEqual(a.count(self.outside), 0)
self.assertEqual(a.count(None), 0)
def test_remove(self):
for x in self.example:
example = 2*self.example
a = array.array(self.typecode, example)
pos = example.index(x)
example2 = example[:pos] + example[pos+1:]
a.remove(x)
self.assertEqual(a, array.array(self.typecode, example2))
a = array.array(self.typecode, self.example)
self.assertRaises(ValueError, a.remove, self.outside)
self.assertRaises(ValueError, a.remove, None)
def test_pop(self):
a = array.array(self.typecode)
self.assertRaises(IndexError, a.pop)
a = array.array(self.typecode, 2*self.example)
self.assertRaises(TypeError, a.pop, 42, 42)
self.assertRaises(TypeError, a.pop, None)
self.assertRaises(IndexError, a.pop, len(a))
self.assertRaises(IndexError, a.pop, -len(a)-1)
self.assertEntryEqual(a.pop(0), self.example[0])
self.assertEqual(
a,
array.array(self.typecode, self.example[1:]+self.example)
)
self.assertEntryEqual(a.pop(1), self.example[2])
self.assertEqual(
a,
array.array(self.typecode, self.example[1:2]+self.example[3:]+self.example)
)
self.assertEntryEqual(a.pop(0), self.example[1])
self.assertEntryEqual(a.pop(), self.example[-1])
self.assertEqual(
a,
array.array(self.typecode, self.example[3:]+self.example[:-1])
)
def test_reverse(self):
a = array.array(self.typecode, self.example)
self.assertRaises(TypeError, a.reverse, 42)
a.reverse()
self.assertEqual(
a,
array.array(self.typecode, self.example[::-1])
)
def test_extend(self):
a = array.array(self.typecode, self.example)
self.assertRaises(TypeError, a.extend)
a.extend(array.array(self.typecode, self.example[::-1]))
self.assertEqual(
a,
array.array(self.typecode, self.example+self.example[::-1])
)
a = array.array(self.typecode, self.example)
a.extend(a)
self.assertEqual(
a,
array.array(self.typecode, self.example+self.example)
)
b = array.array(self.badtypecode())
self.assertRaises(TypeError, a.extend, b)
a = array.array(self.typecode, self.example)
a.extend(self.example[::-1])
self.assertEqual(
a,
array.array(self.typecode, self.example+self.example[::-1])
)
def test_constructor_with_iterable_argument(self):
a = array.array(self.typecode, iter(self.example))
b = array.array(self.typecode, self.example)
self.assertEqual(a, b)
# non-iterable argument
self.assertRaises(TypeError, array.array, self.typecode, 10)
# pass through errors raised in __iter__
class A:
def __iter__(self):
raise UnicodeError
self.assertRaises(UnicodeError, array.array, self.typecode, A())
# pass through errors raised in next()
def B():
raise UnicodeError
yield None
self.assertRaises(UnicodeError, array.array, self.typecode, B())
def test_coveritertraverse(self):
try:
import gc
except ImportError:
self.skipTest('gc module not available')
a = array.array(self.typecode)
l = [iter(a)]
l.append(l)
gc.collect()
def test_buffer(self):
a = array.array(self.typecode, self.example)
m = memoryview(a)
expected = m.tobytes()
self.assertEqual(a.tobytes(), expected)
self.assertEqual(a.tobytes()[0], expected[0])
# Resizing is forbidden when there are buffer exports.
# For issue 4509, we also check after each error that
# the array was not modified.
self.assertRaises(BufferError, a.append, a[0])
self.assertEqual(m.tobytes(), expected)
self.assertRaises(BufferError, a.extend, a[0:1])
self.assertEqual(m.tobytes(), expected)
self.assertRaises(BufferError, a.remove, a[0])
self.assertEqual(m.tobytes(), expected)
self.assertRaises(BufferError, a.pop, 0)
self.assertEqual(m.tobytes(), expected)
self.assertRaises(BufferError, a.fromlist, a.tolist())
self.assertEqual(m.tobytes(), expected)
self.assertRaises(BufferError, a.frombytes, a.tobytes())
self.assertEqual(m.tobytes(), expected)
if self.typecode == 'u':
self.assertRaises(BufferError, a.fromunicode, a.tounicode())
self.assertEqual(m.tobytes(), expected)
self.assertRaises(BufferError, operator.imul, a, 2)
self.assertEqual(m.tobytes(), expected)
self.assertRaises(BufferError, operator.imul, a, 0)
self.assertEqual(m.tobytes(), expected)
self.assertRaises(BufferError, operator.setitem, a, slice(0, 0), a)
self.assertEqual(m.tobytes(), expected)
self.assertRaises(BufferError, operator.delitem, a, 0)
self.assertEqual(m.tobytes(), expected)
self.assertRaises(BufferError, operator.delitem, a, slice(0, 1))
self.assertEqual(m.tobytes(), expected)
def test_weakref(self):
s = array.array(self.typecode, self.example)
p = weakref.proxy(s)
self.assertEqual(p.tobytes(), s.tobytes())
s = None
self.assertRaises(ReferenceError, len, p)
@unittest.skipUnless(hasattr(sys, 'getrefcount'),
'test needs sys.getrefcount()')
def test_bug_782369(self):
for i in range(10):
b = array.array('B', range(64))
rc = sys.getrefcount(10)
for i in range(10):
b = array.array('B', range(64))
self.assertEqual(rc, sys.getrefcount(10))
def test_subclass_with_kwargs(self):
# SF bug #1486663 -- this used to erroneously raise a TypeError
ArraySubclassWithKwargs('b', newarg=1)
def test_create_from_bytes(self):
# XXX This test probably needs to be moved in a subclass or
# generalized to use self.typecode.
a = array.array('H', b"1234")
self.assertEqual(len(a) * a.itemsize, 4)
@support.cpython_only
def test_sizeof_with_buffer(self):
a = array.array(self.typecode, self.example)
basesize = support.calcvobjsize('Pn2Pi')
buffer_size = a.buffer_info()[1] * a.itemsize
support.check_sizeof(self, a, basesize + buffer_size)
@support.cpython_only
def test_sizeof_without_buffer(self):
a = array.array(self.typecode)
basesize = support.calcvobjsize('Pn2Pi')
support.check_sizeof(self, a, basesize)
def test_initialize_with_unicode(self):
if self.typecode != 'u':
with self.assertRaises(TypeError) as cm:
a = array.array(self.typecode, 'foo')
self.assertIn("cannot use a str", str(cm.exception))
with self.assertRaises(TypeError) as cm:
a = array.array(self.typecode, array.array('u', 'foo'))
self.assertIn("cannot use a unicode array", str(cm.exception))
else:
a = array.array(self.typecode, "foo")
a = array.array(self.typecode, array.array('u', 'foo'))
@support.cpython_only
def test_obsolete_write_lock(self):
from _testcapi import getbuffer_with_null_view
a = array.array('B', b"")
self.assertRaises(BufferError, getbuffer_with_null_view, a)
def test_free_after_iterating(self):
support.check_free_after_iterating(self, iter, array.array,
(self.typecode,))
support.check_free_after_iterating(self, reversed, array.array,
(self.typecode,))
class StringTest(BaseTest):
def test_setitem(self):
super().test_setitem()
a = array.array(self.typecode, self.example)
self.assertRaises(TypeError, a.__setitem__, 0, self.example[:2])
class UnicodeTest(StringTest, unittest.TestCase):
typecode = 'u'
example = '\x01\u263a\x00\ufeff'
smallerexample = '\x01\u263a\x00\ufefe'
biggerexample = '\x01\u263a\x01\ufeff'
outside = str('\x33')
minitemsize = 2
def test_unicode(self):
self.assertRaises(TypeError, array.array, 'b', 'foo')
a = array.array('u', '\xa0\xc2\u1234')
a.fromunicode(' ')
a.fromunicode('')
a.fromunicode('')
a.fromunicode('\x11abc\xff\u1234')
s = a.tounicode()
self.assertEqual(s, '\xa0\xc2\u1234 \x11abc\xff\u1234')
self.assertEqual(a.itemsize, sizeof_wchar)
s = '\x00="\'a\\b\x80\xff\u0000\u0001\u1234'
a = array.array('u', s)
self.assertEqual(
repr(a),
"array('u', '\\x00=\"\\'a\\\\b\\x80\xff\\x00\\x01\u1234')")
self.assertRaises(TypeError, a.fromunicode)
def test_issue17223(self):
# this used to crash
if sizeof_wchar == 4:
# U+FFFFFFFF is an invalid code point in Unicode 6.0
invalid_str = b'\xff\xff\xff\xff'
else:
# PyUnicode_FromUnicode() cannot fail with 16-bit wchar_t
self.skipTest("specific to 32-bit wchar_t")
a = array.array('u', invalid_str)
self.assertRaises(ValueError, a.tounicode)
self.assertRaises(ValueError, str, a)
class NumberTest(BaseTest):
def test_extslice(self):
a = array.array(self.typecode, range(5))
self.assertEqual(a[::], a)
self.assertEqual(a[::2], array.array(self.typecode, [0,2,4]))
self.assertEqual(a[1::2], array.array(self.typecode, [1,3]))
self.assertEqual(a[::-1], array.array(self.typecode, [4,3,2,1,0]))
self.assertEqual(a[::-2], array.array(self.typecode, [4,2,0]))
self.assertEqual(a[3::-2], array.array(self.typecode, [3,1]))
self.assertEqual(a[-100:100:], a)
self.assertEqual(a[100:-100:-1], a[::-1])
self.assertEqual(a[-100:100:2], array.array(self.typecode, [0,2,4]))
self.assertEqual(a[1000:2000:2], array.array(self.typecode, []))
self.assertEqual(a[-1000:-2000:-2], array.array(self.typecode, []))
def test_delslice(self):
a = array.array(self.typecode, range(5))
del a[::2]
self.assertEqual(a, array.array(self.typecode, [1,3]))
a = array.array(self.typecode, range(5))
del a[1::2]
self.assertEqual(a, array.array(self.typecode, [0,2,4]))
a = array.array(self.typecode, range(5))
del a[1::-2]
self.assertEqual(a, array.array(self.typecode, [0,2,3,4]))
a = array.array(self.typecode, range(10))
del a[::1000]
self.assertEqual(a, array.array(self.typecode, [1,2,3,4,5,6,7,8,9]))
# test issue7788
a = array.array(self.typecode, range(10))
del a[9::1<<333]
def test_assignment(self):
a = array.array(self.typecode, range(10))
a[::2] = array.array(self.typecode, [42]*5)
self.assertEqual(a, array.array(self.typecode, [42, 1, 42, 3, 42, 5, 42, 7, 42, 9]))
a = array.array(self.typecode, range(10))
a[::-4] = array.array(self.typecode, [10]*3)
self.assertEqual(a, array.array(self.typecode, [0, 10, 2, 3, 4, 10, 6, 7, 8 ,10]))
a = array.array(self.typecode, range(4))
a[::-1] = a
self.assertEqual(a, array.array(self.typecode, [3, 2, 1, 0]))
a = array.array(self.typecode, range(10))
b = a[:]
c = a[:]
ins = array.array(self.typecode, range(2))
a[2:3] = ins
b[slice(2,3)] = ins
c[2:3:] = ins
def test_iterationcontains(self):
a = array.array(self.typecode, range(10))
self.assertEqual(list(a), list(range(10)))
b = array.array(self.typecode, [20])
self.assertEqual(a[-1] in a, True)
self.assertEqual(b[0] not in a, True)
def check_overflow(self, lower, upper):
# method to be used by subclasses
# should not overflow assigning lower limit
a = array.array(self.typecode, [lower])
a[0] = lower
# should overflow assigning less than lower limit
self.assertRaises(OverflowError, array.array, self.typecode, [lower-1])
self.assertRaises(OverflowError, a.__setitem__, 0, lower-1)
# should not overflow assigning upper limit
a = array.array(self.typecode, [upper])
a[0] = upper
# should overflow assigning more than upper limit
self.assertRaises(OverflowError, array.array, self.typecode, [upper+1])
self.assertRaises(OverflowError, a.__setitem__, 0, upper+1)
def test_subclassing(self):
typecode = self.typecode
class ExaggeratingArray(array.array):
__slots__ = ['offset']
def __new__(cls, typecode, data, offset):
return array.array.__new__(cls, typecode, data)
def __init__(self, typecode, data, offset):
self.offset = offset
def __getitem__(self, i):
return array.array.__getitem__(self, i) + self.offset
a = ExaggeratingArray(self.typecode, [3, 6, 7, 11], 4)
self.assertEntryEqual(a[0], 7)
self.assertRaises(AttributeError, setattr, a, "color", "blue")
def test_frombytearray(self):
a = array.array('b', range(10))
b = array.array(self.typecode, a)
self.assertEqual(a, b)
class IntegerNumberTest(NumberTest):
def test_type_error(self):
a = array.array(self.typecode)
a.append(42)
with self.assertRaises(TypeError):
a.append(42.0)
with self.assertRaises(TypeError):
a[0] = 42.0
class Intable:
def __init__(self, num):
self._num = num
def __int__(self):
return self._num
def __sub__(self, other):
return Intable(int(self) - int(other))
def __add__(self, other):
return Intable(int(self) + int(other))
class SignedNumberTest(IntegerNumberTest):
example = [-1, 0, 1, 42, 0x7f]
smallerexample = [-1, 0, 1, 42, 0x7e]
biggerexample = [-1, 0, 1, 43, 0x7f]
outside = 23
def test_overflow(self):
a = array.array(self.typecode)
lower = -1 * int(pow(2, a.itemsize * 8 - 1))
upper = int(pow(2, a.itemsize * 8 - 1)) - 1
self.check_overflow(lower, upper)
self.check_overflow(Intable(lower), Intable(upper))
class UnsignedNumberTest(IntegerNumberTest):
example = [0, 1, 17, 23, 42, 0xff]
smallerexample = [0, 1, 17, 23, 42, 0xfe]
biggerexample = [0, 1, 17, 23, 43, 0xff]
outside = 0xaa
def test_overflow(self):
a = array.array(self.typecode)
lower = 0
upper = int(pow(2, a.itemsize * 8)) - 1
self.check_overflow(lower, upper)
self.check_overflow(Intable(lower), Intable(upper))
def test_bytes_extend(self):
s = bytes(self.example)
a = array.array(self.typecode, self.example)
a.extend(s)
self.assertEqual(
a,
array.array(self.typecode, self.example+self.example)
)
a = array.array(self.typecode, self.example)
a.extend(bytearray(reversed(s)))
self.assertEqual(
a,
array.array(self.typecode, self.example+self.example[::-1])
)
class ByteTest(SignedNumberTest, unittest.TestCase):
typecode = 'b'
minitemsize = 1
class UnsignedByteTest(UnsignedNumberTest, unittest.TestCase):
typecode = 'B'
minitemsize = 1
class ShortTest(SignedNumberTest, unittest.TestCase):
typecode = 'h'
minitemsize = 2
class UnsignedShortTest(UnsignedNumberTest, unittest.TestCase):
typecode = 'H'
minitemsize = 2
class IntTest(SignedNumberTest, unittest.TestCase):
typecode = 'i'
minitemsize = 2
class UnsignedIntTest(UnsignedNumberTest, unittest.TestCase):
typecode = 'I'
minitemsize = 2
class LongTest(SignedNumberTest, unittest.TestCase):
typecode = 'l'
minitemsize = 4
class UnsignedLongTest(UnsignedNumberTest, unittest.TestCase):
typecode = 'L'
minitemsize = 4
class LongLongTest(SignedNumberTest, unittest.TestCase):
typecode = 'q'
minitemsize = 8
class UnsignedLongLongTest(UnsignedNumberTest, unittest.TestCase):
typecode = 'Q'
minitemsize = 8
class FPTest(NumberTest):
example = [-42.0, 0, 42, 1e5, -1e10]
smallerexample = [-42.0, 0, 42, 1e5, -2e10]
biggerexample = [-42.0, 0, 42, 1e5, 1e10]
outside = 23
def assertEntryEqual(self, entry1, entry2):
self.assertAlmostEqual(entry1, entry2)
def test_byteswap(self):
a = array.array(self.typecode, self.example)
self.assertRaises(TypeError, a.byteswap, 42)
if a.itemsize in (1, 2, 4, 8):
b = array.array(self.typecode, self.example)
b.byteswap()
if a.itemsize==1:
self.assertEqual(a, b)
else:
# On alphas treating the byte swapped bit patters as
# floats/doubles results in floating point exceptions
# => compare the 8bit string values instead
self.assertNotEqual(a.tobytes(), b.tobytes())
b.byteswap()
self.assertEqual(a, b)
class FloatTest(FPTest, unittest.TestCase):
typecode = 'f'
minitemsize = 4
class DoubleTest(FPTest, unittest.TestCase):
typecode = 'd'
minitemsize = 8
def test_alloc_overflow(self):
from sys import maxsize
a = array.array('d', [-1]*65536)
try:
a *= maxsize//65536 + 1
except MemoryError:
pass
else:
self.fail("Array of size > maxsize created - MemoryError expected")
b = array.array('d', [ 2.71828183, 3.14159265, -1])
try:
b * (maxsize//3 + 1)
except MemoryError:
pass
else:
self.fail("Array of size > maxsize created - MemoryError expected")
if __name__ == "__main__":
unittest.main()
| 48,152 | 1,390 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_lzma.py | import _compression
from io import BytesIO, UnsupportedOperation, DEFAULT_BUFFER_SIZE
import os
import pathlib
import pickle
import random
import sys
from test import support
import unittest
from encodings import utf_16_le
from test.support import (
_4G, TESTFN, import_module, bigmemtest, run_unittest, unlink
)
lzma = import_module("lzma")
from lzma import LZMACompressor, LZMADecompressor, LZMAError, LZMAFile
class CompressorDecompressorTestCase(unittest.TestCase):
# Test error cases.
def test_simple_bad_args(self):
self.assertRaises(TypeError, LZMACompressor, [])
self.assertRaises(TypeError, LZMACompressor, format=3.45)
self.assertRaises(TypeError, LZMACompressor, check="")
self.assertRaises(TypeError, LZMACompressor, preset="asdf")
self.assertRaises(TypeError, LZMACompressor, filters=3)
# Can't specify FORMAT_AUTO when compressing.
self.assertRaises(ValueError, LZMACompressor, format=lzma.FORMAT_AUTO)
# Can't specify a preset and a custom filter chain at the same time.
with self.assertRaises(ValueError):
LZMACompressor(preset=7, filters=[{"id": lzma.FILTER_LZMA2}])
self.assertRaises(TypeError, LZMADecompressor, ())
self.assertRaises(TypeError, LZMADecompressor, memlimit=b"qw")
with self.assertRaises(TypeError):
LZMADecompressor(lzma.FORMAT_RAW, filters="zzz")
# Cannot specify a memory limit with FILTER_RAW.
with self.assertRaises(ValueError):
LZMADecompressor(lzma.FORMAT_RAW, memlimit=0x1000000)
# Can only specify a custom filter chain with FILTER_RAW.
self.assertRaises(ValueError, LZMADecompressor, filters=FILTERS_RAW_1)
with self.assertRaises(ValueError):
LZMADecompressor(format=lzma.FORMAT_XZ, filters=FILTERS_RAW_1)
with self.assertRaises(ValueError):
LZMADecompressor(format=lzma.FORMAT_ALONE, filters=FILTERS_RAW_1)
lzc = LZMACompressor()
self.assertRaises(TypeError, lzc.compress)
self.assertRaises(TypeError, lzc.compress, b"foo", b"bar")
self.assertRaises(TypeError, lzc.flush, b"blah")
empty = lzc.flush()
self.assertRaises(ValueError, lzc.compress, b"quux")
self.assertRaises(ValueError, lzc.flush)
lzd = LZMADecompressor()
self.assertRaises(TypeError, lzd.decompress)
self.assertRaises(TypeError, lzd.decompress, b"foo", b"bar")
lzd.decompress(empty)
self.assertRaises(EOFError, lzd.decompress, b"quux")
def test_bad_filter_spec(self):
self.assertRaises(TypeError, LZMACompressor, filters=[b"wobsite"])
self.assertRaises(ValueError, LZMACompressor, filters=[{"xyzzy": 3}])
self.assertRaises(ValueError, LZMACompressor, filters=[{"id": 98765}])
with self.assertRaises(ValueError):
LZMACompressor(filters=[{"id": lzma.FILTER_LZMA2, "foo": 0}])
with self.assertRaises(ValueError):
LZMACompressor(filters=[{"id": lzma.FILTER_DELTA, "foo": 0}])
with self.assertRaises(ValueError):
LZMACompressor(filters=[{"id": lzma.FILTER_X86, "foo": 0}])
def test_decompressor_after_eof(self):
lzd = LZMADecompressor()
lzd.decompress(COMPRESSED_XZ)
self.assertRaises(EOFError, lzd.decompress, b"nyan")
def test_decompressor_memlimit(self):
lzd = LZMADecompressor(memlimit=1024)
self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_XZ)
lzd = LZMADecompressor(lzma.FORMAT_XZ, memlimit=1024)
self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_XZ)
lzd = LZMADecompressor(lzma.FORMAT_ALONE, memlimit=1024)
self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_ALONE)
# Test LZMADecompressor on known-good input data.
def _test_decompressor(self, lzd, data, check, unused_data=b""):
self.assertFalse(lzd.eof)
out = lzd.decompress(data)
self.assertEqual(out, INPUT)
self.assertEqual(lzd.check, check)
self.assertTrue(lzd.eof)
self.assertEqual(lzd.unused_data, unused_data)
def test_decompressor_auto(self):
lzd = LZMADecompressor()
self._test_decompressor(lzd, COMPRESSED_XZ, lzma.CHECK_CRC64)
lzd = LZMADecompressor()
self._test_decompressor(lzd, COMPRESSED_ALONE, lzma.CHECK_NONE)
def test_decompressor_xz(self):
lzd = LZMADecompressor(lzma.FORMAT_XZ)
self._test_decompressor(lzd, COMPRESSED_XZ, lzma.CHECK_CRC64)
def test_decompressor_alone(self):
lzd = LZMADecompressor(lzma.FORMAT_ALONE)
self._test_decompressor(lzd, COMPRESSED_ALONE, lzma.CHECK_NONE)
def test_decompressor_raw_1(self):
lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_1)
self._test_decompressor(lzd, COMPRESSED_RAW_1, lzma.CHECK_NONE)
def test_decompressor_raw_2(self):
lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_2)
self._test_decompressor(lzd, COMPRESSED_RAW_2, lzma.CHECK_NONE)
def test_decompressor_raw_3(self):
lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_3)
self._test_decompressor(lzd, COMPRESSED_RAW_3, lzma.CHECK_NONE)
def test_decompressor_raw_4(self):
lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_4)
self._test_decompressor(lzd, COMPRESSED_RAW_4, lzma.CHECK_NONE)
def test_decompressor_chunks(self):
lzd = LZMADecompressor()
out = []
for i in range(0, len(COMPRESSED_XZ), 10):
self.assertFalse(lzd.eof)
out.append(lzd.decompress(COMPRESSED_XZ[i:i+10]))
out = b"".join(out)
self.assertEqual(out, INPUT)
self.assertEqual(lzd.check, lzma.CHECK_CRC64)
self.assertTrue(lzd.eof)
self.assertEqual(lzd.unused_data, b"")
def test_decompressor_chunks_empty(self):
lzd = LZMADecompressor()
out = []
for i in range(0, len(COMPRESSED_XZ), 10):
self.assertFalse(lzd.eof)
out.append(lzd.decompress(b''))
out.append(lzd.decompress(b''))
out.append(lzd.decompress(b''))
out.append(lzd.decompress(COMPRESSED_XZ[i:i+10]))
out = b"".join(out)
self.assertEqual(out, INPUT)
self.assertEqual(lzd.check, lzma.CHECK_CRC64)
self.assertTrue(lzd.eof)
self.assertEqual(lzd.unused_data, b"")
def test_decompressor_chunks_maxsize(self):
lzd = LZMADecompressor()
max_length = 100
out = []
# Feed first half the input
len_ = len(COMPRESSED_XZ) // 2
out.append(lzd.decompress(COMPRESSED_XZ[:len_],
max_length=max_length))
self.assertFalse(lzd.needs_input)
self.assertEqual(len(out[-1]), max_length)
# Retrieve more data without providing more input
out.append(lzd.decompress(b'', max_length=max_length))
self.assertFalse(lzd.needs_input)
self.assertEqual(len(out[-1]), max_length)
# Retrieve more data while providing more input
out.append(lzd.decompress(COMPRESSED_XZ[len_:],
max_length=max_length))
self.assertLessEqual(len(out[-1]), max_length)
# Retrieve remaining uncompressed data
while not lzd.eof:
out.append(lzd.decompress(b'', max_length=max_length))
self.assertLessEqual(len(out[-1]), max_length)
out = b"".join(out)
self.assertEqual(out, INPUT)
self.assertEqual(lzd.check, lzma.CHECK_CRC64)
self.assertEqual(lzd.unused_data, b"")
def test_decompressor_inputbuf_1(self):
# Test reusing input buffer after moving existing
# contents to beginning
lzd = LZMADecompressor()
out = []
# Create input buffer and fill it
self.assertEqual(lzd.decompress(COMPRESSED_XZ[:100],
max_length=0), b'')
# Retrieve some results, freeing capacity at beginning
# of input buffer
out.append(lzd.decompress(b'', 2))
# Add more data that fits into input buffer after
# moving existing data to beginning
out.append(lzd.decompress(COMPRESSED_XZ[100:105], 15))
# Decompress rest of data
out.append(lzd.decompress(COMPRESSED_XZ[105:]))
self.assertEqual(b''.join(out), INPUT)
def test_decompressor_inputbuf_2(self):
# Test reusing input buffer by appending data at the
# end right away
lzd = LZMADecompressor()
out = []
# Create input buffer and empty it
self.assertEqual(lzd.decompress(COMPRESSED_XZ[:200],
max_length=0), b'')
out.append(lzd.decompress(b''))
# Fill buffer with new data
out.append(lzd.decompress(COMPRESSED_XZ[200:280], 2))
# Append some more data, not enough to require resize
out.append(lzd.decompress(COMPRESSED_XZ[280:300], 2))
# Decompress rest of data
out.append(lzd.decompress(COMPRESSED_XZ[300:]))
self.assertEqual(b''.join(out), INPUT)
def test_decompressor_inputbuf_3(self):
# Test reusing input buffer after extending it
lzd = LZMADecompressor()
out = []
# Create almost full input buffer
out.append(lzd.decompress(COMPRESSED_XZ[:200], 5))
# Add even more data to it, requiring resize
out.append(lzd.decompress(COMPRESSED_XZ[200:300], 5))
# Decompress rest of data
out.append(lzd.decompress(COMPRESSED_XZ[300:]))
self.assertEqual(b''.join(out), INPUT)
def test_decompressor_unused_data(self):
lzd = LZMADecompressor()
extra = b"fooblibar"
self._test_decompressor(lzd, COMPRESSED_XZ + extra, lzma.CHECK_CRC64,
unused_data=extra)
def test_decompressor_bad_input(self):
lzd = LZMADecompressor()
self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_RAW_1)
lzd = LZMADecompressor(lzma.FORMAT_XZ)
self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_ALONE)
lzd = LZMADecompressor(lzma.FORMAT_ALONE)
self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_XZ)
lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_1)
self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_XZ)
def test_decompressor_bug_28275(self):
# Test coverage for Issue 28275
lzd = LZMADecompressor()
self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_RAW_1)
# Previously, a second call could crash due to internal inconsistency
self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_RAW_1)
# Test that LZMACompressor->LZMADecompressor preserves the input data.
def test_roundtrip_xz(self):
lzc = LZMACompressor()
cdata = lzc.compress(INPUT) + lzc.flush()
lzd = LZMADecompressor()
self._test_decompressor(lzd, cdata, lzma.CHECK_CRC64)
def test_roundtrip_alone(self):
lzc = LZMACompressor(lzma.FORMAT_ALONE)
cdata = lzc.compress(INPUT) + lzc.flush()
lzd = LZMADecompressor()
self._test_decompressor(lzd, cdata, lzma.CHECK_NONE)
def test_roundtrip_raw(self):
lzc = LZMACompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_4)
cdata = lzc.compress(INPUT) + lzc.flush()
lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_4)
self._test_decompressor(lzd, cdata, lzma.CHECK_NONE)
def test_roundtrip_raw_empty(self):
lzc = LZMACompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_4)
cdata = lzc.compress(INPUT)
cdata += lzc.compress(b'')
cdata += lzc.compress(b'')
cdata += lzc.compress(b'')
cdata += lzc.flush()
lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_4)
self._test_decompressor(lzd, cdata, lzma.CHECK_NONE)
def test_roundtrip_chunks(self):
lzc = LZMACompressor()
cdata = []
for i in range(0, len(INPUT), 10):
cdata.append(lzc.compress(INPUT[i:i+10]))
cdata.append(lzc.flush())
cdata = b"".join(cdata)
lzd = LZMADecompressor()
self._test_decompressor(lzd, cdata, lzma.CHECK_CRC64)
def test_roundtrip_empty_chunks(self):
lzc = LZMACompressor()
cdata = []
for i in range(0, len(INPUT), 10):
cdata.append(lzc.compress(INPUT[i:i+10]))
cdata.append(lzc.compress(b''))
cdata.append(lzc.compress(b''))
cdata.append(lzc.compress(b''))
cdata.append(lzc.flush())
cdata = b"".join(cdata)
lzd = LZMADecompressor()
self._test_decompressor(lzd, cdata, lzma.CHECK_CRC64)
# LZMADecompressor intentionally does not handle concatenated streams.
def test_decompressor_multistream(self):
lzd = LZMADecompressor()
self._test_decompressor(lzd, COMPRESSED_XZ + COMPRESSED_ALONE,
lzma.CHECK_CRC64, unused_data=COMPRESSED_ALONE)
# Test with inputs larger than 4GiB.
@bigmemtest(size=_4G + 100, memuse=2)
def test_compressor_bigmem(self, size):
lzc = LZMACompressor()
cdata = lzc.compress(b"x" * size) + lzc.flush()
ddata = lzma.decompress(cdata)
try:
self.assertEqual(len(ddata), size)
self.assertEqual(len(ddata.strip(b"x")), 0)
finally:
ddata = None
@bigmemtest(size=_4G + 100, memuse=3)
def test_decompressor_bigmem(self, size):
lzd = LZMADecompressor()
blocksize = 10 * 1024 * 1024
block = random.getrandbits(blocksize * 8).to_bytes(blocksize, "little")
try:
input = block * (size // blocksize + 1)
cdata = lzma.compress(input)
ddata = lzd.decompress(cdata)
self.assertEqual(ddata, input)
finally:
input = cdata = ddata = None
# Pickling raises an exception; there's no way to serialize an lzma_stream.
def test_pickle(self):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
with self.assertRaises(TypeError):
pickle.dumps(LZMACompressor(), proto)
with self.assertRaises(TypeError):
pickle.dumps(LZMADecompressor(), proto)
@support.refcount_test
def test_refleaks_in_decompressor___init__(self):
gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
lzd = LZMADecompressor()
refs_before = gettotalrefcount()
for i in range(100):
lzd.__init__()
self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
class CompressDecompressFunctionTestCase(unittest.TestCase):
# Test error cases:
def test_bad_args(self):
self.assertRaises(TypeError, lzma.compress)
self.assertRaises(TypeError, lzma.compress, [])
self.assertRaises(TypeError, lzma.compress, b"", format="xz")
self.assertRaises(TypeError, lzma.compress, b"", check="none")
self.assertRaises(TypeError, lzma.compress, b"", preset="blah")
self.assertRaises(TypeError, lzma.compress, b"", filters=1024)
# Can't specify a preset and a custom filter chain at the same time.
with self.assertRaises(ValueError):
lzma.compress(b"", preset=3, filters=[{"id": lzma.FILTER_LZMA2}])
self.assertRaises(TypeError, lzma.decompress)
self.assertRaises(TypeError, lzma.decompress, [])
self.assertRaises(TypeError, lzma.decompress, b"", format="lzma")
self.assertRaises(TypeError, lzma.decompress, b"", memlimit=7.3e9)
with self.assertRaises(TypeError):
lzma.decompress(b"", format=lzma.FORMAT_RAW, filters={})
# Cannot specify a memory limit with FILTER_RAW.
with self.assertRaises(ValueError):
lzma.decompress(b"", format=lzma.FORMAT_RAW, memlimit=0x1000000)
# Can only specify a custom filter chain with FILTER_RAW.
with self.assertRaises(ValueError):
lzma.decompress(b"", filters=FILTERS_RAW_1)
with self.assertRaises(ValueError):
lzma.decompress(b"", format=lzma.FORMAT_XZ, filters=FILTERS_RAW_1)
with self.assertRaises(ValueError):
lzma.decompress(
b"", format=lzma.FORMAT_ALONE, filters=FILTERS_RAW_1)
def test_decompress_memlimit(self):
with self.assertRaises(LZMAError):
lzma.decompress(COMPRESSED_XZ, memlimit=1024)
with self.assertRaises(LZMAError):
lzma.decompress(
COMPRESSED_XZ, format=lzma.FORMAT_XZ, memlimit=1024)
with self.assertRaises(LZMAError):
lzma.decompress(
COMPRESSED_ALONE, format=lzma.FORMAT_ALONE, memlimit=1024)
# Test LZMADecompressor on known-good input data.
def test_decompress_good_input(self):
ddata = lzma.decompress(COMPRESSED_XZ)
self.assertEqual(ddata, INPUT)
ddata = lzma.decompress(COMPRESSED_ALONE)
self.assertEqual(ddata, INPUT)
ddata = lzma.decompress(COMPRESSED_XZ, lzma.FORMAT_XZ)
self.assertEqual(ddata, INPUT)
ddata = lzma.decompress(COMPRESSED_ALONE, lzma.FORMAT_ALONE)
self.assertEqual(ddata, INPUT)
ddata = lzma.decompress(
COMPRESSED_RAW_1, lzma.FORMAT_RAW, filters=FILTERS_RAW_1)
self.assertEqual(ddata, INPUT)
ddata = lzma.decompress(
COMPRESSED_RAW_2, lzma.FORMAT_RAW, filters=FILTERS_RAW_2)
self.assertEqual(ddata, INPUT)
ddata = lzma.decompress(
COMPRESSED_RAW_3, lzma.FORMAT_RAW, filters=FILTERS_RAW_3)
self.assertEqual(ddata, INPUT)
ddata = lzma.decompress(
COMPRESSED_RAW_4, lzma.FORMAT_RAW, filters=FILTERS_RAW_4)
self.assertEqual(ddata, INPUT)
def test_decompress_incomplete_input(self):
self.assertRaises(LZMAError, lzma.decompress, COMPRESSED_XZ[:128])
self.assertRaises(LZMAError, lzma.decompress, COMPRESSED_ALONE[:128])
self.assertRaises(LZMAError, lzma.decompress, COMPRESSED_RAW_1[:128],
format=lzma.FORMAT_RAW, filters=FILTERS_RAW_1)
self.assertRaises(LZMAError, lzma.decompress, COMPRESSED_RAW_2[:128],
format=lzma.FORMAT_RAW, filters=FILTERS_RAW_2)
self.assertRaises(LZMAError, lzma.decompress, COMPRESSED_RAW_3[:128],
format=lzma.FORMAT_RAW, filters=FILTERS_RAW_3)
self.assertRaises(LZMAError, lzma.decompress, COMPRESSED_RAW_4[:128],
format=lzma.FORMAT_RAW, filters=FILTERS_RAW_4)
def test_decompress_bad_input(self):
with self.assertRaises(LZMAError):
lzma.decompress(COMPRESSED_BOGUS)
with self.assertRaises(LZMAError):
lzma.decompress(COMPRESSED_RAW_1)
with self.assertRaises(LZMAError):
lzma.decompress(COMPRESSED_ALONE, format=lzma.FORMAT_XZ)
with self.assertRaises(LZMAError):
lzma.decompress(COMPRESSED_XZ, format=lzma.FORMAT_ALONE)
with self.assertRaises(LZMAError):
lzma.decompress(COMPRESSED_XZ, format=lzma.FORMAT_RAW,
filters=FILTERS_RAW_1)
# Test that compress()->decompress() preserves the input data.
def test_roundtrip(self):
cdata = lzma.compress(INPUT)
ddata = lzma.decompress(cdata)
self.assertEqual(ddata, INPUT)
cdata = lzma.compress(INPUT, lzma.FORMAT_XZ)
ddata = lzma.decompress(cdata)
self.assertEqual(ddata, INPUT)
cdata = lzma.compress(INPUT, lzma.FORMAT_ALONE)
ddata = lzma.decompress(cdata)
self.assertEqual(ddata, INPUT)
cdata = lzma.compress(INPUT, lzma.FORMAT_RAW, filters=FILTERS_RAW_4)
ddata = lzma.decompress(cdata, lzma.FORMAT_RAW, filters=FILTERS_RAW_4)
self.assertEqual(ddata, INPUT)
# Unlike LZMADecompressor, decompress() *does* handle concatenated streams.
def test_decompress_multistream(self):
ddata = lzma.decompress(COMPRESSED_XZ + COMPRESSED_ALONE)
self.assertEqual(ddata, INPUT * 2)
# Test robust handling of non-LZMA data following the compressed stream(s).
def test_decompress_trailing_junk(self):
ddata = lzma.decompress(COMPRESSED_XZ + COMPRESSED_BOGUS)
self.assertEqual(ddata, INPUT)
def test_decompress_multistream_trailing_junk(self):
ddata = lzma.decompress(COMPRESSED_XZ * 3 + COMPRESSED_BOGUS)
self.assertEqual(ddata, INPUT * 3)
class TempFile:
"""Context manager - creates a file, and deletes it on __exit__."""
def __init__(self, filename, data=b""):
self.filename = filename
self.data = data
def __enter__(self):
with open(self.filename, "wb") as f:
f.write(self.data)
def __exit__(self, *args):
unlink(self.filename)
class FileTestCase(unittest.TestCase):
def test_init(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
pass
with LZMAFile(BytesIO(), "w") as f:
pass
with LZMAFile(BytesIO(), "x") as f:
pass
with LZMAFile(BytesIO(), "a") as f:
pass
def test_init_with_PathLike_filename(self):
filename = pathlib.Path(TESTFN)
with TempFile(filename, COMPRESSED_XZ):
with LZMAFile(filename) as f:
self.assertEqual(f.read(), INPUT)
with LZMAFile(filename, "a") as f:
f.write(INPUT)
with LZMAFile(filename) as f:
self.assertEqual(f.read(), INPUT * 2)
def test_init_with_filename(self):
with TempFile(TESTFN, COMPRESSED_XZ):
with LZMAFile(TESTFN) as f:
pass
with LZMAFile(TESTFN, "w") as f:
pass
with LZMAFile(TESTFN, "a") as f:
pass
def test_init_mode(self):
with TempFile(TESTFN):
with LZMAFile(TESTFN, "r"):
pass
with LZMAFile(TESTFN, "rb"):
pass
with LZMAFile(TESTFN, "w"):
pass
with LZMAFile(TESTFN, "wb"):
pass
with LZMAFile(TESTFN, "a"):
pass
with LZMAFile(TESTFN, "ab"):
pass
def test_init_with_x_mode(self):
self.addCleanup(unlink, TESTFN)
for mode in ("x", "xb"):
unlink(TESTFN)
with LZMAFile(TESTFN, mode):
pass
with self.assertRaises(FileExistsError):
with LZMAFile(TESTFN, mode):
pass
def test_init_bad_mode(self):
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), (3, "x"))
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), "")
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), "xt")
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), "x+")
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), "rx")
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), "wx")
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), "rt")
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), "r+")
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), "wt")
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), "w+")
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), "rw")
def test_init_bad_check(self):
with self.assertRaises(TypeError):
LZMAFile(BytesIO(), "w", check=b"asd")
# CHECK_UNKNOWN and anything above CHECK_ID_MAX should be invalid.
with self.assertRaises(LZMAError):
LZMAFile(BytesIO(), "w", check=lzma.CHECK_UNKNOWN)
with self.assertRaises(LZMAError):
LZMAFile(BytesIO(), "w", check=lzma.CHECK_ID_MAX + 3)
# Cannot specify a check with mode="r".
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), check=lzma.CHECK_NONE)
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), check=lzma.CHECK_CRC32)
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), check=lzma.CHECK_CRC64)
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), check=lzma.CHECK_SHA256)
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), check=lzma.CHECK_UNKNOWN)
def test_init_bad_preset(self):
with self.assertRaises(TypeError):
LZMAFile(BytesIO(), "w", preset=4.39)
with self.assertRaises(LZMAError):
LZMAFile(BytesIO(), "w", preset=10)
with self.assertRaises(LZMAError):
LZMAFile(BytesIO(), "w", preset=23)
with self.assertRaises(OverflowError):
LZMAFile(BytesIO(), "w", preset=-1)
with self.assertRaises(OverflowError):
LZMAFile(BytesIO(), "w", preset=-7)
with self.assertRaises(TypeError):
LZMAFile(BytesIO(), "w", preset="foo")
# Cannot specify a preset with mode="r".
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), preset=3)
def test_init_bad_filter_spec(self):
with self.assertRaises(TypeError):
LZMAFile(BytesIO(), "w", filters=[b"wobsite"])
with self.assertRaises(ValueError):
LZMAFile(BytesIO(), "w", filters=[{"xyzzy": 3}])
with self.assertRaises(ValueError):
LZMAFile(BytesIO(), "w", filters=[{"id": 98765}])
with self.assertRaises(ValueError):
LZMAFile(BytesIO(), "w",
filters=[{"id": lzma.FILTER_LZMA2, "foo": 0}])
with self.assertRaises(ValueError):
LZMAFile(BytesIO(), "w",
filters=[{"id": lzma.FILTER_DELTA, "foo": 0}])
with self.assertRaises(ValueError):
LZMAFile(BytesIO(), "w",
filters=[{"id": lzma.FILTER_X86, "foo": 0}])
def test_init_with_preset_and_filters(self):
with self.assertRaises(ValueError):
LZMAFile(BytesIO(), "w", format=lzma.FORMAT_RAW,
preset=6, filters=FILTERS_RAW_1)
def test_close(self):
with BytesIO(COMPRESSED_XZ) as src:
f = LZMAFile(src)
f.close()
# LZMAFile.close() should not close the underlying file object.
self.assertFalse(src.closed)
# Try closing an already-closed LZMAFile.
f.close()
self.assertFalse(src.closed)
# Test with a real file on disk, opened directly by LZMAFile.
with TempFile(TESTFN, COMPRESSED_XZ):
f = LZMAFile(TESTFN)
fp = f._fp
f.close()
# Here, LZMAFile.close() *should* close the underlying file object.
self.assertTrue(fp.closed)
# Try closing an already-closed LZMAFile.
f.close()
def test_closed(self):
f = LZMAFile(BytesIO(COMPRESSED_XZ))
try:
self.assertFalse(f.closed)
f.read()
self.assertFalse(f.closed)
finally:
f.close()
self.assertTrue(f.closed)
f = LZMAFile(BytesIO(), "w")
try:
self.assertFalse(f.closed)
finally:
f.close()
self.assertTrue(f.closed)
def test_fileno(self):
f = LZMAFile(BytesIO(COMPRESSED_XZ))
try:
self.assertRaises(UnsupportedOperation, f.fileno)
finally:
f.close()
self.assertRaises(ValueError, f.fileno)
with TempFile(TESTFN, COMPRESSED_XZ):
f = LZMAFile(TESTFN)
try:
self.assertEqual(f.fileno(), f._fp.fileno())
self.assertIsInstance(f.fileno(), int)
finally:
f.close()
self.assertRaises(ValueError, f.fileno)
def test_seekable(self):
f = LZMAFile(BytesIO(COMPRESSED_XZ))
try:
self.assertTrue(f.seekable())
f.read()
self.assertTrue(f.seekable())
finally:
f.close()
self.assertRaises(ValueError, f.seekable)
f = LZMAFile(BytesIO(), "w")
try:
self.assertFalse(f.seekable())
finally:
f.close()
self.assertRaises(ValueError, f.seekable)
src = BytesIO(COMPRESSED_XZ)
src.seekable = lambda: False
f = LZMAFile(src)
try:
self.assertFalse(f.seekable())
finally:
f.close()
self.assertRaises(ValueError, f.seekable)
def test_readable(self):
f = LZMAFile(BytesIO(COMPRESSED_XZ))
try:
self.assertTrue(f.readable())
f.read()
self.assertTrue(f.readable())
finally:
f.close()
self.assertRaises(ValueError, f.readable)
f = LZMAFile(BytesIO(), "w")
try:
self.assertFalse(f.readable())
finally:
f.close()
self.assertRaises(ValueError, f.readable)
def test_writable(self):
f = LZMAFile(BytesIO(COMPRESSED_XZ))
try:
self.assertFalse(f.writable())
f.read()
self.assertFalse(f.writable())
finally:
f.close()
self.assertRaises(ValueError, f.writable)
f = LZMAFile(BytesIO(), "w")
try:
self.assertTrue(f.writable())
finally:
f.close()
self.assertRaises(ValueError, f.writable)
def test_read(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
self.assertEqual(f.read(), INPUT)
self.assertEqual(f.read(), b"")
with LZMAFile(BytesIO(COMPRESSED_ALONE)) as f:
self.assertEqual(f.read(), INPUT)
with LZMAFile(BytesIO(COMPRESSED_XZ), format=lzma.FORMAT_XZ) as f:
self.assertEqual(f.read(), INPUT)
self.assertEqual(f.read(), b"")
with LZMAFile(BytesIO(COMPRESSED_ALONE), format=lzma.FORMAT_ALONE) as f:
self.assertEqual(f.read(), INPUT)
self.assertEqual(f.read(), b"")
with LZMAFile(BytesIO(COMPRESSED_RAW_1),
format=lzma.FORMAT_RAW, filters=FILTERS_RAW_1) as f:
self.assertEqual(f.read(), INPUT)
self.assertEqual(f.read(), b"")
with LZMAFile(BytesIO(COMPRESSED_RAW_2),
format=lzma.FORMAT_RAW, filters=FILTERS_RAW_2) as f:
self.assertEqual(f.read(), INPUT)
self.assertEqual(f.read(), b"")
with LZMAFile(BytesIO(COMPRESSED_RAW_3),
format=lzma.FORMAT_RAW, filters=FILTERS_RAW_3) as f:
self.assertEqual(f.read(), INPUT)
self.assertEqual(f.read(), b"")
with LZMAFile(BytesIO(COMPRESSED_RAW_4),
format=lzma.FORMAT_RAW, filters=FILTERS_RAW_4) as f:
self.assertEqual(f.read(), INPUT)
self.assertEqual(f.read(), b"")
def test_read_0(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
self.assertEqual(f.read(0), b"")
with LZMAFile(BytesIO(COMPRESSED_ALONE)) as f:
self.assertEqual(f.read(0), b"")
with LZMAFile(BytesIO(COMPRESSED_XZ), format=lzma.FORMAT_XZ) as f:
self.assertEqual(f.read(0), b"")
with LZMAFile(BytesIO(COMPRESSED_ALONE), format=lzma.FORMAT_ALONE) as f:
self.assertEqual(f.read(0), b"")
def test_read_10(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
chunks = []
while True:
result = f.read(10)
if not result:
break
self.assertLessEqual(len(result), 10)
chunks.append(result)
self.assertEqual(b"".join(chunks), INPUT)
def test_read_multistream(self):
with LZMAFile(BytesIO(COMPRESSED_XZ * 5)) as f:
self.assertEqual(f.read(), INPUT * 5)
with LZMAFile(BytesIO(COMPRESSED_XZ + COMPRESSED_ALONE)) as f:
self.assertEqual(f.read(), INPUT * 2)
with LZMAFile(BytesIO(COMPRESSED_RAW_3 * 4),
format=lzma.FORMAT_RAW, filters=FILTERS_RAW_3) as f:
self.assertEqual(f.read(), INPUT * 4)
def test_read_multistream_buffer_size_aligned(self):
# Test the case where a stream boundary coincides with the end
# of the raw read buffer.
saved_buffer_size = _compression.BUFFER_SIZE
_compression.BUFFER_SIZE = len(COMPRESSED_XZ)
try:
with LZMAFile(BytesIO(COMPRESSED_XZ * 5)) as f:
self.assertEqual(f.read(), INPUT * 5)
finally:
_compression.BUFFER_SIZE = saved_buffer_size
def test_read_trailing_junk(self):
with LZMAFile(BytesIO(COMPRESSED_XZ + COMPRESSED_BOGUS)) as f:
self.assertEqual(f.read(), INPUT)
def test_read_multistream_trailing_junk(self):
with LZMAFile(BytesIO(COMPRESSED_XZ * 5 + COMPRESSED_BOGUS)) as f:
self.assertEqual(f.read(), INPUT * 5)
def test_read_from_file(self):
with TempFile(TESTFN, COMPRESSED_XZ):
with LZMAFile(TESTFN) as f:
self.assertEqual(f.read(), INPUT)
self.assertEqual(f.read(), b"")
def test_read_from_file_with_bytes_filename(self):
try:
bytes_filename = TESTFN.encode("ascii")
except UnicodeEncodeError:
self.skipTest("Temporary file name needs to be ASCII")
with TempFile(TESTFN, COMPRESSED_XZ):
with LZMAFile(bytes_filename) as f:
self.assertEqual(f.read(), INPUT)
self.assertEqual(f.read(), b"")
def test_read_incomplete(self):
with LZMAFile(BytesIO(COMPRESSED_XZ[:128])) as f:
self.assertRaises(EOFError, f.read)
def test_read_truncated(self):
# Drop stream footer: CRC (4 bytes), index size (4 bytes),
# flags (2 bytes) and magic number (2 bytes).
truncated = COMPRESSED_XZ[:-12]
with LZMAFile(BytesIO(truncated)) as f:
self.assertRaises(EOFError, f.read)
with LZMAFile(BytesIO(truncated)) as f:
self.assertEqual(f.read(len(INPUT)), INPUT)
self.assertRaises(EOFError, f.read, 1)
# Incomplete 12-byte header.
for i in range(12):
with LZMAFile(BytesIO(truncated[:i])) as f:
self.assertRaises(EOFError, f.read, 1)
def test_read_bad_args(self):
f = LZMAFile(BytesIO(COMPRESSED_XZ))
f.close()
self.assertRaises(ValueError, f.read)
with LZMAFile(BytesIO(), "w") as f:
self.assertRaises(ValueError, f.read)
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
self.assertRaises(TypeError, f.read, float())
def test_read_bad_data(self):
with LZMAFile(BytesIO(COMPRESSED_BOGUS)) as f:
self.assertRaises(LZMAError, f.read)
def test_read1(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
blocks = []
while True:
result = f.read1()
if not result:
break
blocks.append(result)
self.assertEqual(b"".join(blocks), INPUT)
self.assertEqual(f.read1(), b"")
def test_read1_0(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
self.assertEqual(f.read1(0), b"")
def test_read1_10(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
blocks = []
while True:
result = f.read1(10)
if not result:
break
blocks.append(result)
self.assertEqual(b"".join(blocks), INPUT)
self.assertEqual(f.read1(), b"")
def test_read1_multistream(self):
with LZMAFile(BytesIO(COMPRESSED_XZ * 5)) as f:
blocks = []
while True:
result = f.read1()
if not result:
break
blocks.append(result)
self.assertEqual(b"".join(blocks), INPUT * 5)
self.assertEqual(f.read1(), b"")
def test_read1_bad_args(self):
f = LZMAFile(BytesIO(COMPRESSED_XZ))
f.close()
self.assertRaises(ValueError, f.read1)
with LZMAFile(BytesIO(), "w") as f:
self.assertRaises(ValueError, f.read1)
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
self.assertRaises(TypeError, f.read1, None)
def test_peek(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
result = f.peek()
self.assertGreater(len(result), 0)
self.assertTrue(INPUT.startswith(result))
self.assertEqual(f.read(), INPUT)
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
result = f.peek(10)
self.assertGreater(len(result), 0)
self.assertTrue(INPUT.startswith(result))
self.assertEqual(f.read(), INPUT)
def test_peek_bad_args(self):
with LZMAFile(BytesIO(), "w") as f:
self.assertRaises(ValueError, f.peek)
def test_iterator(self):
with BytesIO(INPUT) as f:
lines = f.readlines()
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
self.assertListEqual(list(iter(f)), lines)
with LZMAFile(BytesIO(COMPRESSED_ALONE)) as f:
self.assertListEqual(list(iter(f)), lines)
with LZMAFile(BytesIO(COMPRESSED_XZ), format=lzma.FORMAT_XZ) as f:
self.assertListEqual(list(iter(f)), lines)
with LZMAFile(BytesIO(COMPRESSED_ALONE), format=lzma.FORMAT_ALONE) as f:
self.assertListEqual(list(iter(f)), lines)
with LZMAFile(BytesIO(COMPRESSED_RAW_2),
format=lzma.FORMAT_RAW, filters=FILTERS_RAW_2) as f:
self.assertListEqual(list(iter(f)), lines)
def test_readline(self):
with BytesIO(INPUT) as f:
lines = f.readlines()
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
for line in lines:
self.assertEqual(f.readline(), line)
def test_readlines(self):
with BytesIO(INPUT) as f:
lines = f.readlines()
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
self.assertListEqual(f.readlines(), lines)
def test_decompress_limited(self):
"""Decompressed data buffering should be limited"""
bomb = lzma.compress(b'\0' * int(2e6), preset=6)
self.assertLess(len(bomb), _compression.BUFFER_SIZE)
decomp = LZMAFile(BytesIO(bomb))
self.assertEqual(decomp.read(1), b'\0')
max_decomp = 1 + DEFAULT_BUFFER_SIZE
self.assertLessEqual(decomp._buffer.raw.tell(), max_decomp,
"Excessive amount of data was decompressed")
def test_write(self):
with BytesIO() as dst:
with LZMAFile(dst, "w") as f:
f.write(INPUT)
expected = lzma.compress(INPUT)
self.assertEqual(dst.getvalue(), expected)
with BytesIO() as dst:
with LZMAFile(dst, "w", format=lzma.FORMAT_XZ) as f:
f.write(INPUT)
expected = lzma.compress(INPUT, format=lzma.FORMAT_XZ)
self.assertEqual(dst.getvalue(), expected)
with BytesIO() as dst:
with LZMAFile(dst, "w", format=lzma.FORMAT_ALONE) as f:
f.write(INPUT)
expected = lzma.compress(INPUT, format=lzma.FORMAT_ALONE)
self.assertEqual(dst.getvalue(), expected)
with BytesIO() as dst:
with LZMAFile(dst, "w", format=lzma.FORMAT_RAW,
filters=FILTERS_RAW_2) as f:
f.write(INPUT)
expected = lzma.compress(INPUT, format=lzma.FORMAT_RAW,
filters=FILTERS_RAW_2)
self.assertEqual(dst.getvalue(), expected)
def test_write_10(self):
with BytesIO() as dst:
with LZMAFile(dst, "w") as f:
for start in range(0, len(INPUT), 10):
f.write(INPUT[start:start+10])
expected = lzma.compress(INPUT)
self.assertEqual(dst.getvalue(), expected)
def test_write_append(self):
part1 = INPUT[:1024]
part2 = INPUT[1024:1536]
part3 = INPUT[1536:]
expected = b"".join(lzma.compress(x) for x in (part1, part2, part3))
with BytesIO() as dst:
with LZMAFile(dst, "w") as f:
f.write(part1)
with LZMAFile(dst, "a") as f:
f.write(part2)
with LZMAFile(dst, "a") as f:
f.write(part3)
self.assertEqual(dst.getvalue(), expected)
def test_write_to_file(self):
try:
with LZMAFile(TESTFN, "w") as f:
f.write(INPUT)
expected = lzma.compress(INPUT)
with open(TESTFN, "rb") as f:
self.assertEqual(f.read(), expected)
finally:
unlink(TESTFN)
def test_write_to_file_with_bytes_filename(self):
try:
bytes_filename = TESTFN.encode("ascii")
except UnicodeEncodeError:
self.skipTest("Temporary file name needs to be ASCII")
try:
with LZMAFile(bytes_filename, "w") as f:
f.write(INPUT)
expected = lzma.compress(INPUT)
with open(TESTFN, "rb") as f:
self.assertEqual(f.read(), expected)
finally:
unlink(TESTFN)
def test_write_append_to_file(self):
part1 = INPUT[:1024]
part2 = INPUT[1024:1536]
part3 = INPUT[1536:]
expected = b"".join(lzma.compress(x) for x in (part1, part2, part3))
try:
with LZMAFile(TESTFN, "w") as f:
f.write(part1)
with LZMAFile(TESTFN, "a") as f:
f.write(part2)
with LZMAFile(TESTFN, "a") as f:
f.write(part3)
with open(TESTFN, "rb") as f:
self.assertEqual(f.read(), expected)
finally:
unlink(TESTFN)
def test_write_bad_args(self):
f = LZMAFile(BytesIO(), "w")
f.close()
self.assertRaises(ValueError, f.write, b"foo")
with LZMAFile(BytesIO(COMPRESSED_XZ), "r") as f:
self.assertRaises(ValueError, f.write, b"bar")
with LZMAFile(BytesIO(), "w") as f:
self.assertRaises(TypeError, f.write, None)
self.assertRaises(TypeError, f.write, "text")
self.assertRaises(TypeError, f.write, 789)
def test_writelines(self):
with BytesIO(INPUT) as f:
lines = f.readlines()
with BytesIO() as dst:
with LZMAFile(dst, "w") as f:
f.writelines(lines)
expected = lzma.compress(INPUT)
self.assertEqual(dst.getvalue(), expected)
def test_seek_forward(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
f.seek(555)
self.assertEqual(f.read(), INPUT[555:])
def test_seek_forward_across_streams(self):
with LZMAFile(BytesIO(COMPRESSED_XZ * 2)) as f:
f.seek(len(INPUT) + 123)
self.assertEqual(f.read(), INPUT[123:])
def test_seek_forward_relative_to_current(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
f.read(100)
f.seek(1236, 1)
self.assertEqual(f.read(), INPUT[1336:])
def test_seek_forward_relative_to_end(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
f.seek(-555, 2)
self.assertEqual(f.read(), INPUT[-555:])
def test_seek_backward(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
f.read(1001)
f.seek(211)
self.assertEqual(f.read(), INPUT[211:])
def test_seek_backward_across_streams(self):
with LZMAFile(BytesIO(COMPRESSED_XZ * 2)) as f:
f.read(len(INPUT) + 333)
f.seek(737)
self.assertEqual(f.read(), INPUT[737:] + INPUT)
def test_seek_backward_relative_to_end(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
f.seek(-150, 2)
self.assertEqual(f.read(), INPUT[-150:])
def test_seek_past_end(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
f.seek(len(INPUT) + 9001)
self.assertEqual(f.tell(), len(INPUT))
self.assertEqual(f.read(), b"")
def test_seek_past_start(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
f.seek(-88)
self.assertEqual(f.tell(), 0)
self.assertEqual(f.read(), INPUT)
def test_seek_bad_args(self):
f = LZMAFile(BytesIO(COMPRESSED_XZ))
f.close()
self.assertRaises(ValueError, f.seek, 0)
with LZMAFile(BytesIO(), "w") as f:
self.assertRaises(ValueError, f.seek, 0)
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
self.assertRaises(ValueError, f.seek, 0, 3)
# io.BufferedReader raises TypeError instead of ValueError
self.assertRaises((TypeError, ValueError), f.seek, 9, ())
self.assertRaises(TypeError, f.seek, None)
self.assertRaises(TypeError, f.seek, b"derp")
def test_tell(self):
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
pos = 0
while True:
self.assertEqual(f.tell(), pos)
result = f.read(183)
if not result:
break
pos += len(result)
self.assertEqual(f.tell(), len(INPUT))
with LZMAFile(BytesIO(), "w") as f:
for pos in range(0, len(INPUT), 144):
self.assertEqual(f.tell(), pos)
f.write(INPUT[pos:pos+144])
self.assertEqual(f.tell(), len(INPUT))
def test_tell_bad_args(self):
f = LZMAFile(BytesIO(COMPRESSED_XZ))
f.close()
self.assertRaises(ValueError, f.tell)
class OpenTestCase(unittest.TestCase):
def test_binary_modes(self):
with lzma.open(BytesIO(COMPRESSED_XZ), "rb") as f:
self.assertEqual(f.read(), INPUT)
with BytesIO() as bio:
with lzma.open(bio, "wb") as f:
f.write(INPUT)
file_data = lzma.decompress(bio.getvalue())
self.assertEqual(file_data, INPUT)
with lzma.open(bio, "ab") as f:
f.write(INPUT)
file_data = lzma.decompress(bio.getvalue())
self.assertEqual(file_data, INPUT * 2)
def test_text_modes(self):
uncompressed = INPUT.decode("ascii")
uncompressed_raw = uncompressed.replace("\n", os.linesep)
with lzma.open(BytesIO(COMPRESSED_XZ), "rt") as f:
self.assertEqual(f.read(), uncompressed)
with BytesIO() as bio:
with lzma.open(bio, "wt") as f:
f.write(uncompressed)
file_data = lzma.decompress(bio.getvalue()).decode("ascii")
self.assertEqual(file_data, uncompressed_raw)
with lzma.open(bio, "at") as f:
f.write(uncompressed)
file_data = lzma.decompress(bio.getvalue()).decode("ascii")
self.assertEqual(file_data, uncompressed_raw * 2)
def test_filename(self):
with TempFile(TESTFN):
with lzma.open(TESTFN, "wb") as f:
f.write(INPUT)
with open(TESTFN, "rb") as f:
file_data = lzma.decompress(f.read())
self.assertEqual(file_data, INPUT)
with lzma.open(TESTFN, "rb") as f:
self.assertEqual(f.read(), INPUT)
with lzma.open(TESTFN, "ab") as f:
f.write(INPUT)
with lzma.open(TESTFN, "rb") as f:
self.assertEqual(f.read(), INPUT * 2)
def test_with_pathlike_filename(self):
filename = pathlib.Path(TESTFN)
with TempFile(filename):
with lzma.open(filename, "wb") as f:
f.write(INPUT)
with open(filename, "rb") as f:
file_data = lzma.decompress(f.read())
self.assertEqual(file_data, INPUT)
with lzma.open(filename, "rb") as f:
self.assertEqual(f.read(), INPUT)
def test_bad_params(self):
# Test invalid parameter combinations.
with self.assertRaises(ValueError):
lzma.open(TESTFN, "")
with self.assertRaises(ValueError):
lzma.open(TESTFN, "rbt")
with self.assertRaises(ValueError):
lzma.open(TESTFN, "rb", encoding="utf-8")
with self.assertRaises(ValueError):
lzma.open(TESTFN, "rb", errors="ignore")
with self.assertRaises(ValueError):
lzma.open(TESTFN, "rb", newline="\n")
def test_format_and_filters(self):
# Test non-default format and filter chain.
options = {"format": lzma.FORMAT_RAW, "filters": FILTERS_RAW_1}
with lzma.open(BytesIO(COMPRESSED_RAW_1), "rb", **options) as f:
self.assertEqual(f.read(), INPUT)
with BytesIO() as bio:
with lzma.open(bio, "wb", **options) as f:
f.write(INPUT)
file_data = lzma.decompress(bio.getvalue(), **options)
self.assertEqual(file_data, INPUT)
def test_encoding(self):
# Test non-default encoding.
uncompressed = INPUT.decode("ascii")
uncompressed_raw = uncompressed.replace("\n", os.linesep)
with BytesIO() as bio:
with lzma.open(bio, "wt", encoding="utf-16-le") as f:
f.write(uncompressed)
file_data = lzma.decompress(bio.getvalue()).decode("utf-16-le")
self.assertEqual(file_data, uncompressed_raw)
bio.seek(0)
with lzma.open(bio, "rt", encoding="utf-16-le") as f:
self.assertEqual(f.read(), uncompressed)
def test_encoding_error_handler(self):
# Test with non-default encoding error handler.
with BytesIO(lzma.compress(b"foo\xffbar")) as bio:
with lzma.open(bio, "rt", encoding="ascii", errors="ignore") as f:
self.assertEqual(f.read(), "foobar")
def test_newline(self):
# Test with explicit newline (universal newline mode disabled).
text = INPUT.decode("ascii")
with BytesIO() as bio:
with lzma.open(bio, "wt", newline="\n") as f:
f.write(text)
bio.seek(0)
with lzma.open(bio, "rt", newline="\r") as f:
self.assertEqual(f.readlines(), [text])
def test_x_mode(self):
self.addCleanup(unlink, TESTFN)
for mode in ("x", "xb", "xt"):
unlink(TESTFN)
with lzma.open(TESTFN, mode):
pass
with self.assertRaises(FileExistsError):
with lzma.open(TESTFN, mode):
pass
class MiscellaneousTestCase(unittest.TestCase):
def test_is_check_supported(self):
# CHECK_NONE and CHECK_CRC32 should always be supported,
# regardless of the options liblzma was compiled with.
self.assertTrue(lzma.is_check_supported(lzma.CHECK_NONE))
self.assertTrue(lzma.is_check_supported(lzma.CHECK_CRC32))
# The .xz format spec cannot store check IDs above this value.
self.assertFalse(lzma.is_check_supported(lzma.CHECK_ID_MAX + 1))
# This value should not be a valid check ID.
self.assertFalse(lzma.is_check_supported(lzma.CHECK_UNKNOWN))
def test__encode_filter_properties(self):
with self.assertRaises(TypeError):
lzma._encode_filter_properties(b"not a dict")
with self.assertRaises(ValueError):
lzma._encode_filter_properties({"id": 0x100})
with self.assertRaises(ValueError):
lzma._encode_filter_properties({"id": lzma.FILTER_LZMA2, "junk": 12})
with self.assertRaises(lzma.LZMAError):
lzma._encode_filter_properties({"id": lzma.FILTER_DELTA,
"dist": 9001})
# Test with parameters used by zipfile module.
props = lzma._encode_filter_properties({
"id": lzma.FILTER_LZMA1,
"pb": 2,
"lp": 0,
"lc": 3,
"dict_size": 8 << 20,
})
self.assertEqual(props, b"]\x00\x00\x80\x00")
def test__decode_filter_properties(self):
with self.assertRaises(TypeError):
lzma._decode_filter_properties(lzma.FILTER_X86, {"should be": bytes})
with self.assertRaises(lzma.LZMAError):
lzma._decode_filter_properties(lzma.FILTER_DELTA, b"too long")
# Test with parameters used by zipfile module.
filterspec = lzma._decode_filter_properties(
lzma.FILTER_LZMA1, b"]\x00\x00\x80\x00")
self.assertEqual(filterspec["id"], lzma.FILTER_LZMA1)
self.assertEqual(filterspec["pb"], 2)
self.assertEqual(filterspec["lp"], 0)
self.assertEqual(filterspec["lc"], 3)
self.assertEqual(filterspec["dict_size"], 8 << 20)
def test_filter_properties_roundtrip(self):
spec1 = lzma._decode_filter_properties(
lzma.FILTER_LZMA1, b"]\x00\x00\x80\x00")
reencoded = lzma._encode_filter_properties(spec1)
spec2 = lzma._decode_filter_properties(lzma.FILTER_LZMA1, reencoded)
self.assertEqual(spec1, spec2)
# Test data:
INPUT = b"""
LAERTES
O, fear me not.
I stay too long: but here my father comes.
Enter POLONIUS
A double blessing is a double grace,
Occasion smiles upon a second leave.
LORD POLONIUS
Yet here, Laertes! aboard, aboard, for shame!
The wind sits in the shoulder of your sail,
And you are stay'd for. There; my blessing with thee!
And these few precepts in thy memory
See thou character. Give thy thoughts no tongue,
Nor any unproportioned thought his act.
Be thou familiar, but by no means vulgar.
Those friends thou hast, and their adoption tried,
Grapple them to thy soul with hoops of steel;
But do not dull thy palm with entertainment
Of each new-hatch'd, unfledged comrade. Beware
Of entrance to a quarrel, but being in,
Bear't that the opposed may beware of thee.
Give every man thy ear, but few thy voice;
Take each man's censure, but reserve thy judgment.
Costly thy habit as thy purse can buy,
But not express'd in fancy; rich, not gaudy;
For the apparel oft proclaims the man,
And they in France of the best rank and station
Are of a most select and generous chief in that.
Neither a borrower nor a lender be;
For loan oft loses both itself and friend,
And borrowing dulls the edge of husbandry.
This above all: to thine ownself be true,
And it must follow, as the night the day,
Thou canst not then be false to any man.
Farewell: my blessing season this in thee!
LAERTES
Most humbly do I take my leave, my lord.
LORD POLONIUS
The time invites you; go; your servants tend.
LAERTES
Farewell, Ophelia; and remember well
What I have said to you.
OPHELIA
'Tis in my memory lock'd,
And you yourself shall keep the key of it.
LAERTES
Farewell.
"""
COMPRESSED_BOGUS = b"this is not a valid lzma stream"
COMPRESSED_XZ = (
b"\xfd7zXZ\x00\x00\x04\xe6\xd6\xb4F\x02\x00!\x01\x16\x00\x00\x00t/\xe5\xa3"
b"\xe0\x07\x80\x03\xdf]\x00\x05\x14\x07bX\x19\xcd\xddn\x98\x15\xe4\xb4\x9d"
b"o\x1d\xc4\xe5\n\x03\xcc2h\xc7\\\x86\xff\xf8\xe2\xfc\xe7\xd9\xfe6\xb8("
b"\xa8wd\xc2\"u.n\x1e\xc3\xf2\x8e\x8d\x8f\x02\x17/\xa6=\xf0\xa2\xdf/M\x89"
b"\xbe\xde\xa7\x1cz\x18-]\xd5\xef\x13\x8frZ\x15\x80\x8c\xf8\x8do\xfa\x12"
b"\x9b#z/\xef\xf0\xfaF\x01\x82\xa3M\x8e\xa1t\xca6 BF$\xe5Q\xa4\x98\xee\xde"
b"l\xe8\x7f\xf0\x9d,bn\x0b\x13\xd4\xa8\x81\xe4N\xc8\x86\x153\xf5x2\xa2O"
b"\x13@Q\xa1\x00/\xa5\xd0O\x97\xdco\xae\xf7z\xc4\xcdS\xb6t<\x16\xf2\x9cI#"
b"\x89ud\xc66Y\xd9\xee\xe6\xce\x12]\xe5\xf0\xaa\x96-Pe\xade:\x04\t\x1b\xf7"
b"\xdb7\n\x86\x1fp\xc8J\xba\xf4\xf0V\xa9\xdc\xf0\x02%G\xf9\xdf=?\x15\x1b"
b"\xe1(\xce\x82=\xd6I\xac3\x12\x0cR\xb7\xae\r\xb1i\x03\x95\x01\xbd\xbe\xfa"
b"\x02s\x01P\x9d\x96X\xb12j\xc8L\xa8\x84b\xf6\xc3\xd4c-H\x93oJl\xd0iQ\xe4k"
b"\x84\x0b\xc1\xb7\xbc\xb1\x17\x88\xb1\xca?@\xf6\x07\xea\xe6x\xf1H12P\x0f"
b"\x8a\xc9\xeauw\xe3\xbe\xaai\xa9W\xd0\x80\xcd#cb5\x99\xd8]\xa9d\x0c\xbd"
b"\xa2\xdcWl\xedUG\xbf\x89yF\xf77\x81v\xbd5\x98\xbeh8\x18W\x08\xf0\x1b\x99"
b"5:\x1a?rD\x96\xa1\x04\x0f\xae\xba\x85\xeb\x9d5@\xf5\x83\xd37\x83\x8ac"
b"\x06\xd4\x97i\xcdt\x16S\x82k\xf6K\x01vy\x88\x91\x9b6T\xdae\r\xfd]:k\xbal"
b"\xa9\xbba\xc34\xf9r\xeb}r\xdb\xc7\xdb*\x8f\x03z\xdc8h\xcc\xc9\xd3\xbcl"
b"\xa5-\xcb\xeaK\xa2\xc5\x15\xc0\xe3\xc1\x86Z\xfb\xebL\xe13\xcf\x9c\xe3"
b"\x1d\xc9\xed\xc2\x06\xcc\xce!\x92\xe5\xfe\x9c^\xa59w \x9bP\xa3PK\x08d"
b"\xf9\xe2Z}\xa7\xbf\xed\xeb%$\x0c\x82\xb8/\xb0\x01\xa9&,\xf7qh{Q\x96)\xf2"
b"q\x96\xc3\x80\xb4\x12\xb0\xba\xe6o\xf4!\xb4[\xd4\x8aw\x10\xf7t\x0c\xb3"
b"\xd9\xd5\xc3`^\x81\x11??\\\xa4\x99\x85R\xd4\x8e\x83\xc9\x1eX\xbfa\xf1"
b"\xac\xb0\xea\xea\xd7\xd0\xab\x18\xe2\xf2\xed\xe1\xb7\xc9\x18\xcbS\xe4>"
b"\xc9\x95H\xe8\xcb\t\r%\xeb\xc7$.o\xf1\xf3R\x17\x1db\xbb\xd8U\xa5^\xccS"
b"\x16\x01\x87\xf3/\x93\xd1\xf0v\xc0r\xd7\xcc\xa2Gkz\xca\x80\x0e\xfd\xd0"
b"\x8b\xbb\xd2Ix\xb3\x1ey\xca-0\xe3z^\xd6\xd6\x8f_\xf1\x9dP\x9fi\xa7\xd1"
b"\xe8\x90\x84\xdc\xbf\xcdky\x8e\xdc\x81\x7f\xa3\xb2+\xbf\x04\xef\xd8\\"
b"\xc4\xdf\xe1\xb0\x01\xe9\x93\xe3Y\xf1\x1dY\xe8h\x81\xcf\xf1w\xcc\xb4\xef"
b" \x8b|\x04\xea\x83ej\xbe\x1f\xd4z\x9c`\xd3\x1a\x92A\x06\xe5\x8f\xa9\x13"
b"\t\x9e=\xfa\x1c\xe5_\x9f%v\x1bo\x11ZO\xd8\xf4\t\xddM\x16-\x04\xfc\x18<\""
b"CM\xddg~b\xf6\xef\x8e\x0c\xd0\xde|\xa0'\x8a\x0c\xd6x\xae!J\xa6F\x88\x15u"
b"\x008\x17\xbc7y\xb3\xd8u\xac_\x85\x8d\xe7\xc1@\x9c\xecqc\xa3#\xad\xf1"
b"\x935\xb5)_\r\xec3]\x0fo]5\xd0my\x07\x9b\xee\x81\xb5\x0f\xcfK+\x00\xc0"
b"\xe4b\x10\xe4\x0c\x1a \x9b\xe0\x97t\xf6\xa1\x9e\x850\xba\x0c\x9a\x8d\xc8"
b"\x8f\x07\xd7\xae\xc8\xf9+i\xdc\xb9k\xb0>f\x19\xb8\r\xa8\xf8\x1f$\xa5{p"
b"\xc6\x880\xce\xdb\xcf\xca_\x86\xac\x88h6\x8bZ%'\xd0\n\xbf\x0f\x9c\"\xba"
b"\xe5\x86\x9f\x0f7X=mNX[\xcc\x19FU\xc9\x860\xbc\x90a+* \xae_$\x03\x1e\xd3"
b"\xcd_\xa0\x9c\xde\xaf46q\xa5\xc9\x92\xd7\xca\xe3`\x9d\x85}\xb4\xff\xb3"
b"\x83\xfb\xb6\xca\xae`\x0bw\x7f\xfc\xd8\xacVe\x19\xc8\x17\x0bZ\xad\x88"
b"\xeb#\x97\x03\x13\xb1d\x0f{\x0c\x04w\x07\r\x97\xbd\xd6\xc1\xc3B:\x95\x08"
b"^\x10V\xaeaH\x02\xd9\xe3\n\\\x01X\xf6\x9c\x8a\x06u#%\xbe*\xa1\x18v\x85"
b"\xec!\t4\x00\x00\x00\x00Vj?uLU\xf3\xa6\x00\x01\xfb\x07\x81\x0f\x00\x00tw"
b"\x99P\xb1\xc4g\xfb\x02\x00\x00\x00\x00\x04YZ"
)
COMPRESSED_ALONE = (
b"]\x00\x00\x80\x00\xff\xff\xff\xff\xff\xff\xff\xff\x00\x05\x14\x07bX\x19"
b"\xcd\xddn\x98\x15\xe4\xb4\x9do\x1d\xc4\xe5\n\x03\xcc2h\xc7\\\x86\xff\xf8"
b"\xe2\xfc\xe7\xd9\xfe6\xb8(\xa8wd\xc2\"u.n\x1e\xc3\xf2\x8e\x8d\x8f\x02"
b"\x17/\xa6=\xf0\xa2\xdf/M\x89\xbe\xde\xa7\x1cz\x18-]\xd5\xef\x13\x8frZ"
b"\x15\x80\x8c\xf8\x8do\xfa\x12\x9b#z/\xef\xf0\xfaF\x01\x82\xa3M\x8e\xa1t"
b"\xca6 BF$\xe5Q\xa4\x98\xee\xdel\xe8\x7f\xf0\x9d,bn\x0b\x13\xd4\xa8\x81"
b"\xe4N\xc8\x86\x153\xf5x2\xa2O\x13@Q\xa1\x00/\xa5\xd0O\x97\xdco\xae\xf7z"
b"\xc4\xcdS\xb6t<\x16\xf2\x9cI#\x89ud\xc66Y\xd9\xee\xe6\xce\x12]\xe5\xf0"
b"\xaa\x96-Pe\xade:\x04\t\x1b\xf7\xdb7\n\x86\x1fp\xc8J\xba\xf4\xf0V\xa9"
b"\xdc\xf0\x02%G\xf9\xdf=?\x15\x1b\xe1(\xce\x82=\xd6I\xac3\x12\x0cR\xb7"
b"\xae\r\xb1i\x03\x95\x01\xbd\xbe\xfa\x02s\x01P\x9d\x96X\xb12j\xc8L\xa8"
b"\x84b\xf8\x1epl\xeajr\xd1=\t\x03\xdd\x13\x1b3!E\xf9vV\xdaF\xf3\xd7\xb4"
b"\x0c\xa9P~\xec\xdeE\xe37\xf6\x1d\xc6\xbb\xddc%\xb6\x0fI\x07\xf0;\xaf\xe7"
b"\xa0\x8b\xa7Z\x99(\xe9\xe2\xf0o\x18>`\xe1\xaa\xa8\xd9\xa1\xb2}\xe7\x8d"
b"\x834T\xb6\xef\xc1\xde\xe3\x98\xbcD\x03MA@\xd8\xed\xdc\xc8\x93\x03\x1a"
b"\x93\x0b\x7f\x94\x12\x0b\x02Sa\x18\xc9\xc5\x9bTJE}\xf6\xc8g\x17#ZV\x01"
b"\xc9\x9dc\x83\x0e>0\x16\x90S\xb8/\x03y_\x18\xfa(\xd7\x0br\xa2\xb0\xba?"
b"\x8c\xe6\x83@\x84\xdf\x02:\xc5z\x9e\xa6\x84\xc9\xf5BeyX\x83\x1a\xf1 :\t"
b"\xf7\x19\xfexD\\&G\xf3\x85Y\xa2J\xf9\x0bv{\x89\xf6\xe7)A\xaf\x04o\x00"
b"\x075\xd3\xe0\x7f\x97\x98F\x0f?v\x93\xedVtTf\xb5\x97\x83\xed\x19\xd7\x1a"
b"'k\xd7\xd9\xc5\\Y\xd1\xdc\x07\x15|w\xbc\xacd\x87\x08d\xec\xa7\xf6\x82"
b"\xfc\xb3\x93\xeb\xb9 \x8d\xbc ,\xb3X\xb0\xd2s\xd7\xd1\xffv\x05\xdf}\xa2"
b"\x96\xfb%\n\xdf\xa2\x7f\x08.\xa16\n\xe0\x19\x93\x7fh\n\x1c\x8c\x0f \x11"
b"\xc6Bl\x95\x19U}\xe4s\xb5\x10H\xea\x86pB\xe88\x95\xbe\x8cZ\xdb\xe4\x94A"
b"\x92\xb9;z\xaa\xa7{\x1c5!\xc0\xaf\xc1A\xf9\xda\xf0$\xb0\x02qg\xc8\xc7/|"
b"\xafr\x99^\x91\x88\xbf\x03\xd9=\xd7n\xda6{>8\n\xc7:\xa9'\xba.\x0b\xe2"
b"\xb5\x1d\x0e\n\x9a\x8e\x06\x8f:\xdd\x82'[\xc3\"wD$\xa7w\xecq\x8c,1\x93"
b"\xd0,\xae2w\x93\x12$Jd\x19mg\x02\x93\x9cA\x95\x9d&\xca8i\x9c\xb0;\xe7NQ"
b"\x1frh\x8beL;\xb0m\xee\x07Q\x9b\xc6\xd8\x03\xb5\xdeN\xd4\xfe\x98\xd0\xdc"
b"\x1a[\x04\xde\x1a\xf6\x91j\xf8EOli\x8eB^\x1d\x82\x07\xb2\xb5R]\xb7\xd7"
b"\xe9\xa6\xc3.\xfb\xf0-\xb4e\x9b\xde\x03\x88\xc6\xc1iN\x0e\x84wbQ\xdf~"
b"\xe9\xa4\x884\x96kM\xbc)T\xf3\x89\x97\x0f\x143\xe7)\xa0\xb3B\x00\xa8\xaf"
b"\x82^\xcb\xc7..\xdb\xc7\t\x9dH\xee5\xe9#\xe6NV\x94\xcb$Kk\xe3\x7f\r\xe3t"
b"\x12\xcf'\xefR\x8b\xf42\xcf-LH\xac\xe5\x1f0~?SO\xeb\xc1E\x1a\x1c]\xf2"
b"\xc4<\x11\x02\x10Z0a*?\xe4r\xff\xfb\xff\xf6\x14nG\xead^\xd6\xef8\xb6uEI"
b"\x99\nV\xe2\xb3\x95\x8e\x83\xf6i!\xb5&1F\xb1DP\xf4 SO3D!w\x99_G\x7f+\x90"
b".\xab\xbb]\x91>\xc9#h;\x0f5J\x91K\xf4^-[\x9e\x8a\\\x94\xca\xaf\xf6\x19"
b"\xd4\xa1\x9b\xc4\xb8p\xa1\xae\x15\xe9r\x84\xe0\xcar.l []\x8b\xaf+0\xf2g"
b"\x01aKY\xdfI\xcf,\n\xe8\xf0\xe7V\x80_#\xb2\xf2\xa9\x06\x8c>w\xe2W,\xf4"
b"\x8c\r\xf963\xf5J\xcc2\x05=kT\xeaUti\xe5_\xce\x1b\xfa\x8dl\x02h\xef\xa8"
b"\xfbf\x7f\xff\xf0\x19\xeax"
)
FILTERS_RAW_1 = [{"id": lzma.FILTER_LZMA2, "preset": 3}]
COMPRESSED_RAW_1 = (
b"\xe0\x07\x80\x03\xfd]\x00\x05\x14\x07bX\x19\xcd\xddn\x96cyq\xa1\xdd\xee"
b"\xf8\xfam\xe3'\x88\xd3\xff\xe4\x9e \xceQ\x91\xa4\x14I\xf6\xb9\x9dVL8\x15"
b"_\x0e\x12\xc3\xeb\xbc\xa5\xcd\nW\x1d$=R;\x1d\xf8k8\t\xb1{\xd4\xc5+\x9d"
b"\x87c\xe5\xef\x98\xb4\xd7S3\xcd\xcc\xd2\xed\xa4\x0em\xe5\xf4\xdd\xd0b"
b"\xbe4*\xaa\x0b\xc5\x08\x10\x85+\x81.\x17\xaf9\xc9b\xeaZrA\xe20\x7fs\"r"
b"\xdaG\x81\xde\x90cu\xa5\xdb\xa9.A\x08l\xb0<\xf6\x03\xddOi\xd0\xc5\xb4"
b"\xec\xecg4t6\"\xa6\xb8o\xb5?\x18^}\xb6}\x03[:\xeb\x03\xa9\n[\x89l\x19g"
b"\x16\xc82\xed\x0b\xfb\x86n\xa2\x857@\x93\xcd6T\xc3u\xb0\t\xf9\x1b\x918"
b"\xfc[\x1b\x1e4\xb3\x14\x06PCV\xa8\"\xf5\x81x~\xe9\xb5N\x9cK\x9f\xc6\xc3%"
b"\xc8k:{6\xe7\xf7\xbd\x05\x02\xb4\xc4\xc3\xd3\xfd\xc3\xa8\\\xfc@\xb1F_"
b"\xc8\x90\xd9sU\x98\xad8\x05\x07\xde7J\x8bM\xd0\xb3;X\xec\x87\xef\xae\xb3"
b"eO,\xb1z,d\x11y\xeejlB\x02\x1d\xf28\x1f#\x896\xce\x0b\xf0\xf5\xa9PK\x0f"
b"\xb3\x13P\xd8\x88\xd2\xa1\x08\x04C?\xdb\x94_\x9a\"\xe9\xe3e\x1d\xde\x9b"
b"\xa1\xe8>H\x98\x10;\xc5\x03#\xb5\x9d4\x01\xe7\xc5\xba%v\xa49\x97A\xe0\""
b"\x8c\xc22\xe3i\xc1\x9d\xab3\xdf\xbe\xfdDm7\x1b\x9d\xab\xb5\x15o:J\x92"
b"\xdb\x816\x17\xc2O\x99\x1b\x0e\x8d\xf3\tQ\xed\x8e\x95S/\x16M\xb2S\x04"
b"\x0f\xc3J\xc6\xc7\xe4\xcb\xc5\xf4\xe7d\x14\xe4=^B\xfb\xd3E\xd3\x1e\xcd"
b"\x91\xa5\xd0G\x8f.\xf6\xf9\x0bb&\xd9\x9f\xc2\xfdj\xa2\x9e\xc4\\\x0e\x1dC"
b"v\xe8\xd2\x8a?^H\xec\xae\xeb>\xfe\xb8\xab\xd4IqY\x8c\xd4K7\x11\xf4D\xd0W"
b"\xa5\xbe\xeaO\xbf\xd0\x04\xfdl\x10\xae5\xd4U\x19\x06\xf9{\xaa\xe0\x81"
b"\x0f\xcf\xa3k{\x95\xbd\x19\xa2\xf8\xe4\xa3\x08O*\xf1\xf1B-\xc7(\x0eR\xfd"
b"@E\x9f\xd3\x1e:\xfdV\xb7\x04Y\x94\xeb]\x83\xc4\xa5\xd7\xc0gX\x98\xcf\x0f"
b"\xcd3\x00]n\x17\xec\xbd\xa3Y\x86\xc5\xf3u\xf6*\xbdT\xedA$A\xd9A\xe7\x98"
b"\xef\x14\x02\x9a\xfdiw\xec\xa0\x87\x11\xd9%\xc5\xeb\x8a=\xae\xc0\xc4\xc6"
b"D\x80\x8f\xa8\xd1\xbbq\xb2\xc0\xa0\xf5Cqp\xeeL\xe3\xe5\xdc \x84\"\xe9"
b"\x80t\x83\x05\xba\xf1\xc5~\x93\xc9\xf0\x01c\xceix\x9d\xed\xc5)l\x16)\xd1"
b"\x03@l\x04\x7f\x87\xa5yn\x1b\x01D\xaa:\xd2\x96\xb4\xb3?\xb0\xf9\xce\x07"
b"\xeb\x81\x00\xe4\xc3\xf5%_\xae\xd4\xf9\xeb\xe2\rh\xb2#\xd67Q\x16D\x82hn"
b"\xd1\xa3_?q\xf0\xe2\xac\xf317\x9e\xd0_\x83|\xf1\xca\xb7\x95S\xabW\x12"
b"\xff\xddt\xf69L\x01\xf2|\xdaW\xda\xees\x98L\x18\xb8_\xe8$\x82\xea\xd6"
b"\xd1F\xd4\x0b\xcdk\x01vf\x88h\xc3\xae\xb91\xc7Q\x9f\xa5G\xd9\xcc\x1f\xe3"
b"5\xb1\xdcy\x7fI\x8bcw\x8e\x10rIp\x02:\x19p_\xc8v\xcea\"\xc1\xd9\x91\x03"
b"\xbfe\xbe\xa6\xb3\xa8\x14\x18\xc3\xabH*m}\xc2\xc1\x9a}>l%\xce\x84\x99"
b"\xb3d\xaf\xd3\x82\x15\xdf\xc1\xfc5fOg\x9b\xfc\x8e^&\t@\xce\x9f\x06J\xb8"
b"\xb5\x86\x1d\xda{\x9f\xae\xb0\xff\x02\x81r\x92z\x8cM\xb7ho\xc9^\x9c\xb6"
b"\x9c\xae\xd1\xc9\xf4\xdfU7\xd6\\!\xea\x0b\x94k\xb9Ud~\x98\xe7\x86\x8az"
b"\x10;\xe3\x1d\xe5PG\xf8\xa4\x12\x05w\x98^\xc4\xb1\xbb\xfb\xcf\xe0\x7f"
b"\x033Sf\x0c \xb1\xf6@\x94\xe5\xa3\xb2\xa7\x10\x9a\xc0\x14\xc3s\xb5xRD"
b"\xf4`W\xd9\xe5\xd3\xcf\x91\rTZ-X\xbe\xbf\xb5\xe2\xee|\x1a\xbf\xfb\x08"
b"\x91\xe1\xfc\x9a\x18\xa3\x8b\xd6^\x89\xf5[\xef\x87\xd1\x06\x1c7\xd6\xa2"
b"\t\tQ5/@S\xc05\xd2VhAK\x03VC\r\x9b\x93\xd6M\xf1xO\xaaO\xed\xb9<\x0c\xdae"
b"*\xd0\x07Hk6\x9fG+\xa1)\xcd\x9cl\x87\xdb\xe1\xe7\xefK}\x875\xab\xa0\x19u"
b"\xf6*F\xb32\x00\x00\x00"
)
FILTERS_RAW_2 = [{"id": lzma.FILTER_DELTA, "dist": 2},
{"id": lzma.FILTER_LZMA2,
"preset": lzma.PRESET_DEFAULT | lzma.PRESET_EXTREME}]
COMPRESSED_RAW_2 = (
b"\xe0\x07\x80\x05\x91]\x00\x05\x14\x06-\xd4\xa8d?\xef\xbe\xafH\xee\x042"
b"\xcb.\xb5g\x8f\xfb\x14\xab\xa5\x9f\x025z\xa4\xdd\xd8\t[}W\xf8\x0c\x1dmH"
b"\xfa\x05\xfcg\xba\xe5\x01Q\x0b\x83R\xb6A\x885\xc0\xba\xee\n\x1cv~\xde:o"
b"\x06:J\xa7\x11Cc\xea\xf7\xe5*o\xf7\x83\\l\xbdE\x19\x1f\r\xa8\x10\xb42"
b"\x0caU{\xd7\xb8w\xdc\xbe\x1b\xfc8\xb4\xcc\xd38\\\xf6\x13\xf6\xe7\x98\xfa"
b"\xc7[\x17_9\x86%\xa8\xf8\xaa\xb8\x8dfs#\x1e=\xed<\x92\x10\\t\xff\x86\xfb"
b"=\x9e7\x18\x1dft\\\xb5\x01\x95Q\xc5\x19\xb38\xe0\xd4\xaa\x07\xc3\x7f\xd8"
b"\xa2\x00>-\xd3\x8e\xa1#\xfa\x83ArAm\xdbJ~\x93\xa3B\x82\xe0\xc7\xcc(\x08`"
b"WK\xad\x1b\x94kaj\x04 \xde\xfc\xe1\xed\xb0\x82\x91\xefS\x84%\x86\xfbi"
b"\x99X\xf1B\xe7\x90;E\xfde\x98\xda\xca\xd6T\xb4bg\xa4\n\x9aj\xd1\x83\x9e]"
b"\"\x7fM\xb5\x0fr\xd2\\\xa5j~P\x10GH\xbfN*Z\x10.\x81\tpE\x8a\x08\xbe1\xbd"
b"\xcd\xa9\xe1\x8d\x1f\x04\xf9\x0eH\xb9\xae\xd6\xc3\xc1\xa5\xa9\x95P\xdc~"
b"\xff\x01\x930\xa9\x04\xf6\x03\xfe\xb5JK\xc3]\xdd9\xb1\xd3\xd7F\xf5\xd1"
b"\x1e\xa0\x1c_\xed[\x0c\xae\xd4\x8b\x946\xeb\xbf\xbb\xe3$kS{\xb5\x80,f:Sj"
b"\x0f\x08z\x1c\xf5\xe8\xe6\xae\x98\xb0Q~r\x0f\xb0\x05?\xb6\x90\x19\x02&"
b"\xcb\x80\t\xc4\xea\x9c|x\xce\x10\x9c\xc5|\xcbdhh+\x0c'\xc5\x81\xc33\xb5"
b"\x14q\xd6\xc5\xe3`Z#\xdc\x8a\xab\xdd\xea\x08\xc2I\xe7\x02l{\xec\x196\x06"
b"\x91\x8d\xdc\xd5\xb3x\xe1hz%\xd1\xf8\xa5\xdd\x98!\x8c\x1c\xc1\x17RUa\xbb"
b"\x95\x0f\xe4X\xea1\x0c\xf1=R\xbe\xc60\xe3\xa4\x9a\x90bd\x97$]B\x01\xdd"
b"\x1f\xe3h2c\x1e\xa0L`4\xc6x\xa3Z\x8a\r\x14]T^\xd8\x89\x1b\x92\r;\xedY"
b"\x0c\xef\x8d9z\xf3o\xb6)f\xa9]$n\rp\x93\xd0\x10\xa4\x08\xb8\xb2\x8b\xb6"
b"\x8f\x80\xae;\xdcQ\xf1\xfa\x9a\x06\x8e\xa5\x0e\x8cK\x9c @\xaa:UcX\n!\xc6"
b"\x02\x12\xcb\x1b\"=\x16.\x1f\x176\xf2g=\xe1Wn\xe9\xe1\xd4\xf1O\xad\x15"
b"\x86\xe9\xa3T\xaf\xa9\xd7D\xb5\xd1W3pnt\x11\xc7VOj\xb7M\xc4i\xa1\xf1$3"
b"\xbb\xdc\x8af\xb0\xc5Y\r\xd1\xfb\xf2\xe7K\xe6\xc5hwO\xfe\x8c2^&\x07\xd5"
b"\x1fV\x19\xfd\r\x14\xd2i=yZ\xe6o\xaf\xc6\xb6\x92\x9d\xc4\r\xb3\xafw\xac%"
b"\xcfc\x1a\xf1`]\xf2\x1a\x9e\x808\xedm\xedQ\xb2\xfe\xe4h`[q\xae\xe0\x0f"
b"\xba0g\xb6\"N\xc3\xfb\xcfR\x11\xc5\x18)(\xc40\\\xa3\x02\xd9G!\xce\x1b"
b"\xc1\x96x\xb5\xc8z\x1f\x01\xb4\xaf\xde\xc2\xcd\x07\xe7H\xb3y\xa8M\n\\A\t"
b"ar\xddM\x8b\x9a\xea\x84\x9b!\xf1\x8d\xb1\xf1~\x1e\r\xa5H\xba\xf1\x84o"
b"\xda\x87\x01h\xe9\xa2\xbe\xbeqN\x9d\x84\x0b!WG\xda\xa1\xa5A\xb7\xc7`j"
b"\x15\xf2\xe9\xdd?\x015B\xd2~E\x06\x11\xe0\x91!\x05^\x80\xdd\xa8y\x15}"
b"\xa1)\xb1)\x81\x18\xf4\xf4\xf8\xc0\xefD\xe3\xdb2f\x1e\x12\xabu\xc9\x97"
b"\xcd\x1e\xa7\x0c\x02x4_6\x03\xc4$t\xf39\x94\x1d=\xcb\xbfv\\\xf5\xa3\x1d"
b"\x9d8jk\x95\x13)ff\xf9n\xc4\xa9\xe3\x01\xb8\xda\xfb\xab\xdfM\x99\xfb\x05"
b"\xe0\xe9\xb0I\xf4E\xab\xe2\x15\xa3\x035\xe7\xdeT\xee\x82p\xb4\x88\xd3"
b"\x893\x9c/\xc0\xd6\x8fou;\xf6\x95PR\xa9\xb2\xc1\xefFj\xe2\xa7$\xf7h\xf1"
b"\xdfK(\xc9c\xba7\xe8\xe3)\xdd\xb2,\x83\xfb\x84\x18.y\x18Qi\x88\xf8`h-"
b"\xef\xd5\xed\x8c\t\xd8\xc3^\x0f\x00\xb7\xd0[!\xafM\x9b\xd7.\x07\xd8\xfb"
b"\xd9\xe2-S+\xaa8,\xa0\x03\x1b \xea\xa8\x00\xc3\xab~\xd0$e\xa5\x7f\xf7"
b"\x95P]\x12\x19i\xd9\x7fo\x0c\xd8g^\rE\xa5\x80\x18\xc5\x01\x80\xaek`\xff~"
b"\xb6y\xe7+\xe5\x11^D\xa7\x85\x18\"!\xd6\xd2\xa7\xf4\x1eT\xdb\x02\xe15"
b"\x02Y\xbc\x174Z\xe7\x9cH\x1c\xbf\x0f\xc6\xe9f]\xcf\x8cx\xbc\xe5\x15\x94"
b"\xfc3\xbc\xa7TUH\xf1\x84\x1b\xf7\xa9y\xc07\x84\xf8X\xd8\xef\xfc \x1c\xd8"
b"( /\xf2\xb7\xec\xc1\\\x8c\xf6\x95\xa1\x03J\x83vP8\xe1\xe3\xbb~\xc24kA"
b"\x98y\xa1\xf2P\xe9\x9d\xc9J\xf8N\x99\xb4\xceaO\xde\x16\x1e\xc2\x19\xa7"
b"\x03\xd2\xe0\x8f:\x15\xf3\x84\x9e\xee\xe6e\xb8\x02q\xc7AC\x1emw\xfd\t"
b"\x9a\x1eu\xc1\xa9\xcaCwUP\x00\xa5\xf78L4w!\x91L2 \x87\xd0\xf2\x06\x81j"
b"\x80;\x03V\x06\x87\x92\xcb\x90lv@E\x8d\x8d\xa5\xa6\xe7Z[\xdf\xd6E\x03`>"
b"\x8f\xde\xa1bZ\x84\xd0\xa9`\x05\x0e{\x80;\xe3\xbef\x8d\x1d\xebk1.\xe3"
b"\xe9N\x15\xf7\xd4(\xfa\xbb\x15\xbdu\xf7\x7f\x86\xae!\x03L\x1d\xb5\xc1"
b"\xb9\x11\xdb\xd0\x93\xe4\x02\xe1\xd2\xcbBjc_\xe8}d\xdb\xc3\xa0Y\xbe\xc9/"
b"\x95\x01\xa3,\xe6bl@\x01\xdbp\xc2\xce\x14\x168\xc2q\xe3uH\x89X\xa4\xa9"
b"\x19\x1d\xc1}\x7fOX\x19\x9f\xdd\xbe\x85\x83\xff\x96\x1ee\x82O`CF=K\xeb$I"
b"\x17_\xefX\x8bJ'v\xde\x1f+\xd9.v\xf8Tv\x17\xf2\x9f5\x19\xe1\xb9\x91\xa8S"
b"\x86\xbd\x1a\"(\xa5x\x8dC\x03X\x81\x91\xa8\x11\xc4pS\x13\xbc\xf2'J\xae!"
b"\xef\xef\x84G\t\x8d\xc4\x10\x132\x00oS\x9e\xe0\xe4d\x8f\xb8y\xac\xa6\x9f"
b",\xb8f\x87\r\xdf\x9eE\x0f\xe1\xd0\\L\x00\xb2\xe1h\x84\xef}\x98\xa8\x11"
b"\xccW#\\\x83\x7fo\xbbz\x8f\x00"
)
FILTERS_RAW_3 = [{"id": lzma.FILTER_IA64, "start_offset": 0x100},
{"id": lzma.FILTER_LZMA2}]
COMPRESSED_RAW_3 = (
b"\xe0\x07\x80\x03\xdf]\x00\x05\x14\x07bX\x19\xcd\xddn\x98\x15\xe4\xb4\x9d"
b"o\x1d\xc4\xe5\n\x03\xcc2h\xc7\\\x86\xff\xf8\xe2\xfc\xe7\xd9\xfe6\xb8("
b"\xa8wd\xc2\"u.n\x1e\xc3\xf2\x8e\x8d\x8f\x02\x17/\xa6=\xf0\xa2\xdf/M\x89"
b"\xbe\xde\xa7\x1cz\x18-]\xd5\xef\x13\x8frZ\x15\x80\x8c\xf8\x8do\xfa\x12"
b"\x9b#z/\xef\xf0\xfaF\x01\x82\xa3M\x8e\xa1t\xca6 BF$\xe5Q\xa4\x98\xee\xde"
b"l\xe8\x7f\xf0\x9d,bn\x0b\x13\xd4\xa8\x81\xe4N\xc8\x86\x153\xf5x2\xa2O"
b"\x13@Q\xa1\x00/\xa5\xd0O\x97\xdco\xae\xf7z\xc4\xcdS\xb6t<\x16\xf2\x9cI#"
b"\x89ud\xc66Y\xd9\xee\xe6\xce\x12]\xe5\xf0\xaa\x96-Pe\xade:\x04\t\x1b\xf7"
b"\xdb7\n\x86\x1fp\xc8J\xba\xf4\xf0V\xa9\xdc\xf0\x02%G\xf9\xdf=?\x15\x1b"
b"\xe1(\xce\x82=\xd6I\xac3\x12\x0cR\xb7\xae\r\xb1i\x03\x95\x01\xbd\xbe\xfa"
b"\x02s\x01P\x9d\x96X\xb12j\xc8L\xa8\x84b\xf6\xc3\xd4c-H\x93oJl\xd0iQ\xe4k"
b"\x84\x0b\xc1\xb7\xbc\xb1\x17\x88\xb1\xca?@\xf6\x07\xea\xe6x\xf1H12P\x0f"
b"\x8a\xc9\xeauw\xe3\xbe\xaai\xa9W\xd0\x80\xcd#cb5\x99\xd8]\xa9d\x0c\xbd"
b"\xa2\xdcWl\xedUG\xbf\x89yF\xf77\x81v\xbd5\x98\xbeh8\x18W\x08\xf0\x1b\x99"
b"5:\x1a?rD\x96\xa1\x04\x0f\xae\xba\x85\xeb\x9d5@\xf5\x83\xd37\x83\x8ac"
b"\x06\xd4\x97i\xcdt\x16S\x82k\xf6K\x01vy\x88\x91\x9b6T\xdae\r\xfd]:k\xbal"
b"\xa9\xbba\xc34\xf9r\xeb}r\xdb\xc7\xdb*\x8f\x03z\xdc8h\xcc\xc9\xd3\xbcl"
b"\xa5-\xcb\xeaK\xa2\xc5\x15\xc0\xe3\xc1\x86Z\xfb\xebL\xe13\xcf\x9c\xe3"
b"\x1d\xc9\xed\xc2\x06\xcc\xce!\x92\xe5\xfe\x9c^\xa59w \x9bP\xa3PK\x08d"
b"\xf9\xe2Z}\xa7\xbf\xed\xeb%$\x0c\x82\xb8/\xb0\x01\xa9&,\xf7qh{Q\x96)\xf2"
b"q\x96\xc3\x80\xb4\x12\xb0\xba\xe6o\xf4!\xb4[\xd4\x8aw\x10\xf7t\x0c\xb3"
b"\xd9\xd5\xc3`^\x81\x11??\\\xa4\x99\x85R\xd4\x8e\x83\xc9\x1eX\xbfa\xf1"
b"\xac\xb0\xea\xea\xd7\xd0\xab\x18\xe2\xf2\xed\xe1\xb7\xc9\x18\xcbS\xe4>"
b"\xc9\x95H\xe8\xcb\t\r%\xeb\xc7$.o\xf1\xf3R\x17\x1db\xbb\xd8U\xa5^\xccS"
b"\x16\x01\x87\xf3/\x93\xd1\xf0v\xc0r\xd7\xcc\xa2Gkz\xca\x80\x0e\xfd\xd0"
b"\x8b\xbb\xd2Ix\xb3\x1ey\xca-0\xe3z^\xd6\xd6\x8f_\xf1\x9dP\x9fi\xa7\xd1"
b"\xe8\x90\x84\xdc\xbf\xcdky\x8e\xdc\x81\x7f\xa3\xb2+\xbf\x04\xef\xd8\\"
b"\xc4\xdf\xe1\xb0\x01\xe9\x93\xe3Y\xf1\x1dY\xe8h\x81\xcf\xf1w\xcc\xb4\xef"
b" \x8b|\x04\xea\x83ej\xbe\x1f\xd4z\x9c`\xd3\x1a\x92A\x06\xe5\x8f\xa9\x13"
b"\t\x9e=\xfa\x1c\xe5_\x9f%v\x1bo\x11ZO\xd8\xf4\t\xddM\x16-\x04\xfc\x18<\""
b"CM\xddg~b\xf6\xef\x8e\x0c\xd0\xde|\xa0'\x8a\x0c\xd6x\xae!J\xa6F\x88\x15u"
b"\x008\x17\xbc7y\xb3\xd8u\xac_\x85\x8d\xe7\xc1@\x9c\xecqc\xa3#\xad\xf1"
b"\x935\xb5)_\r\xec3]\x0fo]5\xd0my\x07\x9b\xee\x81\xb5\x0f\xcfK+\x00\xc0"
b"\xe4b\x10\xe4\x0c\x1a \x9b\xe0\x97t\xf6\xa1\x9e\x850\xba\x0c\x9a\x8d\xc8"
b"\x8f\x07\xd7\xae\xc8\xf9+i\xdc\xb9k\xb0>f\x19\xb8\r\xa8\xf8\x1f$\xa5{p"
b"\xc6\x880\xce\xdb\xcf\xca_\x86\xac\x88h6\x8bZ%'\xd0\n\xbf\x0f\x9c\"\xba"
b"\xe5\x86\x9f\x0f7X=mNX[\xcc\x19FU\xc9\x860\xbc\x90a+* \xae_$\x03\x1e\xd3"
b"\xcd_\xa0\x9c\xde\xaf46q\xa5\xc9\x92\xd7\xca\xe3`\x9d\x85}\xb4\xff\xb3"
b"\x83\xfb\xb6\xca\xae`\x0bw\x7f\xfc\xd8\xacVe\x19\xc8\x17\x0bZ\xad\x88"
b"\xeb#\x97\x03\x13\xb1d\x0f{\x0c\x04w\x07\r\x97\xbd\xd6\xc1\xc3B:\x95\x08"
b"^\x10V\xaeaH\x02\xd9\xe3\n\\\x01X\xf6\x9c\x8a\x06u#%\xbe*\xa1\x18v\x85"
b"\xec!\t4\x00\x00\x00"
)
FILTERS_RAW_4 = [{"id": lzma.FILTER_DELTA, "dist": 4},
{"id": lzma.FILTER_X86, "start_offset": 0x40},
{"id": lzma.FILTER_LZMA2, "preset": 4, "lc": 2}]
COMPRESSED_RAW_4 = (
b"\xe0\x07\x80\x06\x0e\\\x00\x05\x14\x07bW\xaah\xdd\x10\xdc'\xd6\x90,\xc6v"
b"Jq \x14l\xb7\x83xB\x0b\x97f=&fx\xba\n>Tn\xbf\x8f\xfb\x1dF\xca\xc3v_\xca?"
b"\xfbV<\x92#\xd4w\xa6\x8a\xeb\xf6\x03\xc0\x01\x94\xd8\x9e\x13\x12\x98\xd1"
b"*\xfa]c\xe8\x1e~\xaf\xb5]Eg\xfb\x9e\x01\"8\xb2\x90\x06=~\xe9\x91W\xcd"
b"\xecD\x12\xc7\xfa\xe1\x91\x06\xc7\x99\xb9\xe3\x901\x87\x19u\x0f\x869\xff"
b"\xc1\xb0hw|\xb0\xdcl\xcck\xb16o7\x85\xee{Y_b\xbf\xbc$\xf3=\x8d\x8bw\xe5Z"
b"\x08@\xc4kmE\xad\xfb\xf6*\xd8\xad\xa1\xfb\xc5{\xdej,)\x1emB\x1f<\xaeca"
b"\x80(\xee\x07 \xdf\xe9\xf8\xeb\x0e-\x97\x86\x90c\xf9\xea'B\xf7`\xd7\xb0"
b"\x92\xbd\xa0\x82]\xbd\x0e\x0eB\x19\xdc\x96\xc6\x19\xd86D\xf0\xd5\x831"
b"\x03\xb7\x1c\xf7&5\x1a\x8f PZ&j\xf8\x98\x1bo\xcc\x86\x9bS\xd3\xa5\xcdu"
b"\xf9$\xcc\x97o\xe5V~\xfb\x97\xb5\x0b\x17\x9c\xfdxW\x10\xfep4\x80\xdaHDY"
b"\xfa)\xfet\xb5\"\xd4\xd3F\x81\xf4\x13\x1f\xec\xdf\xa5\x13\xfc\"\x91x\xb7"
b"\x99\xce\xc8\x92\n\xeb[\x10l*Y\xd8\xb1@\x06\xc8o\x8d7r\xebu\xfd5\x0e\x7f"
b"\xf1$U{\t}\x1fQ\xcfxN\x9d\x9fXX\xe9`\x83\xc1\x06\xf4\x87v-f\x11\xdb/\\"
b"\x06\xff\xd7)B\xf3g\x06\x88#2\x1eB244\x7f4q\t\xc893?mPX\x95\xa6a\xfb)d"
b"\x9b\xfc\x98\x9aj\x04\xae\x9b\x9d\x19w\xba\xf92\xfaA\x11\\\x17\x97C3\xa4"
b"\xbc!\x88\xcdo[\xec:\x030\x91.\x85\xe0@\\4\x16\x12\x9d\xcaJv\x97\xb04"
b"\xack\xcbkf\xa3ss\xfc\x16^\x8ce\x85a\xa5=&\xecr\xb3p\xd1E\xd5\x80y\xc7"
b"\xda\xf6\xfek\xbcT\xbfH\xee\x15o\xc5\x8c\x830\xec\x1d\x01\xae\x0c-e\\"
b"\x91\x90\x94\xb2\xf8\x88\x91\xe8\x0b\xae\xa7>\x98\xf6\x9ck\xd2\xc6\x08"
b"\xe6\xab\t\x98\xf2!\xa0\x8c^\xacqA\x99<\x1cEG\x97\xc8\xf1\xb6\xb9\x82"
b"\x8d\xf7\x08s\x98a\xff\xe3\xcc\x92\x0e\xd2\xb6U\xd7\xd9\x86\x7fa\xe5\x1c"
b"\x8dTG@\t\x1e\x0e7*\xfc\xde\xbc]6N\xf7\xf1\x84\x9e\x9f\xcf\xe9\x1e\xb5'"
b"\xf4<\xdf\x99sq\xd0\x9d\xbd\x99\x0b\xb4%p4\xbf{\xbb\x8a\xd2\x0b\xbc=M"
b"\x94H:\xf5\xa8\xd6\xa4\xc90\xc2D\xb9\xd3\xa8\xb0S\x87 `\xa2\xeb\xf3W\xce"
b" 7\xf9N#\r\xe6\xbe\t\x9d\xe7\x811\xf9\x10\xc1\xc2\x14\xf6\xfc\xcba\xb7"
b"\xb1\x7f\x95l\xe4\tjA\xec:\x10\xe5\xfe\xc2\\=D\xe2\x0c\x0b3]\xf7\xc1\xf7"
b"\xbceZ\xb1A\xea\x16\xe5\xfddgFQ\xed\xaf\x04\xa3\xd3\xf8\xa2q\x19B\xd4r"
b"\xc5\x0c\x9a\x14\x94\xea\x91\xc4o\xe4\xbb\xb4\x99\xf4@\xd1\xe6\x0c\xe3"
b"\xc6d\xa0Q\n\xf2/\xd8\xb8S5\x8a\x18:\xb5g\xac\x95D\xce\x17\x07\xd4z\xda"
b"\x90\xe65\x07\x19H!\t\xfdu\x16\x8e\x0eR\x19\xf4\x8cl\x0c\xf9Q\xf1\x80"
b"\xe3\xbf\xd7O\xf8\x8c\x18\x0b\x9c\xf1\x1fb\xe1\tR\xb2\xf1\xe1A\xea \xcf-"
b"IGE\xf1\x14\x98$\x83\x15\xc9\xd8j\xbf\x19\x0f\xd5\xd1\xaa\xb3\xf3\xa5I2s"
b"\x8d\x145\xca\xd5\xd93\x9c\xb8D0\xe6\xaa%\xd0\xc0P}JO^h\x8e\x08\xadlV."
b"\x18\x88\x13\x05o\xb0\x07\xeaw\xe0\xb6\xa4\xd5*\xe4r\xef\x07G+\xc1\xbei["
b"w\xe8\xab@_\xef\x15y\xe5\x12\xc9W\x1b.\xad\x85-\xc2\xf7\xe3mU6g\x8eSA"
b"\x01(\xd3\xdb\x16\x13=\xde\x92\xf9,D\xb8\x8a\xb2\xb4\xc9\xc3\xefnE\xe8\\"
b"\xa6\xe2Y\xd2\xcf\xcb\x8c\xb6\xd5\xe9\x1d\x1e\x9a\x8b~\xe2\xa6\rE\x84uV"
b"\xed\xc6\x99\xddm<\x10[\x0fu\x1f\xc1\x1d1\n\xcfw\xb2%!\xf0[\xce\x87\x83B"
b"\x08\xaa,\x08%d\xcef\x94\"\xd9g.\xc83\xcbXY+4\xec\x85qA\n\x1d=9\xf0*\xb1"
b"\x1f/\xf3s\xd61b\x7f@\xfb\x9d\xe3FQ\\\xbd\x82\x1e\x00\xf3\xce\xd3\xe1"
b"\xca,E\xfd7[\xab\xb6\xb7\xac!mA}\xbd\x9d3R5\x9cF\xabH\xeb\x92)cc\x13\xd0"
b"\xbd\xee\xe9n{\x1dIJB\xa5\xeb\x11\xe8`w&`\x8b}@Oxe\t\x8a\x07\x02\x95\xf2"
b"\xed\xda|\xb1e\xbe\xaa\xbbg\x19@\xe1Y\x878\x84\x0f\x8c\xe3\xc98\xf2\x9e"
b"\xd5N\xb5J\xef\xab!\xe2\x8dq\xe1\xe5q\xc5\xee\x11W\xb7\xe4k*\x027\xa0"
b"\xa3J\xf4\xd8m\xd0q\x94\xcb\x07\n:\xb6`.\xe4\x9c\x15+\xc0)\xde\x80X\xd4"
b"\xcfQm\x01\xc2cP\x1cA\x85'\xc9\xac\x8b\xe6\xb2)\xe6\x84t\x1c\x92\xe4Z"
b"\x1cR\xb0\x9e\x96\xd1\xfb\x1c\xa6\x8b\xcb`\x10\x12]\xf2gR\x9bFT\xe0\xc8H"
b"S\xfb\xac<\x04\xc7\xc1\xe8\xedP\xf4\x16\xdb\xc0\xd7e\xc2\x17J^\x1f\xab"
b"\xff[\x08\x19\xb4\xf5\xfb\x19\xb4\x04\xe5c~']\xcb\xc2A\xec\x90\xd0\xed"
b"\x06,\xc5K{\x86\x03\xb1\xcdMx\xdeQ\x8c3\xf9\x8a\xea=\x89\xaba\xd2\xc89a"
b"\xd72\xf0\xc3\x19\x8a\xdfs\xd4\xfd\xbb\x81b\xeaE\"\xd8\xf4d\x0cD\xf7IJ!"
b"\xe5d\xbbG\xe9\xcam\xaa\x0f_r\x95\x91NBq\xcaP\xce\xa7\xa9\xb5\x10\x94eP!"
b"|\x856\xcd\xbfIir\xb8e\x9bjP\x97q\xabwS7\x1a\x0ehM\xe7\xca\x86?\xdeP}y~"
b"\x0f\x95I\xfc\x13\xe1<Q\x1b\x868\x1d\x11\xdf\x94\xf4\x82>r\xa9k\x88\xcb"
b"\xfd\xc3v\xe2\xb9\x8a\x02\x8eq\x92I\xf8\xf6\xf1\x03s\x9b\xb8\xe3\"\xe3"
b"\xa9\xa5>D\xb8\x96;\xe7\x92\xd133\xe8\xdd'e\xc9.\xdc;\x17\x1f\xf5H\x13q"
b"\xa4W\x0c\xdb~\x98\x01\xeb\xdf\xe32\x13\x0f\xddx\n6\xa0\t\x10\xb6\xbb"
b"\xb0\xc3\x18\xb6;\x9fj[\xd9\xd5\xc9\x06\x8a\x87\xcd\xe5\xee\xfc\x9c-%@"
b"\xee\xe0\xeb\xd2\xe3\xe8\xfb\xc0\x122\\\xc7\xaf\xc2\xa1Oth\xb3\x8f\x82"
b"\xb3\x18\xa8\x07\xd5\xee_\xbe\xe0\x1cA\x1e_\r\x9a\xb0\x17W&\xa2D\x91\x94"
b"\x1a\xb2\xef\xf2\xdc\x85;X\xb0,\xeb>-7S\xe5\xca\x07)\x1fp\x7f\xcaQBL\xca"
b"\xf3\xb9d\xfc\xb5su\xb0\xc8\x95\x90\xeb*)\xa0v\xe4\x9a{FW\xf4l\xde\xcdj"
b"\x00"
)
def test_main():
run_unittest(
CompressorDecompressorTestCase,
CompressDecompressFunctionTestCase,
FileTestCase,
OpenTestCase,
MiscellaneousTestCase,
)
if __name__ == "__main__":
test_main()
| 79,724 | 1,777 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_reprlib.py | """
Test cases for the repr module
Nick Mathewson
"""
import sys
import os
import shutil
import importlib
import importlib.util
import unittest
from test.support import create_empty_file, verbose
from reprlib import repr as r # Don't shadow builtin repr
from reprlib import Repr
from reprlib import recursive_repr
def nestedTuple(nesting):
t = ()
for i in range(nesting):
t = (t,)
return t
class ReprTests(unittest.TestCase):
def test_string(self):
eq = self.assertEqual
eq(r("abc"), "'abc'")
eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'")
s = "a"*30+"b"*30
expected = repr(s)[:13] + "..." + repr(s)[-14:]
eq(r(s), expected)
eq(r("\"'"), repr("\"'"))
s = "\""*30+"'"*100
expected = repr(s)[:13] + "..." + repr(s)[-14:]
eq(r(s), expected)
def test_tuple(self):
eq = self.assertEqual
eq(r((1,)), "(1,)")
t3 = (1, 2, 3)
eq(r(t3), "(1, 2, 3)")
r2 = Repr()
r2.maxtuple = 2
expected = repr(t3)[:-2] + "...)"
eq(r2.repr(t3), expected)
def test_container(self):
from array import array
from collections import deque
eq = self.assertEqual
# Tuples give up after 6 elements
eq(r(()), "()")
eq(r((1,)), "(1,)")
eq(r((1, 2, 3)), "(1, 2, 3)")
eq(r((1, 2, 3, 4, 5, 6)), "(1, 2, 3, 4, 5, 6)")
eq(r((1, 2, 3, 4, 5, 6, 7)), "(1, 2, 3, 4, 5, 6, ...)")
# Lists give up after 6 as well
eq(r([]), "[]")
eq(r([1]), "[1]")
eq(r([1, 2, 3]), "[1, 2, 3]")
eq(r([1, 2, 3, 4, 5, 6]), "[1, 2, 3, 4, 5, 6]")
eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]")
# Sets give up after 6 as well
eq(r(set([])), "set()")
eq(r(set([1])), "{1}")
eq(r(set([1, 2, 3])), "{1, 2, 3}")
eq(r(set([1, 2, 3, 4, 5, 6])), "{1, 2, 3, 4, 5, 6}")
eq(r(set([1, 2, 3, 4, 5, 6, 7])), "{1, 2, 3, 4, 5, 6, ...}")
# Frozensets give up after 6 as well
eq(r(frozenset([])), "frozenset()")
eq(r(frozenset([1])), "frozenset({1})")
eq(r(frozenset([1, 2, 3])), "frozenset({1, 2, 3})")
eq(r(frozenset([1, 2, 3, 4, 5, 6])), "frozenset({1, 2, 3, 4, 5, 6})")
eq(r(frozenset([1, 2, 3, 4, 5, 6, 7])), "frozenset({1, 2, 3, 4, 5, 6, ...})")
# collections.deque after 6
eq(r(deque([1, 2, 3, 4, 5, 6, 7])), "deque([1, 2, 3, 4, 5, 6, ...])")
# Dictionaries give up after 4.
eq(r({}), "{}")
d = {'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}
eq(r(d), "{'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}")
d['arthur'] = 1
eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}")
# array.array after 5.
eq(r(array('i')), "array('i')")
eq(r(array('i', [1])), "array('i', [1])")
eq(r(array('i', [1, 2])), "array('i', [1, 2])")
eq(r(array('i', [1, 2, 3])), "array('i', [1, 2, 3])")
eq(r(array('i', [1, 2, 3, 4])), "array('i', [1, 2, 3, 4])")
eq(r(array('i', [1, 2, 3, 4, 5])), "array('i', [1, 2, 3, 4, 5])")
eq(r(array('i', [1, 2, 3, 4, 5, 6])),
"array('i', [1, 2, 3, 4, 5, ...])")
def test_set_literal(self):
eq = self.assertEqual
eq(r({1}), "{1}")
eq(r({1, 2, 3}), "{1, 2, 3}")
eq(r({1, 2, 3, 4, 5, 6}), "{1, 2, 3, 4, 5, 6}")
eq(r({1, 2, 3, 4, 5, 6, 7}), "{1, 2, 3, 4, 5, 6, ...}")
def test_frozenset(self):
eq = self.assertEqual
eq(r(frozenset({1})), "frozenset({1})")
eq(r(frozenset({1, 2, 3})), "frozenset({1, 2, 3})")
eq(r(frozenset({1, 2, 3, 4, 5, 6})), "frozenset({1, 2, 3, 4, 5, 6})")
eq(r(frozenset({1, 2, 3, 4, 5, 6, 7})), "frozenset({1, 2, 3, 4, 5, 6, ...})")
def test_numbers(self):
eq = self.assertEqual
eq(r(123), repr(123))
eq(r(123), repr(123))
eq(r(1.0/3), repr(1.0/3))
n = 10**100
expected = repr(n)[:18] + "..." + repr(n)[-19:]
eq(r(n), expected)
def test_instance(self):
eq = self.assertEqual
i1 = ClassWithRepr("a")
eq(r(i1), repr(i1))
i2 = ClassWithRepr("x"*1000)
expected = repr(i2)[:13] + "..." + repr(i2)[-14:]
eq(r(i2), expected)
i3 = ClassWithFailingRepr()
eq(r(i3), ("<ClassWithFailingRepr instance at %#x>"%id(i3)))
s = r(ClassWithFailingRepr)
self.assertTrue(s.startswith("<class "))
self.assertTrue(s.endswith(">"))
self.assertIn(s.find("..."), [12, 13])
def test_lambda(self):
r = repr(lambda x: x)
self.assertTrue(r.startswith("<function ReprTests.test_lambda.<locals>.<lambda"), r)
# XXX anonymous functions? see func_repr
def test_builtin_function(self):
eq = self.assertEqual
# Functions
eq(repr(hash), '<built-in function hash>')
# Methods
self.assertTrue(repr(''.split).startswith(
'<built-in method split of str object at 0x'))
def test_range(self):
eq = self.assertEqual
eq(repr(range(1)), 'range(0, 1)')
eq(repr(range(1, 2)), 'range(1, 2)')
eq(repr(range(1, 4, 3)), 'range(1, 4, 3)')
def test_nesting(self):
eq = self.assertEqual
# everything is meant to give up after 6 levels.
eq(r([[[[[[[]]]]]]]), "[[[[[[[]]]]]]]")
eq(r([[[[[[[[]]]]]]]]), "[[[[[[[...]]]]]]]")
eq(r(nestedTuple(6)), "(((((((),),),),),),)")
eq(r(nestedTuple(7)), "(((((((...),),),),),),)")
eq(r({ nestedTuple(5) : nestedTuple(5) }),
"{((((((),),),),),): ((((((),),),),),)}")
eq(r({ nestedTuple(6) : nestedTuple(6) }),
"{((((((...),),),),),): ((((((...),),),),),)}")
eq(r([[[[[[{}]]]]]]), "[[[[[[{}]]]]]]")
eq(r([[[[[[[{}]]]]]]]), "[[[[[[[...]]]]]]]")
def test_cell(self):
def get_cell():
x = 42
def inner():
return x
return inner
x = get_cell().__closure__[0]
self.assertRegex(repr(x), r'<cell at 0x[0-9A-Fa-f]+: '
r'int object at 0x[0-9A-Fa-f]+>')
self.assertRegex(r(x), r'<cell at 0x.*\.\.\..*>')
def test_descriptors(self):
eq = self.assertEqual
# method descriptors
eq(repr(dict.items), "<method 'items' of 'dict' objects>")
# XXX member descriptors
# XXX attribute descriptors
# XXX slot descriptors
# static and class methods
class C:
def foo(cls): pass
x = staticmethod(C.foo)
self.assertTrue(repr(x).startswith('<staticmethod object at 0x'))
x = classmethod(C.foo)
self.assertTrue(repr(x).startswith('<classmethod object at 0x'))
def test_unsortable(self):
# Repr.repr() used to call sorted() on sets, frozensets and dicts
# without taking into account that not all objects are comparable
x = set([1j, 2j, 3j])
y = frozenset(x)
z = {1j: 1, 2j: 2}
r(x)
r(y)
r(z)
def write_file(path, text):
with open(path, 'w', encoding='ASCII') as fp:
fp.write(text)
class LongReprTest(unittest.TestCase):
longname = 'areallylongpackageandmodulenametotestreprtruncation'
def setUp(self):
self.pkgname = os.path.join(self.longname)
self.subpkgname = os.path.join(self.longname, self.longname)
# Make the package and subpackage
shutil.rmtree(self.pkgname, ignore_errors=True)
os.mkdir(self.pkgname)
create_empty_file(os.path.join(self.pkgname, '__init__.py'))
shutil.rmtree(self.subpkgname, ignore_errors=True)
os.mkdir(self.subpkgname)
create_empty_file(os.path.join(self.subpkgname, '__init__.py'))
# Remember where we are
self.here = os.getcwd()
sys.path.insert(0, self.here)
# When regrtest is run with its -j option, this command alone is not
# enough.
importlib.invalidate_caches()
def tearDown(self):
actions = []
for dirpath, dirnames, filenames in os.walk(self.pkgname):
for name in dirnames + filenames:
actions.append(os.path.join(dirpath, name))
actions.append(self.pkgname)
actions.sort()
actions.reverse()
for p in actions:
if os.path.isdir(p):
os.rmdir(p)
else:
os.remove(p)
del sys.path[0]
def _check_path_limitations(self, module_name):
# base directory
source_path_len = len(self.here)
# a path separator + `longname` (twice)
source_path_len += 2 * (len(self.longname) + 1)
# a path separator + `module_name` + ".py"
source_path_len += len(module_name) + 1 + len(".py")
cached_path_len = (source_path_len +
len(importlib.util.cache_from_source("x.py")) - len("x.py"))
if os.name == 'nt' and cached_path_len >= 258:
# Under Windows, the max path len is 260 including C's terminating
# NUL character.
# (see http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx#maxpath)
self.skipTest("test paths too long (%d characters) for Windows' 260 character limit"
% cached_path_len)
elif os.name == 'nt' and verbose:
print("cached_path_len =", cached_path_len)
# def test_module(self):
# self.maxDiff = None
# self._check_path_limitations(self.pkgname)
# create_empty_file(os.path.join(self.subpkgname, self.pkgname + '.py'))
# importlib.invalidate_caches()
# from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation
# module = areallylongpackageandmodulenametotestreprtruncation
# self.assertEqual(repr(module), "<module %r from %r>" % (module.__name__, module.__file__))
# self.assertEqual(repr(sys), "<module 'sys' (built-in)>")
# def test_type(self):
# self._check_path_limitations('foo')
# eq = self.assertEqual
# write_file(os.path.join(self.subpkgname, 'foo.py'), '''\
# class foo(object):
# pass
# ''')
# importlib.invalidate_caches()
# from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import foo
# eq(repr(foo.foo),
# "<class '%s.foo'>" % foo.__name__)
# @unittest.skip('need a suitable object')
# def test_object(self):
# # XXX Test the repr of a type with a really long tp_name but with no
# # tp_repr. WIBNI we had ::Inline? :)
# pass
# def test_class(self):
# self._check_path_limitations('bar')
# write_file(os.path.join(self.subpkgname, 'bar.py'), '''\
# class bar:
# pass
# ''')
# importlib.invalidate_caches()
# from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar
# # Module name may be prefixed with "test.", depending on how run.
# self.assertEqual(repr(bar.bar), "<class '%s.bar'>" % bar.__name__)
# def test_instance(self):
# self._check_path_limitations('baz')
# write_file(os.path.join(self.subpkgname, 'baz.py'), '''\
# class baz:
# pass
# ''')
# importlib.invalidate_caches()
# from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz
# ibaz = baz.baz()
# self.assertTrue(repr(ibaz).startswith(
# "<%s.baz object at 0x" % baz.__name__))
# def test_method(self):
# self._check_path_limitations('qux')
# eq = self.assertEqual
# write_file(os.path.join(self.subpkgname, 'qux.py'), '''\
# class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:
# def amethod(self): pass
# ''')
# importlib.invalidate_caches()
# from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import qux
# # Unbound methods first
# r = repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod)
# self.assertTrue(r.startswith('<function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod'), r)
# # Bound method next
# iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
# r = repr(iqux.amethod)
# self.assertTrue(r.startswith(
# '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa object at 0x' \
# % (qux.__name__,) ), r)
@unittest.skip('needs a built-in function with a really long name')
def test_builtin_function(self):
# XXX test built-in functions and methods with really long names
pass
class ClassWithRepr:
def __init__(self, s):
self.s = s
def __repr__(self):
return "ClassWithRepr(%r)" % self.s
class ClassWithFailingRepr:
def __repr__(self):
raise Exception("This should be caught by Repr.repr_instance")
class MyContainer:
'Helper class for TestRecursiveRepr'
def __init__(self, values):
self.values = list(values)
def append(self, value):
self.values.append(value)
@recursive_repr()
def __repr__(self):
return '<' + ', '.join(map(str, self.values)) + '>'
class MyContainer2(MyContainer):
@recursive_repr('+++')
def __repr__(self):
return '<' + ', '.join(map(str, self.values)) + '>'
class MyContainer3:
def __repr__(self):
'Test document content'
pass
wrapped = __repr__
wrapper = recursive_repr()(wrapped)
class TestRecursiveRepr(unittest.TestCase):
def test_recursive_repr(self):
m = MyContainer(list('abcde'))
m.append(m)
m.append('x')
m.append(m)
self.assertEqual(repr(m), '<a, b, c, d, e, ..., x, ...>')
m = MyContainer2(list('abcde'))
m.append(m)
m.append('x')
m.append(m)
self.assertEqual(repr(m), '<a, b, c, d, e, +++, x, +++>')
def test_assigned_attributes(self):
from functools import WRAPPER_ASSIGNMENTS as assigned
wrapped = MyContainer3.wrapped
wrapper = MyContainer3.wrapper
for name in assigned:
self.assertIs(getattr(wrapper, name), getattr(wrapped, name))
if __name__ == "__main__":
unittest.main()
| 15,606 | 406 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_logging.py | # Copyright 2001-2017 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of Vinay Sajip
# not be used in advertising or publicity pertaining to distribution
# of the software without specific, written prior permission.
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""Test harness for the logging module. Run all tests.
Copyright (C) 2001-2017 Vinay Sajip. All Rights Reserved.
"""
import logging
import logging.handlers
import logging.config
import codecs
import configparser
import datetime
import pathlib
import pickle
import io
import gc
import json
import os
import queue
import random
import re
import socket
import struct
import sys
import cosmo
import tempfile
from test.support.script_helper import assert_python_ok
from test import support
import textwrap
import time
import unittest
import warnings
import weakref
try:
import _thread
import threading
# The following imports are needed only for tests which
# require threading
import asyncore
from http.server import HTTPServer, BaseHTTPRequestHandler
import smtpd
from urllib.parse import urlparse, parse_qs
from socketserver import (ThreadingUDPServer, DatagramRequestHandler,
ThreadingTCPServer, StreamRequestHandler)
except ImportError:
threading = None
try:
import win32evtlog, win32evtlogutil, pywintypes
except ImportError:
win32evtlog = win32evtlogutil = pywintypes = None
try:
import zlib
except ImportError:
pass
class BaseTest(unittest.TestCase):
"""Base class for logging tests."""
log_format = "%(name)s -> %(levelname)s: %(message)s"
expected_log_pat = r"^([\w.]+) -> (\w+): (\d+)$"
message_num = 0
def setUp(self):
"""Setup the default logging stream to an internal StringIO instance,
so that we can examine log output as we want."""
logger_dict = logging.getLogger().manager.loggerDict
logging._acquireLock()
try:
self.saved_handlers = logging._handlers.copy()
self.saved_handler_list = logging._handlerList[:]
self.saved_loggers = saved_loggers = logger_dict.copy()
self.saved_name_to_level = logging._nameToLevel.copy()
self.saved_level_to_name = logging._levelToName.copy()
self.logger_states = logger_states = {}
for name in saved_loggers:
logger_states[name] = getattr(saved_loggers[name],
'disabled', None)
finally:
logging._releaseLock()
# Set two unused loggers
self.logger1 = logging.getLogger("\xab\xd7\xbb")
self.logger2 = logging.getLogger("\u013f\u00d6\u0047")
self.root_logger = logging.getLogger("")
self.original_logging_level = self.root_logger.getEffectiveLevel()
self.stream = io.StringIO()
self.root_logger.setLevel(logging.DEBUG)
self.root_hdlr = logging.StreamHandler(self.stream)
self.root_formatter = logging.Formatter(self.log_format)
self.root_hdlr.setFormatter(self.root_formatter)
if self.logger1.hasHandlers():
hlist = self.logger1.handlers + self.root_logger.handlers
raise AssertionError('Unexpected handlers: %s' % hlist)
if self.logger2.hasHandlers():
hlist = self.logger2.handlers + self.root_logger.handlers
raise AssertionError('Unexpected handlers: %s' % hlist)
self.root_logger.addHandler(self.root_hdlr)
self.assertTrue(self.logger1.hasHandlers())
self.assertTrue(self.logger2.hasHandlers())
def tearDown(self):
"""Remove our logging stream, and restore the original logging
level."""
self.stream.close()
self.root_logger.removeHandler(self.root_hdlr)
while self.root_logger.handlers:
h = self.root_logger.handlers[0]
self.root_logger.removeHandler(h)
h.close()
self.root_logger.setLevel(self.original_logging_level)
logging._acquireLock()
try:
logging._levelToName.clear()
logging._levelToName.update(self.saved_level_to_name)
logging._nameToLevel.clear()
logging._nameToLevel.update(self.saved_name_to_level)
logging._handlers.clear()
logging._handlers.update(self.saved_handlers)
logging._handlerList[:] = self.saved_handler_list
loggerDict = logging.getLogger().manager.loggerDict
loggerDict.clear()
loggerDict.update(self.saved_loggers)
logger_states = self.logger_states
for name in self.logger_states:
if logger_states[name] is not None:
self.saved_loggers[name].disabled = logger_states[name]
finally:
logging._releaseLock()
def assert_log_lines(self, expected_values, stream=None, pat=None):
"""Match the collected log lines against the regular expression
self.expected_log_pat, and compare the extracted group values to
the expected_values list of tuples."""
stream = stream or self.stream
pat = re.compile(pat or self.expected_log_pat)
actual_lines = stream.getvalue().splitlines()
self.assertEqual(len(actual_lines), len(expected_values))
for actual, expected in zip(actual_lines, expected_values):
match = pat.search(actual)
if not match:
self.fail("Log line does not match expected pattern:\n" +
actual)
self.assertEqual(tuple(match.groups()), expected)
s = stream.read()
if s:
self.fail("Remaining output at end of log stream:\n" + s)
def next_message(self):
"""Generate a message consisting solely of an auto-incrementing
integer."""
self.message_num += 1
return "%d" % self.message_num
class BuiltinLevelsTest(BaseTest):
"""Test builtin levels and their inheritance."""
def test_flat(self):
# Logging levels in a flat logger namespace.
m = self.next_message
ERR = logging.getLogger("ERR")
ERR.setLevel(logging.ERROR)
INF = logging.LoggerAdapter(logging.getLogger("INF"), {})
INF.setLevel(logging.INFO)
DEB = logging.getLogger("DEB")
DEB.setLevel(logging.DEBUG)
# These should log.
ERR.log(logging.CRITICAL, m())
ERR.error(m())
INF.log(logging.CRITICAL, m())
INF.error(m())
INF.warning(m())
INF.info(m())
DEB.log(logging.CRITICAL, m())
DEB.error(m())
DEB.warning(m())
DEB.info(m())
DEB.debug(m())
# These should not log.
ERR.warning(m())
ERR.info(m())
ERR.debug(m())
INF.debug(m())
self.assert_log_lines([
('ERR', 'CRITICAL', '1'),
('ERR', 'ERROR', '2'),
('INF', 'CRITICAL', '3'),
('INF', 'ERROR', '4'),
('INF', 'WARNING', '5'),
('INF', 'INFO', '6'),
('DEB', 'CRITICAL', '7'),
('DEB', 'ERROR', '8'),
('DEB', 'WARNING', '9'),
('DEB', 'INFO', '10'),
('DEB', 'DEBUG', '11'),
])
def test_nested_explicit(self):
# Logging levels in a nested namespace, all explicitly set.
m = self.next_message
INF = logging.getLogger("INF")
INF.setLevel(logging.INFO)
INF_ERR = logging.getLogger("INF.ERR")
INF_ERR.setLevel(logging.ERROR)
# These should log.
INF_ERR.log(logging.CRITICAL, m())
INF_ERR.error(m())
# These should not log.
INF_ERR.warning(m())
INF_ERR.info(m())
INF_ERR.debug(m())
self.assert_log_lines([
('INF.ERR', 'CRITICAL', '1'),
('INF.ERR', 'ERROR', '2'),
])
def test_nested_inherited(self):
# Logging levels in a nested namespace, inherited from parent loggers.
m = self.next_message
INF = logging.getLogger("INF")
INF.setLevel(logging.INFO)
INF_ERR = logging.getLogger("INF.ERR")
INF_ERR.setLevel(logging.ERROR)
INF_UNDEF = logging.getLogger("INF.UNDEF")
INF_ERR_UNDEF = logging.getLogger("INF.ERR.UNDEF")
UNDEF = logging.getLogger("UNDEF")
# These should log.
INF_UNDEF.log(logging.CRITICAL, m())
INF_UNDEF.error(m())
INF_UNDEF.warning(m())
INF_UNDEF.info(m())
INF_ERR_UNDEF.log(logging.CRITICAL, m())
INF_ERR_UNDEF.error(m())
# These should not log.
INF_UNDEF.debug(m())
INF_ERR_UNDEF.warning(m())
INF_ERR_UNDEF.info(m())
INF_ERR_UNDEF.debug(m())
self.assert_log_lines([
('INF.UNDEF', 'CRITICAL', '1'),
('INF.UNDEF', 'ERROR', '2'),
('INF.UNDEF', 'WARNING', '3'),
('INF.UNDEF', 'INFO', '4'),
('INF.ERR.UNDEF', 'CRITICAL', '5'),
('INF.ERR.UNDEF', 'ERROR', '6'),
])
def test_nested_with_virtual_parent(self):
# Logging levels when some parent does not exist yet.
m = self.next_message
INF = logging.getLogger("INF")
GRANDCHILD = logging.getLogger("INF.BADPARENT.UNDEF")
CHILD = logging.getLogger("INF.BADPARENT")
INF.setLevel(logging.INFO)
# These should log.
GRANDCHILD.log(logging.FATAL, m())
GRANDCHILD.info(m())
CHILD.log(logging.FATAL, m())
CHILD.info(m())
# These should not log.
GRANDCHILD.debug(m())
CHILD.debug(m())
self.assert_log_lines([
('INF.BADPARENT.UNDEF', 'CRITICAL', '1'),
('INF.BADPARENT.UNDEF', 'INFO', '2'),
('INF.BADPARENT', 'CRITICAL', '3'),
('INF.BADPARENT', 'INFO', '4'),
])
def test_regression_22386(self):
"""See issue #22386 for more information."""
self.assertEqual(logging.getLevelName('INFO'), logging.INFO)
self.assertEqual(logging.getLevelName(logging.INFO), 'INFO')
def test_issue27935(self):
fatal = logging.getLevelName('FATAL')
self.assertEqual(fatal, logging.FATAL)
def test_regression_29220(self):
"""See issue #29220 for more information."""
logging.addLevelName(logging.INFO, '')
self.addCleanup(logging.addLevelName, logging.INFO, 'INFO')
self.assertEqual(logging.getLevelName(logging.INFO), '')
self.assertEqual(logging.getLevelName(logging.NOTSET), 'NOTSET')
self.assertEqual(logging.getLevelName('NOTSET'), logging.NOTSET)
class BasicFilterTest(BaseTest):
"""Test the bundled Filter class."""
def test_filter(self):
# Only messages satisfying the specified criteria pass through the
# filter.
filter_ = logging.Filter("spam.eggs")
handler = self.root_logger.handlers[0]
try:
handler.addFilter(filter_)
spam = logging.getLogger("spam")
spam_eggs = logging.getLogger("spam.eggs")
spam_eggs_fish = logging.getLogger("spam.eggs.fish")
spam_bakedbeans = logging.getLogger("spam.bakedbeans")
spam.info(self.next_message())
spam_eggs.info(self.next_message()) # Good.
spam_eggs_fish.info(self.next_message()) # Good.
spam_bakedbeans.info(self.next_message())
self.assert_log_lines([
('spam.eggs', 'INFO', '2'),
('spam.eggs.fish', 'INFO', '3'),
])
finally:
handler.removeFilter(filter_)
def test_callable_filter(self):
# Only messages satisfying the specified criteria pass through the
# filter.
def filterfunc(record):
parts = record.name.split('.')
prefix = '.'.join(parts[:2])
return prefix == 'spam.eggs'
handler = self.root_logger.handlers[0]
try:
handler.addFilter(filterfunc)
spam = logging.getLogger("spam")
spam_eggs = logging.getLogger("spam.eggs")
spam_eggs_fish = logging.getLogger("spam.eggs.fish")
spam_bakedbeans = logging.getLogger("spam.bakedbeans")
spam.info(self.next_message())
spam_eggs.info(self.next_message()) # Good.
spam_eggs_fish.info(self.next_message()) # Good.
spam_bakedbeans.info(self.next_message())
self.assert_log_lines([
('spam.eggs', 'INFO', '2'),
('spam.eggs.fish', 'INFO', '3'),
])
finally:
handler.removeFilter(filterfunc)
def test_empty_filter(self):
f = logging.Filter()
r = logging.makeLogRecord({'name': 'spam.eggs'})
self.assertTrue(f.filter(r))
#
# First, we define our levels. There can be as many as you want - the only
# limitations are that they should be integers, the lowest should be > 0 and
# larger values mean less information being logged. If you need specific
# level values which do not fit into these limitations, you can use a
# mapping dictionary to convert between your application levels and the
# logging system.
#
SILENT = 120
TACITURN = 119
TERSE = 118
EFFUSIVE = 117
SOCIABLE = 116
VERBOSE = 115
TALKATIVE = 114
GARRULOUS = 113
CHATTERBOX = 112
BORING = 111
LEVEL_RANGE = range(BORING, SILENT + 1)
#
# Next, we define names for our levels. You don't need to do this - in which
# case the system will use "Level n" to denote the text for the level.
#
my_logging_levels = {
SILENT : 'Silent',
TACITURN : 'Taciturn',
TERSE : 'Terse',
EFFUSIVE : 'Effusive',
SOCIABLE : 'Sociable',
VERBOSE : 'Verbose',
TALKATIVE : 'Talkative',
GARRULOUS : 'Garrulous',
CHATTERBOX : 'Chatterbox',
BORING : 'Boring',
}
class GarrulousFilter(logging.Filter):
"""A filter which blocks garrulous messages."""
def filter(self, record):
return record.levelno != GARRULOUS
class VerySpecificFilter(logging.Filter):
"""A filter which blocks sociable and taciturn messages."""
def filter(self, record):
return record.levelno not in [SOCIABLE, TACITURN]
class CustomLevelsAndFiltersTest(BaseTest):
"""Test various filtering possibilities with custom logging levels."""
# Skip the logger name group.
expected_log_pat = r"^[\w.]+ -> (\w+): (\d+)$"
def setUp(self):
BaseTest.setUp(self)
for k, v in my_logging_levels.items():
logging.addLevelName(k, v)
def log_at_all_levels(self, logger):
for lvl in LEVEL_RANGE:
logger.log(lvl, self.next_message())
def test_logger_filter(self):
# Filter at logger level.
self.root_logger.setLevel(VERBOSE)
# Levels >= 'Verbose' are good.
self.log_at_all_levels(self.root_logger)
self.assert_log_lines([
('Verbose', '5'),
('Sociable', '6'),
('Effusive', '7'),
('Terse', '8'),
('Taciturn', '9'),
('Silent', '10'),
])
def test_handler_filter(self):
# Filter at handler level.
self.root_logger.handlers[0].setLevel(SOCIABLE)
try:
# Levels >= 'Sociable' are good.
self.log_at_all_levels(self.root_logger)
self.assert_log_lines([
('Sociable', '6'),
('Effusive', '7'),
('Terse', '8'),
('Taciturn', '9'),
('Silent', '10'),
])
finally:
self.root_logger.handlers[0].setLevel(logging.NOTSET)
def test_specific_filters(self):
# Set a specific filter object on the handler, and then add another
# filter object on the logger itself.
handler = self.root_logger.handlers[0]
specific_filter = None
garr = GarrulousFilter()
handler.addFilter(garr)
try:
self.log_at_all_levels(self.root_logger)
first_lines = [
# Notice how 'Garrulous' is missing
('Boring', '1'),
('Chatterbox', '2'),
('Talkative', '4'),
('Verbose', '5'),
('Sociable', '6'),
('Effusive', '7'),
('Terse', '8'),
('Taciturn', '9'),
('Silent', '10'),
]
self.assert_log_lines(first_lines)
specific_filter = VerySpecificFilter()
self.root_logger.addFilter(specific_filter)
self.log_at_all_levels(self.root_logger)
self.assert_log_lines(first_lines + [
# Not only 'Garrulous' is still missing, but also 'Sociable'
# and 'Taciturn'
('Boring', '11'),
('Chatterbox', '12'),
('Talkative', '14'),
('Verbose', '15'),
('Effusive', '17'),
('Terse', '18'),
('Silent', '20'),
])
finally:
if specific_filter:
self.root_logger.removeFilter(specific_filter)
handler.removeFilter(garr)
class HandlerTest(BaseTest):
def test_name(self):
h = logging.Handler()
h.name = 'generic'
self.assertEqual(h.name, 'generic')
h.name = 'anothergeneric'
self.assertEqual(h.name, 'anothergeneric')
self.assertRaises(NotImplementedError, h.emit, None)
def test_builtin_handlers(self):
# We can't actually *use* too many handlers in the tests,
# but we can try instantiating them with various options
if sys.platform in ('linux', 'darwin'):
for existing in (True, False):
fd, fn = tempfile.mkstemp()
os.close(fd)
if not existing:
os.unlink(fn)
h = logging.handlers.WatchedFileHandler(fn, delay=True)
if existing:
dev, ino = h.dev, h.ino
self.assertEqual(dev, -1)
self.assertEqual(ino, -1)
r = logging.makeLogRecord({'msg': 'Test'})
h.handle(r)
# Now remove the file.
os.unlink(fn)
self.assertFalse(os.path.exists(fn))
# The next call should recreate the file.
h.handle(r)
self.assertTrue(os.path.exists(fn))
else:
self.assertEqual(h.dev, -1)
self.assertEqual(h.ino, -1)
h.close()
if existing:
os.unlink(fn)
if sys.platform == 'darwin':
sockname = '/var/run/syslog'
else:
sockname = '/dev/log'
try:
h = logging.handlers.SysLogHandler(sockname)
self.assertEqual(h.facility, h.LOG_USER)
self.assertTrue(h.unixsocket)
h.close()
except OSError: # syslogd might not be available
pass
for method in ('GET', 'POST', 'PUT'):
if method == 'PUT':
self.assertRaises(ValueError, logging.handlers.HTTPHandler,
'localhost', '/log', method)
else:
h = logging.handlers.HTTPHandler('localhost', '/log', method)
h.close()
h = logging.handlers.BufferingHandler(0)
r = logging.makeLogRecord({})
self.assertTrue(h.shouldFlush(r))
h.close()
h = logging.handlers.BufferingHandler(1)
self.assertFalse(h.shouldFlush(r))
h.close()
def test_path_objects(self):
"""
Test that Path objects are accepted as filename arguments to handlers.
See Issue #27493.
"""
fd, fn = tempfile.mkstemp()
os.close(fd)
os.unlink(fn)
pfn = pathlib.Path(fn)
cases = (
(logging.FileHandler, (pfn, 'w')),
(logging.handlers.RotatingFileHandler, (pfn, 'a')),
(logging.handlers.TimedRotatingFileHandler, (pfn, 'h')),
)
if sys.platform in ('linux', 'darwin'):
cases += ((logging.handlers.WatchedFileHandler, (pfn, 'w')),)
for cls, args in cases:
h = cls(*args)
self.assertTrue(os.path.exists(fn))
h.close()
os.unlink(fn)
@unittest.skipIf(os.name == 'nt', 'WatchedFileHandler not appropriate for Windows.')
@unittest.skipUnless(threading, 'Threading required for this test.')
def test_race(self):
# Issue #14632 refers.
def remove_loop(fname, tries):
for _ in range(tries):
try:
os.unlink(fname)
self.deletion_time = time.time()
except OSError:
pass
time.sleep(0.004 * random.randint(0, 4))
del_count = 500
log_count = 500
self.handle_time = None
self.deletion_time = None
for delay in (False, True):
fd, fn = tempfile.mkstemp('.log', 'test_logging-3-')
os.close(fd)
remover = threading.Thread(target=remove_loop, args=(fn, del_count))
remover.daemon = True
remover.start()
h = logging.handlers.WatchedFileHandler(fn, delay=delay)
f = logging.Formatter('%(asctime)s: %(levelname)s: %(message)s')
h.setFormatter(f)
try:
for _ in range(log_count):
time.sleep(0.005)
r = logging.makeLogRecord({'msg': 'testing' })
try:
self.handle_time = time.time()
h.handle(r)
except Exception:
print('Deleted at %s, '
'opened at %s' % (self.deletion_time,
self.handle_time))
raise
finally:
remover.join()
h.close()
if os.path.exists(fn):
os.unlink(fn)
class BadStream(object):
def write(self, data):
raise RuntimeError('deliberate mistake')
class TestStreamHandler(logging.StreamHandler):
def handleError(self, record):
self.error_record = record
class StreamHandlerTest(BaseTest):
def test_error_handling(self):
h = TestStreamHandler(BadStream())
r = logging.makeLogRecord({})
old_raise = logging.raiseExceptions
try:
h.handle(r)
self.assertIs(h.error_record, r)
h = logging.StreamHandler(BadStream())
with support.captured_stderr() as stderr:
h.handle(r)
msg = '\nRuntimeError: deliberate mistake\n'
self.assertIn(msg, stderr.getvalue())
logging.raiseExceptions = False
with support.captured_stderr() as stderr:
h.handle(r)
self.assertEqual('', stderr.getvalue())
finally:
logging.raiseExceptions = old_raise
# -- The following section could be moved into a server_helper.py module
# -- if it proves to be of wider utility than just test_logging
if threading:
class TestSMTPServer(smtpd.SMTPServer):
"""
This class implements a test SMTP server.
:param addr: A (host, port) tuple which the server listens on.
You can specify a port value of zero: the server's
*port* attribute will hold the actual port number
used, which can be used in client connections.
:param handler: A callable which will be called to process
incoming messages. The handler will be passed
the client address tuple, who the message is from,
a list of recipients and the message data.
:param poll_interval: The interval, in seconds, used in the underlying
:func:`select` or :func:`poll` call by
:func:`asyncore.loop`.
:param sockmap: A dictionary which will be used to hold
:class:`asyncore.dispatcher` instances used by
:func:`asyncore.loop`. This avoids changing the
:mod:`asyncore` module's global state.
"""
def __init__(self, addr, handler, poll_interval, sockmap):
smtpd.SMTPServer.__init__(self, addr, None, map=sockmap,
decode_data=True)
self.port = self.socket.getsockname()[1]
self._handler = handler
self._thread = None
self.poll_interval = poll_interval
def process_message(self, peer, mailfrom, rcpttos, data):
"""
Delegates to the handler passed in to the server's constructor.
Typically, this will be a test case method.
:param peer: The client (host, port) tuple.
:param mailfrom: The address of the sender.
:param rcpttos: The addresses of the recipients.
:param data: The message.
"""
self._handler(peer, mailfrom, rcpttos, data)
def start(self):
"""
Start the server running on a separate daemon thread.
"""
self._thread = t = threading.Thread(target=self.serve_forever,
args=(self.poll_interval,))
t.setDaemon(True)
t.start()
def serve_forever(self, poll_interval):
"""
Run the :mod:`asyncore` loop until normal termination
conditions arise.
:param poll_interval: The interval, in seconds, used in the underlying
:func:`select` or :func:`poll` call by
:func:`asyncore.loop`.
"""
try:
asyncore.loop(poll_interval, map=self._map)
except OSError:
# On FreeBSD 8, closing the server repeatably
# raises this error. We swallow it if the
# server has been closed.
if self.connected or self.accepting:
raise
def stop(self, timeout=None):
"""
Stop the thread by closing the server instance.
Wait for the server thread to terminate.
:param timeout: How long to wait for the server thread
to terminate.
"""
self.close()
self._thread.join(timeout)
asyncore.close_all(map=self._map, ignore_all=True)
self._thread = None
class ControlMixin(object):
"""
This mixin is used to start a server on a separate thread, and
shut it down programmatically. Request handling is simplified - instead
of needing to derive a suitable RequestHandler subclass, you just
provide a callable which will be passed each received request to be
processed.
:param handler: A handler callable which will be called with a
single parameter - the request - in order to
process the request. This handler is called on the
server thread, effectively meaning that requests are
processed serially. While not quite Web scale ;-),
this should be fine for testing applications.
:param poll_interval: The polling interval in seconds.
"""
def __init__(self, handler, poll_interval):
self._thread = None
self.poll_interval = poll_interval
self._handler = handler
self.ready = threading.Event()
def start(self):
"""
Create a daemon thread to run the server, and start it.
"""
self._thread = t = threading.Thread(target=self.serve_forever,
args=(self.poll_interval,))
t.setDaemon(True)
t.start()
def serve_forever(self, poll_interval):
"""
Run the server. Set the ready flag before entering the
service loop.
"""
self.ready.set()
super(ControlMixin, self).serve_forever(poll_interval)
def stop(self, timeout=None):
"""
Tell the server thread to stop, and wait for it to do so.
:param timeout: How long to wait for the server thread
to terminate.
"""
self.shutdown()
if self._thread is not None:
self._thread.join(timeout)
self._thread = None
self.server_close()
self.ready.clear()
class TestHTTPServer(ControlMixin, HTTPServer):
"""
An HTTP server which is controllable using :class:`ControlMixin`.
:param addr: A tuple with the IP address and port to listen on.
:param handler: A handler callable which will be called with a
single parameter - the request - in order to
process the request.
:param poll_interval: The polling interval in seconds.
:param log: Pass ``True`` to enable log messages.
"""
def __init__(self, addr, handler, poll_interval=0.5,
log=False, sslctx=None):
class DelegatingHTTPRequestHandler(BaseHTTPRequestHandler):
def __getattr__(self, name, default=None):
if name.startswith('do_'):
return self.process_request
raise AttributeError(name)
def process_request(self):
self.server._handler(self)
def log_message(self, format, *args):
if log:
super(DelegatingHTTPRequestHandler,
self).log_message(format, *args)
HTTPServer.__init__(self, addr, DelegatingHTTPRequestHandler)
ControlMixin.__init__(self, handler, poll_interval)
self.sslctx = sslctx
def get_request(self):
try:
sock, addr = self.socket.accept()
if self.sslctx:
sock = self.sslctx.wrap_socket(sock, server_side=True)
except OSError as e:
# socket errors are silenced by the caller, print them here
sys.stderr.write("Got an error:\n%s\n" % e)
raise
return sock, addr
class TestTCPServer(ControlMixin, ThreadingTCPServer):
"""
A TCP server which is controllable using :class:`ControlMixin`.
:param addr: A tuple with the IP address and port to listen on.
:param handler: A handler callable which will be called with a single
parameter - the request - in order to process the request.
:param poll_interval: The polling interval in seconds.
:bind_and_activate: If True (the default), binds the server and starts it
listening. If False, you need to call
:meth:`server_bind` and :meth:`server_activate` at
some later time before calling :meth:`start`, so that
the server will set up the socket and listen on it.
"""
allow_reuse_address = True
_block_on_close = True
def __init__(self, addr, handler, poll_interval=0.5,
bind_and_activate=True):
class DelegatingTCPRequestHandler(StreamRequestHandler):
def handle(self):
self.server._handler(self)
ThreadingTCPServer.__init__(self, addr, DelegatingTCPRequestHandler,
bind_and_activate)
ControlMixin.__init__(self, handler, poll_interval)
def server_bind(self):
super(TestTCPServer, self).server_bind()
self.port = self.socket.getsockname()[1]
class TestUDPServer(ControlMixin, ThreadingUDPServer):
"""
A UDP server which is controllable using :class:`ControlMixin`.
:param addr: A tuple with the IP address and port to listen on.
:param handler: A handler callable which will be called with a
single parameter - the request - in order to
process the request.
:param poll_interval: The polling interval for shutdown requests,
in seconds.
:bind_and_activate: If True (the default), binds the server and
starts it listening. If False, you need to
call :meth:`server_bind` and
:meth:`server_activate` at some later time
before calling :meth:`start`, so that the server will
set up the socket and listen on it.
"""
_block_on_close = True
def __init__(self, addr, handler, poll_interval=0.5,
bind_and_activate=True):
class DelegatingUDPRequestHandler(DatagramRequestHandler):
def handle(self):
self.server._handler(self)
def finish(self):
data = self.wfile.getvalue()
if data:
try:
super(DelegatingUDPRequestHandler, self).finish()
except OSError:
if not self.server._closed:
raise
ThreadingUDPServer.__init__(self, addr,
DelegatingUDPRequestHandler,
bind_and_activate)
ControlMixin.__init__(self, handler, poll_interval)
self._closed = False
def server_bind(self):
super(TestUDPServer, self).server_bind()
self.port = self.socket.getsockname()[1]
def server_close(self):
super(TestUDPServer, self).server_close()
self._closed = True
if hasattr(socket, "AF_UNIX"):
class TestUnixStreamServer(TestTCPServer):
address_family = socket.AF_UNIX
class TestUnixDatagramServer(TestUDPServer):
address_family = socket.AF_UNIX
# - end of server_helper section
@unittest.skipUnless(threading, 'Threading required for this test.')
class SMTPHandlerTest(BaseTest):
# bpo-14314, bpo-19665, bpo-34092: don't wait forever, timeout of 1 minute
TIMEOUT = 60.0
def test_basic(self):
sockmap = {}
server = TestSMTPServer((support.HOST, 0), self.process_message, 0.001,
sockmap)
server.start()
addr = (support.HOST, server.port)
h = logging.handlers.SMTPHandler(addr, 'me', 'you', 'Log',
timeout=self.TIMEOUT)
self.assertEqual(h.toaddrs, ['you'])
self.messages = []
r = logging.makeLogRecord({'msg': 'Hello \u2713'})
self.handled = threading.Event()
h.handle(r)
self.handled.wait(self.TIMEOUT)
server.stop()
self.assertTrue(self.handled.is_set())
self.assertEqual(len(self.messages), 1)
peer, mailfrom, rcpttos, data = self.messages[0]
self.assertEqual(mailfrom, 'me')
self.assertEqual(rcpttos, ['you'])
self.assertIn('\nSubject: Log\n', data)
self.assertTrue(data.endswith('\n\nHello \u2713'))
h.close()
def process_message(self, *args):
self.messages.append(args)
self.handled.set()
class MemoryHandlerTest(BaseTest):
"""Tests for the MemoryHandler."""
# Do not bother with a logger name group.
expected_log_pat = r"^[\w.]+ -> (\w+): (\d+)$"
def setUp(self):
BaseTest.setUp(self)
self.mem_hdlr = logging.handlers.MemoryHandler(10, logging.WARNING,
self.root_hdlr)
self.mem_logger = logging.getLogger('mem')
self.mem_logger.propagate = 0
self.mem_logger.addHandler(self.mem_hdlr)
def tearDown(self):
self.mem_hdlr.close()
BaseTest.tearDown(self)
def test_flush(self):
# The memory handler flushes to its target handler based on specific
# criteria (message count and message level).
self.mem_logger.debug(self.next_message())
self.assert_log_lines([])
self.mem_logger.info(self.next_message())
self.assert_log_lines([])
# This will flush because the level is >= logging.WARNING
self.mem_logger.warning(self.next_message())
lines = [
('DEBUG', '1'),
('INFO', '2'),
('WARNING', '3'),
]
self.assert_log_lines(lines)
for n in (4, 14):
for i in range(9):
self.mem_logger.debug(self.next_message())
self.assert_log_lines(lines)
# This will flush because it's the 10th message since the last
# flush.
self.mem_logger.debug(self.next_message())
lines = lines + [('DEBUG', str(i)) for i in range(n, n + 10)]
self.assert_log_lines(lines)
self.mem_logger.debug(self.next_message())
self.assert_log_lines(lines)
def test_flush_on_close(self):
"""
Test that the flush-on-close configuration works as expected.
"""
self.mem_logger.debug(self.next_message())
self.assert_log_lines([])
self.mem_logger.info(self.next_message())
self.assert_log_lines([])
self.mem_logger.removeHandler(self.mem_hdlr)
# Default behaviour is to flush on close. Check that it happens.
self.mem_hdlr.close()
lines = [
('DEBUG', '1'),
('INFO', '2'),
]
self.assert_log_lines(lines)
# Now configure for flushing not to be done on close.
self.mem_hdlr = logging.handlers.MemoryHandler(10, logging.WARNING,
self.root_hdlr,
False)
self.mem_logger.addHandler(self.mem_hdlr)
self.mem_logger.debug(self.next_message())
self.assert_log_lines(lines) # no change
self.mem_logger.info(self.next_message())
self.assert_log_lines(lines) # no change
self.mem_logger.removeHandler(self.mem_hdlr)
self.mem_hdlr.close()
# assert that no new lines have been added
self.assert_log_lines(lines) # no change
class ExceptionFormatter(logging.Formatter):
"""A special exception formatter."""
def formatException(self, ei):
return "Got a [%s]" % ei[0].__name__
class ConfigFileTest(BaseTest):
"""Reading logging config from a .ini-style config file."""
check_no_resource_warning = support.check_no_resource_warning
expected_log_pat = r"^(\w+) \+\+ (\w+)$"
# config0 is a standard configuration.
config0 = """
[loggers]
keys=root
[handlers]
keys=hand1
[formatters]
keys=form1
[logger_root]
level=WARNING
handlers=hand1
[handler_hand1]
class=StreamHandler
level=NOTSET
formatter=form1
args=(sys.stdout,)
[formatter_form1]
format=%(levelname)s ++ %(message)s
datefmt=
"""
# config1 adds a little to the standard configuration.
config1 = """
[loggers]
keys=root,parser
[handlers]
keys=hand1
[formatters]
keys=form1
[logger_root]
level=WARNING
handlers=
[logger_parser]
level=DEBUG
handlers=hand1
propagate=1
qualname=compiler.parser
[handler_hand1]
class=StreamHandler
level=NOTSET
formatter=form1
args=(sys.stdout,)
[formatter_form1]
format=%(levelname)s ++ %(message)s
datefmt=
"""
# config1a moves the handler to the root.
config1a = """
[loggers]
keys=root,parser
[handlers]
keys=hand1
[formatters]
keys=form1
[logger_root]
level=WARNING
handlers=hand1
[logger_parser]
level=DEBUG
handlers=
propagate=1
qualname=compiler.parser
[handler_hand1]
class=StreamHandler
level=NOTSET
formatter=form1
args=(sys.stdout,)
[formatter_form1]
format=%(levelname)s ++ %(message)s
datefmt=
"""
# config2 has a subtle configuration error that should be reported
config2 = config1.replace("sys.stdout", "sys.stbout")
# config3 has a less subtle configuration error
config3 = config1.replace("formatter=form1", "formatter=misspelled_name")
# config4 specifies a custom formatter class to be loaded
config4 = """
[loggers]
keys=root
[handlers]
keys=hand1
[formatters]
keys=form1
[logger_root]
level=NOTSET
handlers=hand1
[handler_hand1]
class=StreamHandler
level=NOTSET
formatter=form1
args=(sys.stdout,)
[formatter_form1]
class=""" + __name__ + """.ExceptionFormatter
format=%(levelname)s:%(name)s:%(message)s
datefmt=
"""
# config5 specifies a custom handler class to be loaded
config5 = config1.replace('class=StreamHandler', 'class=logging.StreamHandler')
# config6 uses ', ' delimiters in the handlers and formatters sections
config6 = """
[loggers]
keys=root,parser
[handlers]
keys=hand1, hand2
[formatters]
keys=form1, form2
[logger_root]
level=WARNING
handlers=
[logger_parser]
level=DEBUG
handlers=hand1
propagate=1
qualname=compiler.parser
[handler_hand1]
class=StreamHandler
level=NOTSET
formatter=form1
args=(sys.stdout,)
[handler_hand2]
class=StreamHandler
level=NOTSET
formatter=form1
args=(sys.stderr,)
[formatter_form1]
format=%(levelname)s ++ %(message)s
datefmt=
[formatter_form2]
format=%(message)s
datefmt=
"""
# config7 adds a compiler logger.
config7 = """
[loggers]
keys=root,parser,compiler
[handlers]
keys=hand1
[formatters]
keys=form1
[logger_root]
level=WARNING
handlers=hand1
[logger_compiler]
level=DEBUG
handlers=
propagate=1
qualname=compiler
[logger_parser]
level=DEBUG
handlers=
propagate=1
qualname=compiler.parser
[handler_hand1]
class=StreamHandler
level=NOTSET
formatter=form1
args=(sys.stdout,)
[formatter_form1]
format=%(levelname)s ++ %(message)s
datefmt=
"""
# config 8, check for resource warning
config8 = r"""
[loggers]
keys=root
[handlers]
keys=file
[formatters]
keys=
[logger_root]
level=DEBUG
handlers=file
[handler_file]
class=FileHandler
level=DEBUG
args=("{tempfile}",)
"""
disable_test = """
[loggers]
keys=root
[handlers]
keys=screen
[formatters]
keys=
[logger_root]
level=DEBUG
handlers=screen
[handler_screen]
level=DEBUG
class=StreamHandler
args=(sys.stdout,)
formatter=
"""
def apply_config(self, conf, **kwargs):
file = io.StringIO(textwrap.dedent(conf))
logging.config.fileConfig(file, **kwargs)
def test_config0_ok(self):
# A simple config file which overrides the default settings.
with support.captured_stdout() as output:
self.apply_config(self.config0)
logger = logging.getLogger()
# Won't output anything
logger.info(self.next_message())
# Outputs a message
logger.error(self.next_message())
self.assert_log_lines([
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
def test_config0_using_cp_ok(self):
# A simple config file which overrides the default settings.
with support.captured_stdout() as output:
file = io.StringIO(textwrap.dedent(self.config0))
cp = configparser.ConfigParser()
cp.read_file(file)
logging.config.fileConfig(cp)
logger = logging.getLogger()
# Won't output anything
logger.info(self.next_message())
# Outputs a message
logger.error(self.next_message())
self.assert_log_lines([
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
def test_config1_ok(self, config=config1):
# A config file defining a sub-parser as well.
with support.captured_stdout() as output:
self.apply_config(config)
logger = logging.getLogger("compiler.parser")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '1'),
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
def test_config2_failure(self):
# A simple config file which overrides the default settings.
self.assertRaises(Exception, self.apply_config, self.config2)
def test_config3_failure(self):
# A simple config file which overrides the default settings.
self.assertRaises(Exception, self.apply_config, self.config3)
def test_config4_ok(self):
# A config file specifying a custom formatter class.
with support.captured_stdout() as output:
self.apply_config(self.config4)
logger = logging.getLogger()
try:
raise RuntimeError()
except RuntimeError:
logging.exception("just testing")
sys.stdout.seek(0)
self.assertEqual(output.getvalue(),
"ERROR:root:just testing\nGot a [RuntimeError]\n")
# Original logger output is empty
self.assert_log_lines([])
def test_config5_ok(self):
self.test_config1_ok(config=self.config5)
def test_config6_ok(self):
self.test_config1_ok(config=self.config6)
def test_config7_ok(self):
with support.captured_stdout() as output:
self.apply_config(self.config1a)
logger = logging.getLogger("compiler.parser")
# See issue #11424. compiler-hyphenated sorts
# between compiler and compiler.xyz and this
# was preventing compiler.xyz from being included
# in the child loggers of compiler because of an
# overzealous loop termination condition.
hyphenated = logging.getLogger('compiler-hyphenated')
# All will output a message
logger.info(self.next_message())
logger.error(self.next_message())
hyphenated.critical(self.next_message())
self.assert_log_lines([
('INFO', '1'),
('ERROR', '2'),
('CRITICAL', '3'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
with support.captured_stdout() as output:
self.apply_config(self.config7)
logger = logging.getLogger("compiler.parser")
self.assertFalse(logger.disabled)
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
logger = logging.getLogger("compiler.lexer")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
# Will not appear
hyphenated.critical(self.next_message())
self.assert_log_lines([
('INFO', '4'),
('ERROR', '5'),
('INFO', '6'),
('ERROR', '7'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
def test_config8_ok(self):
def cleanup(h1, fn):
h1.close()
os.remove(fn)
with self.check_no_resource_warning():
fd, fn = tempfile.mkstemp(".log", "test_logging-X-")
os.close(fd)
# Replace single backslash with double backslash in windows
# to avoid unicode error during string formatting
if os.name == "nt":
fn = fn.replace("\\", "\\\\")
config8 = self.config8.format(tempfile=fn)
self.apply_config(config8)
self.apply_config(config8)
handler = logging.root.handlers[0]
self.addCleanup(cleanup, handler, fn)
def test_logger_disabling(self):
self.apply_config(self.disable_test)
logger = logging.getLogger('some_pristine_logger')
self.assertFalse(logger.disabled)
self.apply_config(self.disable_test)
self.assertTrue(logger.disabled)
self.apply_config(self.disable_test, disable_existing_loggers=False)
self.assertFalse(logger.disabled)
@unittest.skipUnless(threading, 'Threading required for this test.')
class SocketHandlerTest(BaseTest):
"""Test for SocketHandler objects."""
if threading:
server_class = TestTCPServer
address = ('localhost', 0)
def setUp(self):
"""Set up a TCP server to receive log messages, and a SocketHandler
pointing to that server's address and port."""
BaseTest.setUp(self)
# Issue #29177: deal with errors that happen during setup
self.server = self.sock_hdlr = self.server_exception = None
try:
self.server = server = self.server_class(self.address,
self.handle_socket, 0.01)
server.start()
# Uncomment next line to test error recovery in setUp()
# raise OSError('dummy error raised')
except OSError as e:
self.server_exception = e
return
server.ready.wait()
hcls = logging.handlers.SocketHandler
if isinstance(server.server_address, tuple):
self.sock_hdlr = hcls('localhost', server.port)
else:
self.sock_hdlr = hcls(server.server_address, None)
self.log_output = ''
self.root_logger.removeHandler(self.root_logger.handlers[0])
self.root_logger.addHandler(self.sock_hdlr)
self.handled = threading.Semaphore(0)
def tearDown(self):
"""Shutdown the TCP server."""
try:
if self.sock_hdlr:
self.root_logger.removeHandler(self.sock_hdlr)
self.sock_hdlr.close()
if self.server:
self.server.stop(2.0)
finally:
BaseTest.tearDown(self)
def handle_socket(self, request):
conn = request.connection
while True:
chunk = conn.recv(4)
if len(chunk) < 4:
break
slen = struct.unpack(">L", chunk)[0]
chunk = conn.recv(slen)
while len(chunk) < slen:
chunk = chunk + conn.recv(slen - len(chunk))
obj = pickle.loads(chunk)
record = logging.makeLogRecord(obj)
self.log_output += record.msg + '\n'
self.handled.release()
def test_output(self):
# The log message sent to the SocketHandler is properly received.
if self.server_exception:
self.skipTest(self.server_exception)
logger = logging.getLogger("tcp")
logger.error("spam")
self.handled.acquire()
logger.debug("eggs")
self.handled.acquire()
self.assertEqual(self.log_output, "spam\neggs\n")
def test_noserver(self):
if self.server_exception:
self.skipTest(self.server_exception)
# Avoid timing-related failures due to SocketHandler's own hard-wired
# one-second timeout on socket.create_connection() (issue #16264).
self.sock_hdlr.retryStart = 2.5
# Kill the server
self.server.stop(2.0)
# The logging call should try to connect, which should fail
try:
raise RuntimeError('Deliberate mistake')
except RuntimeError:
self.root_logger.exception('Never sent')
self.root_logger.error('Never sent, either')
now = time.time()
self.assertGreater(self.sock_hdlr.retryTime, now)
time.sleep(self.sock_hdlr.retryTime - now + 0.001)
self.root_logger.error('Nor this')
def _get_temp_domain_socket():
fd, fn = tempfile.mkstemp(prefix='test_logging_', suffix='.sock')
os.close(fd)
# just need a name - file can't be present, or we'll get an
# 'address already in use' error.
os.remove(fn)
return fn
@unittest.skipUnless(hasattr(socket, "AF_UNIX"), "Unix sockets required")
@unittest.skipUnless(threading, 'Threading required for this test.')
class UnixSocketHandlerTest(SocketHandlerTest):
"""Test for SocketHandler with unix sockets."""
if threading and hasattr(socket, "AF_UNIX"):
server_class = TestUnixStreamServer
def setUp(self):
# override the definition in the base class
self.address = _get_temp_domain_socket()
SocketHandlerTest.setUp(self)
def tearDown(self):
SocketHandlerTest.tearDown(self)
support.unlink(self.address)
@unittest.skipUnless(threading, 'Threading required for this test.')
class DatagramHandlerTest(BaseTest):
"""Test for DatagramHandler."""
if threading:
server_class = TestUDPServer
address = ('localhost', 0)
def setUp(self):
"""Set up a UDP server to receive log messages, and a DatagramHandler
pointing to that server's address and port."""
BaseTest.setUp(self)
# Issue #29177: deal with errors that happen during setup
self.server = self.sock_hdlr = self.server_exception = None
try:
self.server = server = self.server_class(self.address,
self.handle_datagram, 0.01)
server.start()
# Uncomment next line to test error recovery in setUp()
# raise OSError('dummy error raised')
except OSError as e:
self.server_exception = e
return
server.ready.wait()
hcls = logging.handlers.DatagramHandler
if isinstance(server.server_address, tuple):
self.sock_hdlr = hcls('localhost', server.port)
else:
self.sock_hdlr = hcls(server.server_address, None)
self.log_output = ''
self.root_logger.removeHandler(self.root_logger.handlers[0])
self.root_logger.addHandler(self.sock_hdlr)
self.handled = threading.Event()
def tearDown(self):
"""Shutdown the UDP server."""
try:
if self.server:
self.server.stop(2.0)
if self.sock_hdlr:
self.root_logger.removeHandler(self.sock_hdlr)
self.sock_hdlr.close()
finally:
BaseTest.tearDown(self)
def handle_datagram(self, request):
slen = struct.pack('>L', 0) # length of prefix
packet = request.packet[len(slen):]
obj = pickle.loads(packet)
record = logging.makeLogRecord(obj)
self.log_output += record.msg + '\n'
self.handled.set()
def test_output(self):
# The log message sent to the DatagramHandler is properly received.
if self.server_exception:
self.skipTest(self.server_exception)
logger = logging.getLogger("udp")
logger.error("spam")
self.handled.wait()
self.handled.clear()
logger.error("eggs")
self.handled.wait()
self.assertEqual(self.log_output, "spam\neggs\n")
@unittest.skipUnless(hasattr(socket, "AF_UNIX"), "Unix sockets required")
@unittest.skipUnless(threading, 'Threading required for this test.')
class UnixDatagramHandlerTest(DatagramHandlerTest):
"""Test for DatagramHandler using Unix sockets."""
if threading and hasattr(socket, "AF_UNIX"):
server_class = TestUnixDatagramServer
def setUp(self):
# override the definition in the base class
self.address = _get_temp_domain_socket()
DatagramHandlerTest.setUp(self)
def tearDown(self):
DatagramHandlerTest.tearDown(self)
support.unlink(self.address)
@unittest.skipUnless(threading, 'Threading required for this test.')
class SysLogHandlerTest(BaseTest):
"""Test for SysLogHandler using UDP."""
if threading:
server_class = TestUDPServer
address = ('localhost', 0)
def setUp(self):
"""Set up a UDP server to receive log messages, and a SysLogHandler
pointing to that server's address and port."""
BaseTest.setUp(self)
# Issue #29177: deal with errors that happen during setup
self.server = self.sl_hdlr = self.server_exception = None
try:
self.server = server = self.server_class(self.address,
self.handle_datagram, 0.01)
server.start()
# Uncomment next line to test error recovery in setUp()
# raise OSError('dummy error raised')
except OSError as e:
self.server_exception = e
return
server.ready.wait()
hcls = logging.handlers.SysLogHandler
if isinstance(server.server_address, tuple):
self.sl_hdlr = hcls((server.server_address[0], server.port))
else:
self.sl_hdlr = hcls(server.server_address)
self.log_output = ''
self.root_logger.removeHandler(self.root_logger.handlers[0])
self.root_logger.addHandler(self.sl_hdlr)
self.handled = threading.Event()
def tearDown(self):
"""Shutdown the server."""
try:
if self.server:
self.server.stop(2.0)
if self.sl_hdlr:
self.root_logger.removeHandler(self.sl_hdlr)
self.sl_hdlr.close()
finally:
BaseTest.tearDown(self)
def handle_datagram(self, request):
self.log_output = request.packet
self.handled.set()
def test_output(self):
if self.server_exception:
self.skipTest(self.server_exception)
# The log message sent to the SysLogHandler is properly received.
logger = logging.getLogger("slh")
logger.error("sp\xe4m")
self.handled.wait()
self.assertEqual(self.log_output, b'<11>sp\xc3\xa4m\x00')
self.handled.clear()
self.sl_hdlr.append_nul = False
logger.error("sp\xe4m")
self.handled.wait()
self.assertEqual(self.log_output, b'<11>sp\xc3\xa4m')
self.handled.clear()
self.sl_hdlr.ident = "h\xe4m-"
logger.error("sp\xe4m")
self.handled.wait()
self.assertEqual(self.log_output, b'<11>h\xc3\xa4m-sp\xc3\xa4m')
@unittest.skipUnless(hasattr(socket, "AF_UNIX"), "Unix sockets required")
@unittest.skipUnless(threading, 'Threading required for this test.')
class UnixSysLogHandlerTest(SysLogHandlerTest):
"""Test for SysLogHandler with Unix sockets."""
if threading and hasattr(socket, "AF_UNIX"):
server_class = TestUnixDatagramServer
def setUp(self):
# override the definition in the base class
self.address = _get_temp_domain_socket()
SysLogHandlerTest.setUp(self)
def tearDown(self):
SysLogHandlerTest.tearDown(self)
support.unlink(self.address)
@unittest.skipUnless(support.IPV6_ENABLED,
'IPv6 support required for this test.')
@unittest.skipUnless(threading, 'Threading required for this test.')
class IPv6SysLogHandlerTest(SysLogHandlerTest):
"""Test for SysLogHandler with IPv6 host."""
server_class = None # TestUDPServer
address = ('::1', 0)
def setUp(self):
self.server_class.address_family = socket.AF_INET6
super(IPv6SysLogHandlerTest, self).setUp()
def tearDown(self):
self.server_class.address_family = socket.AF_INET
super(IPv6SysLogHandlerTest, self).tearDown()
@unittest.skipUnless(threading, 'Threading required for this test.')
class HTTPHandlerTest(BaseTest):
"""Test for HTTPHandler."""
def setUp(self):
"""Set up an HTTP server to receive log messages, and a HTTPHandler
pointing to that server's address and port."""
BaseTest.setUp(self)
self.handled = threading.Event()
def handle_request(self, request):
self.command = request.command
self.log_data = urlparse(request.path)
if self.command == 'POST':
try:
rlen = int(request.headers['Content-Length'])
self.post_data = request.rfile.read(rlen)
except:
self.post_data = None
request.send_response(200)
request.end_headers()
self.handled.set()
def test_output(self):
# The log message sent to the HTTPHandler is properly received.
logger = logging.getLogger("http")
root_logger = self.root_logger
root_logger.removeHandler(self.root_logger.handlers[0])
for secure in (False, True):
addr = ('localhost', 0)
if secure:
try:
import ssl
except ImportError:
sslctx = None
else:
here = os.path.dirname(__file__)
localhost_cert = os.path.join(here, "keycert.pem")
sslctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
sslctx.load_cert_chain(localhost_cert)
context = ssl.create_default_context(cafile=localhost_cert)
else:
sslctx = None
context = None
self.server = server = TestHTTPServer(addr, self.handle_request,
0.01, sslctx=sslctx)
server.start()
server.ready.wait()
host = 'localhost:%d' % server.server_port
secure_client = secure and sslctx
self.h_hdlr = logging.handlers.HTTPHandler(host, '/frob',
secure=secure_client,
context=context,
credentials=('foo', 'bar'))
self.log_data = None
root_logger.addHandler(self.h_hdlr)
for method in ('GET', 'POST'):
self.h_hdlr.method = method
self.handled.clear()
msg = "sp\xe4m"
logger.error(msg)
self.handled.wait()
self.assertEqual(self.log_data.path, '/frob')
self.assertEqual(self.command, method)
if method == 'GET':
d = parse_qs(self.log_data.query)
else:
d = parse_qs(self.post_data.decode('utf-8'))
self.assertEqual(d['name'], ['http'])
self.assertEqual(d['funcName'], ['test_output'])
self.assertEqual(d['msg'], [msg])
self.server.stop(2.0)
self.root_logger.removeHandler(self.h_hdlr)
self.h_hdlr.close()
class MemoryTest(BaseTest):
"""Test memory persistence of logger objects."""
def setUp(self):
"""Create a dict to remember potentially destroyed objects."""
BaseTest.setUp(self)
self._survivors = {}
def _watch_for_survival(self, *args):
"""Watch the given objects for survival, by creating weakrefs to
them."""
for obj in args:
key = id(obj), repr(obj)
self._survivors[key] = weakref.ref(obj)
def _assertTruesurvival(self):
"""Assert that all objects watched for survival have survived."""
# Trigger cycle breaking.
gc.collect()
dead = []
for (id_, repr_), ref in self._survivors.items():
if ref() is None:
dead.append(repr_)
if dead:
self.fail("%d objects should have survived "
"but have been destroyed: %s" % (len(dead), ", ".join(dead)))
def test_persistent_loggers(self):
# Logger objects are persistent and retain their configuration, even
# if visible references are destroyed.
self.root_logger.setLevel(logging.INFO)
foo = logging.getLogger("foo")
self._watch_for_survival(foo)
foo.setLevel(logging.DEBUG)
self.root_logger.debug(self.next_message())
foo.debug(self.next_message())
self.assert_log_lines([
('foo', 'DEBUG', '2'),
])
del foo
# foo has survived.
self._assertTruesurvival()
# foo has retained its settings.
bar = logging.getLogger("foo")
bar.debug(self.next_message())
self.assert_log_lines([
('foo', 'DEBUG', '2'),
('foo', 'DEBUG', '3'),
])
class EncodingTest(BaseTest):
def test_encoding_plain_file(self):
# In Python 2.x, a plain file object is treated as having no encoding.
log = logging.getLogger("test")
fd, fn = tempfile.mkstemp(".log", "test_logging-1-")
os.close(fd)
# the non-ascii data we write to the log.
data = "foo\x80"
try:
handler = logging.FileHandler(fn, encoding="utf-8")
log.addHandler(handler)
try:
# write non-ascii data to the log.
log.warning(data)
finally:
log.removeHandler(handler)
handler.close()
# check we wrote exactly those bytes, ignoring trailing \n etc
f = open(fn, encoding="utf-8")
try:
self.assertEqual(f.read().rstrip(), data)
finally:
f.close()
finally:
if os.path.isfile(fn):
os.remove(fn)
def test_encoding_cyrillic_unicode(self):
log = logging.getLogger("test")
# Get a message in Unicode: Do svidanya in Cyrillic (meaning goodbye)
message = '\u0434\u043e \u0441\u0432\u0438\u0434\u0430\u043d\u0438\u044f'
# Ensure it's written in a Cyrillic encoding
writer_class = codecs.getwriter('cp1251')
writer_class.encoding = 'cp1251'
stream = io.BytesIO()
writer = writer_class(stream, 'strict')
handler = logging.StreamHandler(writer)
log.addHandler(handler)
try:
log.warning(message)
finally:
log.removeHandler(handler)
handler.close()
# check we wrote exactly those bytes, ignoring trailing \n etc
s = stream.getvalue()
# Compare against what the data should be when encoded in CP-1251
self.assertEqual(s, b'\xe4\xee \xf1\xe2\xe8\xe4\xe0\xed\xe8\xff\n')
class WarningsTest(BaseTest):
def test_warnings(self):
with warnings.catch_warnings():
logging.captureWarnings(True)
self.addCleanup(logging.captureWarnings, False)
warnings.filterwarnings("always", category=UserWarning)
stream = io.StringIO()
h = logging.StreamHandler(stream)
logger = logging.getLogger("py.warnings")
logger.addHandler(h)
warnings.warn("I'm warning you...")
logger.removeHandler(h)
s = stream.getvalue()
h.close()
self.assertGreater(s.find("UserWarning: I'm warning you...\n"), 0)
# See if an explicit file uses the original implementation
a_file = io.StringIO()
warnings.showwarning("Explicit", UserWarning, "dummy.py", 42,
a_file, "Dummy line")
s = a_file.getvalue()
a_file.close()
self.assertEqual(s,
"dummy.py:42: UserWarning: Explicit\n Dummy line\n")
def test_warnings_no_handlers(self):
with warnings.catch_warnings():
logging.captureWarnings(True)
self.addCleanup(logging.captureWarnings, False)
# confirm our assumption: no loggers are set
logger = logging.getLogger("py.warnings")
self.assertEqual(logger.handlers, [])
warnings.showwarning("Explicit", UserWarning, "dummy.py", 42)
self.assertEqual(len(logger.handlers), 1)
self.assertIsInstance(logger.handlers[0], logging.NullHandler)
def formatFunc(format, datefmt=None):
return logging.Formatter(format, datefmt)
def handlerFunc():
return logging.StreamHandler()
class CustomHandler(logging.StreamHandler):
pass
class ConfigDictTest(BaseTest):
"""Reading logging config from a dictionary."""
check_no_resource_warning = support.check_no_resource_warning
expected_log_pat = r"^(\w+) \+\+ (\w+)$"
# config0 is a standard configuration.
config0 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'root' : {
'level' : 'WARNING',
'handlers' : ['hand1'],
},
}
# config1 adds a little to the standard configuration.
config1 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
# config1a moves the handler to the root. Used with config8a
config1a = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
},
},
'root' : {
'level' : 'WARNING',
'handlers' : ['hand1'],
},
}
# config2 has a subtle configuration error that should be reported
config2 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdbout',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
# As config1 but with a misspelt level on a handler
config2a = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NTOSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
# As config1 but with a misspelt level on a logger
config2b = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WRANING',
},
}
# config3 has a less subtle configuration error
config3 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'misspelled_name',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
# config4 specifies a custom formatter class to be loaded
config4 = {
'version': 1,
'formatters': {
'form1' : {
'()' : __name__ + '.ExceptionFormatter',
'format' : '%(levelname)s:%(name)s:%(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'root' : {
'level' : 'NOTSET',
'handlers' : ['hand1'],
},
}
# As config4 but using an actual callable rather than a string
config4a = {
'version': 1,
'formatters': {
'form1' : {
'()' : ExceptionFormatter,
'format' : '%(levelname)s:%(name)s:%(message)s',
},
'form2' : {
'()' : __name__ + '.formatFunc',
'format' : '%(levelname)s:%(name)s:%(message)s',
},
'form3' : {
'()' : formatFunc,
'format' : '%(levelname)s:%(name)s:%(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
'hand2' : {
'()' : handlerFunc,
},
},
'root' : {
'level' : 'NOTSET',
'handlers' : ['hand1'],
},
}
# config5 specifies a custom handler class to be loaded
config5 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : __name__ + '.CustomHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
# config6 specifies a custom handler class to be loaded
# but has bad arguments
config6 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : __name__ + '.CustomHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
'9' : 'invalid parameter name',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
# config 7 does not define compiler.parser but defines compiler.lexer
# so compiler.parser should be disabled after applying it
config7 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler.lexer' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
# config8 defines both compiler and compiler.lexer
# so compiler.parser should not be disabled (since
# compiler is defined)
config8 = {
'version': 1,
'disable_existing_loggers' : False,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
'compiler.lexer' : {
},
},
'root' : {
'level' : 'WARNING',
},
}
# config8a disables existing loggers
config8a = {
'version': 1,
'disable_existing_loggers' : True,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
'compiler.lexer' : {
},
},
'root' : {
'level' : 'WARNING',
},
}
config9 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'WARNING',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'WARNING',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'NOTSET',
},
}
config9a = {
'version': 1,
'incremental' : True,
'handlers' : {
'hand1' : {
'level' : 'WARNING',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'INFO',
},
},
}
config9b = {
'version': 1,
'incremental' : True,
'handlers' : {
'hand1' : {
'level' : 'INFO',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'INFO',
},
},
}
# As config1 but with a filter added
config10 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'filters' : {
'filt1' : {
'name' : 'compiler.parser',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
'filters' : ['filt1'],
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'filters' : ['filt1'],
},
},
'root' : {
'level' : 'WARNING',
'handlers' : ['hand1'],
},
}
# As config1 but using cfg:// references
config11 = {
'version': 1,
'true_formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handler_configs': {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'formatters' : 'cfg://true_formatters',
'handlers' : {
'hand1' : 'cfg://handler_configs[hand1]',
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
# As config11 but missing the version key
config12 = {
'true_formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handler_configs': {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'formatters' : 'cfg://true_formatters',
'handlers' : {
'hand1' : 'cfg://handler_configs[hand1]',
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
# As config11 but using an unsupported version
config13 = {
'version': 2,
'true_formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handler_configs': {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'formatters' : 'cfg://true_formatters',
'handlers' : {
'hand1' : 'cfg://handler_configs[hand1]',
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
# As config0, but with properties
config14 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
'.': {
'foo': 'bar',
'terminator': '!\n',
}
},
},
'root' : {
'level' : 'WARNING',
'handlers' : ['hand1'],
},
}
out_of_order = {
"version": 1,
"formatters": {
"mySimpleFormatter": {
"format": "%(asctime)s (%(name)s) %(levelname)s: %(message)s",
"style": "$"
}
},
"handlers": {
"fileGlobal": {
"class": "logging.StreamHandler",
"level": "DEBUG",
"formatter": "mySimpleFormatter"
},
"bufferGlobal": {
"class": "logging.handlers.MemoryHandler",
"capacity": 5,
"formatter": "mySimpleFormatter",
"target": "fileGlobal",
"level": "DEBUG"
}
},
"loggers": {
"mymodule": {
"level": "DEBUG",
"handlers": ["bufferGlobal"],
"propagate": "true"
}
}
}
def apply_config(self, conf):
logging.config.dictConfig(conf)
def test_config0_ok(self):
# A simple config which overrides the default settings.
with support.captured_stdout() as output:
self.apply_config(self.config0)
logger = logging.getLogger()
# Won't output anything
logger.info(self.next_message())
# Outputs a message
logger.error(self.next_message())
self.assert_log_lines([
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
def test_config1_ok(self, config=config1):
# A config defining a sub-parser as well.
with support.captured_stdout() as output:
self.apply_config(config)
logger = logging.getLogger("compiler.parser")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '1'),
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
def test_config2_failure(self):
# A simple config which overrides the default settings.
self.assertRaises(Exception, self.apply_config, self.config2)
def test_config2a_failure(self):
# A simple config which overrides the default settings.
self.assertRaises(Exception, self.apply_config, self.config2a)
def test_config2b_failure(self):
# A simple config which overrides the default settings.
self.assertRaises(Exception, self.apply_config, self.config2b)
def test_config3_failure(self):
# A simple config which overrides the default settings.
self.assertRaises(Exception, self.apply_config, self.config3)
def test_config4_ok(self):
# A config specifying a custom formatter class.
with support.captured_stdout() as output:
self.apply_config(self.config4)
#logger = logging.getLogger()
try:
raise RuntimeError()
except RuntimeError:
logging.exception("just testing")
sys.stdout.seek(0)
self.assertEqual(output.getvalue(),
"ERROR:root:just testing\nGot a [RuntimeError]\n")
# Original logger output is empty
self.assert_log_lines([])
def test_config4a_ok(self):
# A config specifying a custom formatter class.
with support.captured_stdout() as output:
self.apply_config(self.config4a)
#logger = logging.getLogger()
try:
raise RuntimeError()
except RuntimeError:
logging.exception("just testing")
sys.stdout.seek(0)
self.assertEqual(output.getvalue(),
"ERROR:root:just testing\nGot a [RuntimeError]\n")
# Original logger output is empty
self.assert_log_lines([])
def test_config5_ok(self):
self.test_config1_ok(config=self.config5)
def test_config6_failure(self):
self.assertRaises(Exception, self.apply_config, self.config6)
def test_config7_ok(self):
with support.captured_stdout() as output:
self.apply_config(self.config1)
logger = logging.getLogger("compiler.parser")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '1'),
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
with support.captured_stdout() as output:
self.apply_config(self.config7)
logger = logging.getLogger("compiler.parser")
self.assertTrue(logger.disabled)
logger = logging.getLogger("compiler.lexer")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '3'),
('ERROR', '4'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
# Same as test_config_7_ok but don't disable old loggers.
def test_config_8_ok(self):
with support.captured_stdout() as output:
self.apply_config(self.config1)
logger = logging.getLogger("compiler.parser")
# All will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '1'),
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
with support.captured_stdout() as output:
self.apply_config(self.config8)
logger = logging.getLogger("compiler.parser")
self.assertFalse(logger.disabled)
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
logger = logging.getLogger("compiler.lexer")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '3'),
('ERROR', '4'),
('INFO', '5'),
('ERROR', '6'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
def test_config_8a_ok(self):
with support.captured_stdout() as output:
self.apply_config(self.config1a)
logger = logging.getLogger("compiler.parser")
# See issue #11424. compiler-hyphenated sorts
# between compiler and compiler.xyz and this
# was preventing compiler.xyz from being included
# in the child loggers of compiler because of an
# overzealous loop termination condition.
hyphenated = logging.getLogger('compiler-hyphenated')
# All will output a message
logger.info(self.next_message())
logger.error(self.next_message())
hyphenated.critical(self.next_message())
self.assert_log_lines([
('INFO', '1'),
('ERROR', '2'),
('CRITICAL', '3'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
with support.captured_stdout() as output:
self.apply_config(self.config8a)
logger = logging.getLogger("compiler.parser")
self.assertFalse(logger.disabled)
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
logger = logging.getLogger("compiler.lexer")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
# Will not appear
hyphenated.critical(self.next_message())
self.assert_log_lines([
('INFO', '4'),
('ERROR', '5'),
('INFO', '6'),
('ERROR', '7'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
def test_config_9_ok(self):
with support.captured_stdout() as output:
self.apply_config(self.config9)
logger = logging.getLogger("compiler.parser")
# Nothing will be output since both handler and logger are set to WARNING
logger.info(self.next_message())
self.assert_log_lines([], stream=output)
self.apply_config(self.config9a)
# Nothing will be output since handler is still set to WARNING
logger.info(self.next_message())
self.assert_log_lines([], stream=output)
self.apply_config(self.config9b)
# Message should now be output
logger.info(self.next_message())
self.assert_log_lines([
('INFO', '3'),
], stream=output)
def test_config_10_ok(self):
with support.captured_stdout() as output:
self.apply_config(self.config10)
logger = logging.getLogger("compiler.parser")
logger.warning(self.next_message())
logger = logging.getLogger('compiler')
# Not output, because filtered
logger.warning(self.next_message())
logger = logging.getLogger('compiler.lexer')
# Not output, because filtered
logger.warning(self.next_message())
logger = logging.getLogger("compiler.parser.codegen")
# Output, as not filtered
logger.error(self.next_message())
self.assert_log_lines([
('WARNING', '1'),
('ERROR', '4'),
], stream=output)
def test_config11_ok(self):
self.test_config1_ok(self.config11)
def test_config12_failure(self):
self.assertRaises(Exception, self.apply_config, self.config12)
def test_config13_failure(self):
self.assertRaises(Exception, self.apply_config, self.config13)
def test_config14_ok(self):
with support.captured_stdout() as output:
self.apply_config(self.config14)
h = logging._handlers['hand1']
self.assertEqual(h.foo, 'bar')
self.assertEqual(h.terminator, '!\n')
logging.warning('Exclamation')
self.assertTrue(output.getvalue().endswith('Exclamation!\n'))
def test_config15_ok(self):
def cleanup(h1, fn):
h1.close()
os.remove(fn)
with self.check_no_resource_warning():
fd, fn = tempfile.mkstemp(".log", "test_logging-X-")
os.close(fd)
config = {
"version": 1,
"handlers": {
"file": {
"class": "logging.FileHandler",
"filename": fn
}
},
"root": {
"handlers": ["file"]
}
}
self.apply_config(config)
self.apply_config(config)
handler = logging.root.handlers[0]
self.addCleanup(cleanup, handler, fn)
@unittest.skipUnless(threading, 'listen() needs threading to work')
def setup_via_listener(self, text, verify=None):
text = text.encode("utf-8")
# Ask for a randomly assigned port (by using port 0)
t = logging.config.listen(0, verify)
t.start()
t.ready.wait()
# Now get the port allocated
port = t.port
t.ready.clear()
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2.0)
sock.connect(('localhost', port))
slen = struct.pack('>L', len(text))
s = slen + text
sentsofar = 0
left = len(s)
while left > 0:
sent = sock.send(s[sentsofar:])
sentsofar += sent
left -= sent
sock.close()
finally:
t.ready.wait(2.0)
logging.config.stopListening()
t.join(2.0)
@unittest.skipUnless(threading, 'Threading required for this test.')
def test_listen_config_10_ok(self):
with support.captured_stdout() as output:
self.setup_via_listener(json.dumps(self.config10))
logger = logging.getLogger("compiler.parser")
logger.warning(self.next_message())
logger = logging.getLogger('compiler')
# Not output, because filtered
logger.warning(self.next_message())
logger = logging.getLogger('compiler.lexer')
# Not output, because filtered
logger.warning(self.next_message())
logger = logging.getLogger("compiler.parser.codegen")
# Output, as not filtered
logger.error(self.next_message())
self.assert_log_lines([
('WARNING', '1'),
('ERROR', '4'),
], stream=output)
@unittest.skipUnless(threading, 'Threading required for this test.')
def test_listen_config_1_ok(self):
with support.captured_stdout() as output:
self.setup_via_listener(textwrap.dedent(ConfigFileTest.config1))
logger = logging.getLogger("compiler.parser")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '1'),
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
@unittest.skipUnless(threading, 'Threading required for this test.')
def test_listen_verify(self):
def verify_fail(stuff):
return None
def verify_reverse(stuff):
return stuff[::-1]
logger = logging.getLogger("compiler.parser")
to_send = textwrap.dedent(ConfigFileTest.config1)
# First, specify a verification function that will fail.
# We expect to see no output, since our configuration
# never took effect.
with support.captured_stdout() as output:
self.setup_via_listener(to_send, verify_fail)
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([], stream=output)
# Original logger output has the stuff we logged.
self.assert_log_lines([
('INFO', '1'),
('ERROR', '2'),
], pat=r"^[\w.]+ -> (\w+): (\d+)$")
# Now, perform no verification. Our configuration
# should take effect.
with support.captured_stdout() as output:
self.setup_via_listener(to_send) # no verify callable specified
logger = logging.getLogger("compiler.parser")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '3'),
('ERROR', '4'),
], stream=output)
# Original logger output still has the stuff we logged before.
self.assert_log_lines([
('INFO', '1'),
('ERROR', '2'),
], pat=r"^[\w.]+ -> (\w+): (\d+)$")
# Now, perform verification which transforms the bytes.
with support.captured_stdout() as output:
self.setup_via_listener(to_send[::-1], verify_reverse)
logger = logging.getLogger("compiler.parser")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '5'),
('ERROR', '6'),
], stream=output)
# Original logger output still has the stuff we logged before.
self.assert_log_lines([
('INFO', '1'),
('ERROR', '2'),
], pat=r"^[\w.]+ -> (\w+): (\d+)$")
def test_out_of_order(self):
self.apply_config(self.out_of_order)
handler = logging.getLogger('mymodule').handlers[0]
self.assertIsInstance(handler.target, logging.Handler)
self.assertIsInstance(handler.formatter._style,
logging.StringTemplateStyle)
def test_baseconfig(self):
d = {
'atuple': (1, 2, 3),
'alist': ['a', 'b', 'c'],
'adict': {'d': 'e', 'f': 3 },
'nest1': ('g', ('h', 'i'), 'j'),
'nest2': ['k', ['l', 'm'], 'n'],
'nest3': ['o', 'cfg://alist', 'p'],
}
bc = logging.config.BaseConfigurator(d)
self.assertEqual(bc.convert('cfg://atuple[1]'), 2)
self.assertEqual(bc.convert('cfg://alist[1]'), 'b')
self.assertEqual(bc.convert('cfg://nest1[1][0]'), 'h')
self.assertEqual(bc.convert('cfg://nest2[1][1]'), 'm')
self.assertEqual(bc.convert('cfg://adict.d'), 'e')
self.assertEqual(bc.convert('cfg://adict[f]'), 3)
v = bc.convert('cfg://nest3')
self.assertEqual(v.pop(1), ['a', 'b', 'c'])
self.assertRaises(KeyError, bc.convert, 'cfg://nosuch')
self.assertRaises(ValueError, bc.convert, 'cfg://!')
self.assertRaises(KeyError, bc.convert, 'cfg://adict[2]')
class ManagerTest(BaseTest):
def test_manager_loggerclass(self):
logged = []
class MyLogger(logging.Logger):
def _log(self, level, msg, args, exc_info=None, extra=None):
logged.append(msg)
man = logging.Manager(None)
self.assertRaises(TypeError, man.setLoggerClass, int)
man.setLoggerClass(MyLogger)
logger = man.getLogger('test')
logger.warning('should appear in logged')
logging.warning('should not appear in logged')
self.assertEqual(logged, ['should appear in logged'])
def test_set_log_record_factory(self):
man = logging.Manager(None)
expected = object()
man.setLogRecordFactory(expected)
self.assertEqual(man.logRecordFactory, expected)
class ChildLoggerTest(BaseTest):
def test_child_loggers(self):
r = logging.getLogger()
l1 = logging.getLogger('abc')
l2 = logging.getLogger('def.ghi')
c1 = r.getChild('xyz')
c2 = r.getChild('uvw.xyz')
self.assertIs(c1, logging.getLogger('xyz'))
self.assertIs(c2, logging.getLogger('uvw.xyz'))
c1 = l1.getChild('def')
c2 = c1.getChild('ghi')
c3 = l1.getChild('def.ghi')
self.assertIs(c1, logging.getLogger('abc.def'))
self.assertIs(c2, logging.getLogger('abc.def.ghi'))
self.assertIs(c2, c3)
class DerivedLogRecord(logging.LogRecord):
pass
class LogRecordFactoryTest(BaseTest):
def setUp(self):
class CheckingFilter(logging.Filter):
def __init__(self, cls):
self.cls = cls
def filter(self, record):
t = type(record)
if t is not self.cls:
msg = 'Unexpected LogRecord type %s, expected %s' % (t,
self.cls)
raise TypeError(msg)
return True
BaseTest.setUp(self)
self.filter = CheckingFilter(DerivedLogRecord)
self.root_logger.addFilter(self.filter)
self.orig_factory = logging.getLogRecordFactory()
def tearDown(self):
self.root_logger.removeFilter(self.filter)
BaseTest.tearDown(self)
logging.setLogRecordFactory(self.orig_factory)
def test_logrecord_class(self):
self.assertRaises(TypeError, self.root_logger.warning,
self.next_message())
logging.setLogRecordFactory(DerivedLogRecord)
self.root_logger.error(self.next_message())
self.assert_log_lines([
('root', 'ERROR', '2'),
])
class QueueHandlerTest(BaseTest):
# Do not bother with a logger name group.
expected_log_pat = r"^[\w.]+ -> (\w+): (\d+)$"
def setUp(self):
BaseTest.setUp(self)
self.queue = queue.Queue(-1)
self.que_hdlr = logging.handlers.QueueHandler(self.queue)
self.que_logger = logging.getLogger('que')
self.que_logger.propagate = False
self.que_logger.setLevel(logging.WARNING)
self.que_logger.addHandler(self.que_hdlr)
def tearDown(self):
self.que_hdlr.close()
BaseTest.tearDown(self)
def test_queue_handler(self):
self.que_logger.debug(self.next_message())
self.assertRaises(queue.Empty, self.queue.get_nowait)
self.que_logger.info(self.next_message())
self.assertRaises(queue.Empty, self.queue.get_nowait)
msg = self.next_message()
self.que_logger.warning(msg)
data = self.queue.get_nowait()
self.assertTrue(isinstance(data, logging.LogRecord))
self.assertEqual(data.name, self.que_logger.name)
self.assertEqual((data.msg, data.args), (msg, None))
@unittest.skipUnless(False and hasattr(logging.handlers, 'QueueListener'),
'logging.handlers.QueueListener required for this test')
def test_queue_listener(self): # TODO add QueueListener after threading
handler = support.TestHandler(support.Matcher())
listener = logging.handlers.QueueListener(self.queue, handler)
listener.start()
try:
self.que_logger.warning(self.next_message())
self.que_logger.error(self.next_message())
self.que_logger.critical(self.next_message())
finally:
listener.stop()
self.assertTrue(handler.matches(levelno=logging.WARNING, message='1'))
self.assertTrue(handler.matches(levelno=logging.ERROR, message='2'))
self.assertTrue(handler.matches(levelno=logging.CRITICAL, message='3'))
handler.close()
# Now test with respect_handler_level set
handler = support.TestHandler(support.Matcher())
handler.setLevel(logging.CRITICAL)
listener = logging.handlers.QueueListener(self.queue, handler,
respect_handler_level=True)
listener.start()
try:
self.que_logger.warning(self.next_message())
self.que_logger.error(self.next_message())
self.que_logger.critical(self.next_message())
finally:
listener.stop()
self.assertFalse(handler.matches(levelno=logging.WARNING, message='4'))
self.assertFalse(handler.matches(levelno=logging.ERROR, message='5'))
self.assertTrue(handler.matches(levelno=logging.CRITICAL, message='6'))
if False and hasattr(logging.handlers, 'QueueListener'):
import multiprocessing
from unittest.mock import patch
class QueueListenerTest(BaseTest):
"""
Tests based on patch submitted for issue #27930. Ensure that
QueueListener handles all log messages.
"""
repeat = 20
@staticmethod
def setup_and_log(log_queue, ident):
"""
Creates a logger with a QueueHandler that logs to a queue read by a
QueueListener. Starts the listener, logs five messages, and stops
the listener.
"""
logger = logging.getLogger('test_logger_with_id_%s' % ident)
logger.setLevel(logging.DEBUG)
handler = logging.handlers.QueueHandler(log_queue)
logger.addHandler(handler)
listener = logging.handlers.QueueListener(log_queue)
listener.start()
logger.info('one')
logger.info('two')
logger.info('three')
logger.info('four')
logger.info('five')
listener.stop()
logger.removeHandler(handler)
handler.close()
@patch.object(logging.handlers.QueueListener, 'handle')
@support.reap_threads
def test_handle_called_with_queue_queue(self, mock_handle):
for i in range(self.repeat):
log_queue = queue.Queue()
self.setup_and_log(log_queue, '%s_%s' % (self.id(), i))
self.assertEqual(mock_handle.call_count, 5 * self.repeat,
'correct number of handled log messages')
@support.requires_multiprocessing_queue
@patch.object(logging.handlers.QueueListener, 'handle')
@support.reap_threads
def test_handle_called_with_mp_queue(self, mock_handle):
for i in range(self.repeat):
log_queue = multiprocessing.Queue()
self.setup_and_log(log_queue, '%s_%s' % (self.id(), i))
log_queue.close()
log_queue.join_thread()
self.assertEqual(mock_handle.call_count, 5 * self.repeat,
'correct number of handled log messages')
@staticmethod
def get_all_from_queue(log_queue):
try:
while True:
yield log_queue.get_nowait()
except queue.Empty:
return []
@support.requires_multiprocessing_queue
@support.reap_threads
def test_no_messages_in_queue_after_stop(self):
"""
Five messages are logged then the QueueListener is stopped. This
test then gets everything off the queue. Failure of this test
indicates that messages were not registered on the queue until
_after_ the QueueListener stopped.
"""
for i in range(self.repeat):
queue = multiprocessing.Queue()
self.setup_and_log(queue, '%s_%s' %(self.id(), i))
# time.sleep(1)
items = list(self.get_all_from_queue(queue))
queue.close()
queue.join_thread()
expected = [[], [logging.handlers.QueueListener._sentinel]]
self.assertIn(items, expected,
'Found unexpected messages in queue: %s' % (
[m.msg if isinstance(m, logging.LogRecord)
else m for m in items]))
ZERO = datetime.timedelta(0)
class UTC(datetime.tzinfo):
def utcoffset(self, dt):
return ZERO
dst = utcoffset
def tzname(self, dt):
return 'UTC'
utc = UTC()
class FormatterTest(unittest.TestCase):
def setUp(self):
self.common = {
'name': 'formatter.test',
'level': logging.DEBUG,
'pathname': os.path.join('path', 'to', 'dummy.ext'),
'lineno': 42,
'exc_info': None,
'func': None,
'msg': 'Message with %d %s',
'args': (2, 'placeholders'),
}
self.variants = {
}
def get_record(self, name=None):
result = dict(self.common)
if name is not None:
result.update(self.variants[name])
return logging.makeLogRecord(result)
def test_percent(self):
# Test %-formatting
r = self.get_record()
f = logging.Formatter('${%(message)s}')
self.assertEqual(f.format(r), '${Message with 2 placeholders}')
f = logging.Formatter('%(random)s')
self.assertRaises(KeyError, f.format, r)
self.assertFalse(f.usesTime())
f = logging.Formatter('%(asctime)s')
self.assertTrue(f.usesTime())
f = logging.Formatter('%(asctime)-15s')
self.assertTrue(f.usesTime())
f = logging.Formatter('asctime')
self.assertFalse(f.usesTime())
def test_braces(self):
# Test {}-formatting
r = self.get_record()
f = logging.Formatter('$%{message}%$', style='{')
self.assertEqual(f.format(r), '$%Message with 2 placeholders%$')
f = logging.Formatter('{random}', style='{')
self.assertRaises(KeyError, f.format, r)
self.assertFalse(f.usesTime())
f = logging.Formatter('{asctime}', style='{')
self.assertTrue(f.usesTime())
f = logging.Formatter('{asctime!s:15}', style='{')
self.assertTrue(f.usesTime())
f = logging.Formatter('{asctime:15}', style='{')
self.assertTrue(f.usesTime())
f = logging.Formatter('asctime', style='{')
self.assertFalse(f.usesTime())
def test_dollars(self):
# Test $-formatting
r = self.get_record()
f = logging.Formatter('$message', style='$')
self.assertEqual(f.format(r), 'Message with 2 placeholders')
f = logging.Formatter('$$%${message}%$$', style='$')
self.assertEqual(f.format(r), '$%Message with 2 placeholders%$')
f = logging.Formatter('${random}', style='$')
self.assertRaises(KeyError, f.format, r)
self.assertFalse(f.usesTime())
f = logging.Formatter('${asctime}', style='$')
self.assertTrue(f.usesTime())
f = logging.Formatter('${asctime', style='$')
self.assertFalse(f.usesTime())
f = logging.Formatter('$asctime', style='$')
self.assertTrue(f.usesTime())
f = logging.Formatter('asctime', style='$')
self.assertFalse(f.usesTime())
def test_invalid_style(self):
self.assertRaises(ValueError, logging.Formatter, None, None, 'x')
def test_time(self):
r = self.get_record()
dt = datetime.datetime(1993, 4, 21, 8, 3, 0, 0, utc)
# We use None to indicate we want the local timezone
# We're essentially converting a UTC time to local time
r.created = time.mktime(dt.astimezone(None).timetuple())
r.msecs = 123
f = logging.Formatter('%(asctime)s %(message)s')
f.converter = time.gmtime
self.assertEqual(f.formatTime(r), '1993-04-21 08:03:00,123')
self.assertEqual(f.formatTime(r, '%Y:%d'), '1993:21')
f.format(r)
self.assertEqual(r.asctime, '1993-04-21 08:03:00,123')
class TestBufferingFormatter(logging.BufferingFormatter):
def formatHeader(self, records):
return '[(%d)' % len(records)
def formatFooter(self, records):
return '(%d)]' % len(records)
class BufferingFormatterTest(unittest.TestCase):
def setUp(self):
self.records = [
logging.makeLogRecord({'msg': 'one'}),
logging.makeLogRecord({'msg': 'two'}),
]
def test_default(self):
f = logging.BufferingFormatter()
self.assertEqual('', f.format([]))
self.assertEqual('onetwo', f.format(self.records))
def test_custom(self):
f = TestBufferingFormatter()
self.assertEqual('[(2)onetwo(2)]', f.format(self.records))
lf = logging.Formatter('<%(message)s>')
f = TestBufferingFormatter(lf)
self.assertEqual('[(2)<one><two>(2)]', f.format(self.records))
class ExceptionTest(BaseTest):
@unittest.skipIf(cosmo.MODE == "tiny", "fails only in MODE=tiny")
def test_formatting(self):
r = self.root_logger
h = RecordingHandler()
r.addHandler(h)
try:
raise RuntimeError('deliberate mistake')
except:
logging.exception('failed', stack_info=True)
r.removeHandler(h)
h.close()
r = h.records[0]
self.assertTrue(r.exc_text.startswith('Traceback (most recent '
'call last):\n'))
self.assertTrue(r.exc_text.endswith('\nRuntimeError: '
'deliberate mistake'))
self.assertTrue(r.stack_info.startswith('Stack (most recent '
'call last):\n'))
self.assertTrue(r.stack_info.endswith('logging.exception(\'failed\', '
'stack_info=True)'))
class LastResortTest(BaseTest):
def test_last_resort(self):
# Test the last resort handler
root = self.root_logger
root.removeHandler(self.root_hdlr)
old_lastresort = logging.lastResort
old_raise_exceptions = logging.raiseExceptions
try:
with support.captured_stderr() as stderr:
root.debug('This should not appear')
self.assertEqual(stderr.getvalue(), '')
root.warning('Final chance!')
self.assertEqual(stderr.getvalue(), 'Final chance!\n')
# No handlers and no last resort, so 'No handlers' message
logging.lastResort = None
with support.captured_stderr() as stderr:
root.warning('Final chance!')
msg = 'No handlers could be found for logger "root"\n'
self.assertEqual(stderr.getvalue(), msg)
# 'No handlers' message only printed once
with support.captured_stderr() as stderr:
root.warning('Final chance!')
self.assertEqual(stderr.getvalue(), '')
# If raiseExceptions is False, no message is printed
root.manager.emittedNoHandlerWarning = False
logging.raiseExceptions = False
with support.captured_stderr() as stderr:
root.warning('Final chance!')
self.assertEqual(stderr.getvalue(), '')
finally:
root.addHandler(self.root_hdlr)
logging.lastResort = old_lastresort
logging.raiseExceptions = old_raise_exceptions
class FakeHandler:
def __init__(self, identifier, called):
for method in ('acquire', 'flush', 'close', 'release'):
setattr(self, method, self.record_call(identifier, method, called))
def record_call(self, identifier, method_name, called):
def inner():
called.append('{} - {}'.format(identifier, method_name))
return inner
class RecordingHandler(logging.NullHandler):
def __init__(self, *args, **kwargs):
super(RecordingHandler, self).__init__(*args, **kwargs)
self.records = []
def handle(self, record):
"""Keep track of all the emitted records."""
self.records.append(record)
class ShutdownTest(BaseTest):
"""Test suite for the shutdown method."""
def setUp(self):
super(ShutdownTest, self).setUp()
self.called = []
raise_exceptions = logging.raiseExceptions
self.addCleanup(setattr, logging, 'raiseExceptions', raise_exceptions)
def raise_error(self, error):
def inner():
raise error()
return inner
def test_no_failure(self):
# create some fake handlers
handler0 = FakeHandler(0, self.called)
handler1 = FakeHandler(1, self.called)
handler2 = FakeHandler(2, self.called)
# create live weakref to those handlers
handlers = map(logging.weakref.ref, [handler0, handler1, handler2])
logging.shutdown(handlerList=list(handlers))
expected = ['2 - acquire', '2 - flush', '2 - close', '2 - release',
'1 - acquire', '1 - flush', '1 - close', '1 - release',
'0 - acquire', '0 - flush', '0 - close', '0 - release']
self.assertEqual(expected, self.called)
def _test_with_failure_in_method(self, method, error):
handler = FakeHandler(0, self.called)
setattr(handler, method, self.raise_error(error))
handlers = [logging.weakref.ref(handler)]
logging.shutdown(handlerList=list(handlers))
self.assertEqual('0 - release', self.called[-1])
def test_with_ioerror_in_acquire(self):
self._test_with_failure_in_method('acquire', OSError)
def test_with_ioerror_in_flush(self):
self._test_with_failure_in_method('flush', OSError)
def test_with_ioerror_in_close(self):
self._test_with_failure_in_method('close', OSError)
def test_with_valueerror_in_acquire(self):
self._test_with_failure_in_method('acquire', ValueError)
def test_with_valueerror_in_flush(self):
self._test_with_failure_in_method('flush', ValueError)
def test_with_valueerror_in_close(self):
self._test_with_failure_in_method('close', ValueError)
def test_with_other_error_in_acquire_without_raise(self):
logging.raiseExceptions = False
self._test_with_failure_in_method('acquire', IndexError)
def test_with_other_error_in_flush_without_raise(self):
logging.raiseExceptions = False
self._test_with_failure_in_method('flush', IndexError)
def test_with_other_error_in_close_without_raise(self):
logging.raiseExceptions = False
self._test_with_failure_in_method('close', IndexError)
def test_with_other_error_in_acquire_with_raise(self):
logging.raiseExceptions = True
self.assertRaises(IndexError, self._test_with_failure_in_method,
'acquire', IndexError)
def test_with_other_error_in_flush_with_raise(self):
logging.raiseExceptions = True
self.assertRaises(IndexError, self._test_with_failure_in_method,
'flush', IndexError)
def test_with_other_error_in_close_with_raise(self):
logging.raiseExceptions = True
self.assertRaises(IndexError, self._test_with_failure_in_method,
'close', IndexError)
class ModuleLevelMiscTest(BaseTest):
"""Test suite for some module level methods."""
def test_disable(self):
old_disable = logging.root.manager.disable
# confirm our assumptions are correct
self.assertEqual(old_disable, 0)
self.addCleanup(logging.disable, old_disable)
logging.disable(83)
self.assertEqual(logging.root.manager.disable, 83)
def _test_log(self, method, level=None):
called = []
support.patch(self, logging, 'basicConfig',
lambda *a, **kw: called.append((a, kw)))
recording = RecordingHandler()
logging.root.addHandler(recording)
log_method = getattr(logging, method)
if level is not None:
log_method(level, "test me: %r", recording)
else:
log_method("test me: %r", recording)
self.assertEqual(len(recording.records), 1)
record = recording.records[0]
self.assertEqual(record.getMessage(), "test me: %r" % recording)
expected_level = level if level is not None else getattr(logging, method.upper())
self.assertEqual(record.levelno, expected_level)
# basicConfig was not called!
self.assertEqual(called, [])
def test_log(self):
self._test_log('log', logging.ERROR)
def test_debug(self):
self._test_log('debug')
def test_info(self):
self._test_log('info')
def test_warning(self):
self._test_log('warning')
def test_error(self):
self._test_log('error')
def test_critical(self):
self._test_log('critical')
def test_set_logger_class(self):
self.assertRaises(TypeError, logging.setLoggerClass, object)
class MyLogger(logging.Logger):
pass
logging.setLoggerClass(MyLogger)
self.assertEqual(logging.getLoggerClass(), MyLogger)
logging.setLoggerClass(logging.Logger)
self.assertEqual(logging.getLoggerClass(), logging.Logger)
@support.requires_type_collecting
def test_logging_at_shutdown(self):
# Issue #20037
code = """if 1:
import logging
class A:
def __del__(self):
try:
raise ValueError("some error")
except Exception:
logging.exception("exception in __del__")
a = A()"""
rc, out, err = assert_python_ok("-c", code)
err = err.decode()
self.assertIn("exception in __del__", err)
self.assertIn("ValueError: some error", err)
class LogRecordTest(BaseTest):
def test_str_rep(self):
r = logging.makeLogRecord({})
s = str(r)
self.assertTrue(s.startswith('<LogRecord: '))
self.assertTrue(s.endswith('>'))
def test_dict_arg(self):
h = RecordingHandler()
r = logging.getLogger()
r.addHandler(h)
d = {'less' : 'more' }
logging.warning('less is %(less)s', d)
self.assertIs(h.records[0].args, d)
self.assertEqual(h.records[0].message, 'less is more')
r.removeHandler(h)
h.close()
def test_multiprocessing(self):
r = logging.makeLogRecord({})
self.assertEqual(r.processName, 'MainProcess')
try:
import multiprocessing as mp
r = logging.makeLogRecord({})
self.assertEqual(r.processName, mp.current_process().name)
except ImportError:
pass
def test_optional(self):
r = logging.makeLogRecord({})
NOT_NONE = self.assertIsNotNone
if threading:
NOT_NONE(r.thread)
NOT_NONE(r.threadName)
NOT_NONE(r.process)
NOT_NONE(r.processName)
log_threads = logging.logThreads
log_processes = logging.logProcesses
log_multiprocessing = logging.logMultiprocessing
try:
logging.logThreads = False
logging.logProcesses = False
logging.logMultiprocessing = False
r = logging.makeLogRecord({})
NONE = self.assertIsNone
NONE(r.thread)
NONE(r.threadName)
NONE(r.process)
NONE(r.processName)
finally:
logging.logThreads = log_threads
logging.logProcesses = log_processes
logging.logMultiprocessing = log_multiprocessing
class BasicConfigTest(unittest.TestCase):
"""Test suite for logging.basicConfig."""
def setUp(self):
super(BasicConfigTest, self).setUp()
self.handlers = logging.root.handlers
self.saved_handlers = logging._handlers.copy()
self.saved_handler_list = logging._handlerList[:]
self.original_logging_level = logging.root.level
self.addCleanup(self.cleanup)
logging.root.handlers = []
def tearDown(self):
for h in logging.root.handlers[:]:
logging.root.removeHandler(h)
h.close()
super(BasicConfigTest, self).tearDown()
def cleanup(self):
setattr(logging.root, 'handlers', self.handlers)
logging._handlers.clear()
logging._handlers.update(self.saved_handlers)
logging._handlerList[:] = self.saved_handler_list
logging.root.level = self.original_logging_level
def test_no_kwargs(self):
logging.basicConfig()
# handler defaults to a StreamHandler to sys.stderr
self.assertEqual(len(logging.root.handlers), 1)
handler = logging.root.handlers[0]
self.assertIsInstance(handler, logging.StreamHandler)
self.assertEqual(handler.stream, sys.stderr)
formatter = handler.formatter
# format defaults to logging.BASIC_FORMAT
self.assertEqual(formatter._style._fmt, logging.BASIC_FORMAT)
# datefmt defaults to None
self.assertIsNone(formatter.datefmt)
# style defaults to %
self.assertIsInstance(formatter._style, logging.PercentStyle)
# level is not explicitly set
self.assertEqual(logging.root.level, self.original_logging_level)
def test_strformatstyle(self):
with support.captured_stdout() as output:
logging.basicConfig(stream=sys.stdout, style="{")
logging.error("Log an error")
sys.stdout.seek(0)
self.assertEqual(output.getvalue().strip(),
"ERROR:root:Log an error")
def test_stringtemplatestyle(self):
with support.captured_stdout() as output:
logging.basicConfig(stream=sys.stdout, style="$")
logging.error("Log an error")
sys.stdout.seek(0)
self.assertEqual(output.getvalue().strip(),
"ERROR:root:Log an error")
def test_filename(self):
def cleanup(h1, h2, fn):
h1.close()
h2.close()
os.remove(fn)
logging.basicConfig(filename='test.log')
self.assertEqual(len(logging.root.handlers), 1)
handler = logging.root.handlers[0]
self.assertIsInstance(handler, logging.FileHandler)
expected = logging.FileHandler('test.log', 'a')
self.assertEqual(handler.stream.mode, expected.stream.mode)
self.assertEqual(handler.stream.name, expected.stream.name)
self.addCleanup(cleanup, handler, expected, 'test.log')
def test_filemode(self):
def cleanup(h1, h2, fn):
h1.close()
h2.close()
os.remove(fn)
logging.basicConfig(filename='test.log', filemode='wb')
handler = logging.root.handlers[0]
expected = logging.FileHandler('test.log', 'wb')
self.assertEqual(handler.stream.mode, expected.stream.mode)
self.addCleanup(cleanup, handler, expected, 'test.log')
def test_stream(self):
stream = io.StringIO()
self.addCleanup(stream.close)
logging.basicConfig(stream=stream)
self.assertEqual(len(logging.root.handlers), 1)
handler = logging.root.handlers[0]
self.assertIsInstance(handler, logging.StreamHandler)
self.assertEqual(handler.stream, stream)
def test_format(self):
logging.basicConfig(format='foo')
formatter = logging.root.handlers[0].formatter
self.assertEqual(formatter._style._fmt, 'foo')
def test_datefmt(self):
logging.basicConfig(datefmt='bar')
formatter = logging.root.handlers[0].formatter
self.assertEqual(formatter.datefmt, 'bar')
def test_style(self):
logging.basicConfig(style='$')
formatter = logging.root.handlers[0].formatter
self.assertIsInstance(formatter._style, logging.StringTemplateStyle)
def test_level(self):
old_level = logging.root.level
self.addCleanup(logging.root.setLevel, old_level)
logging.basicConfig(level=57)
self.assertEqual(logging.root.level, 57)
# Test that second call has no effect
logging.basicConfig(level=58)
self.assertEqual(logging.root.level, 57)
def test_incompatible(self):
assertRaises = self.assertRaises
handlers = [logging.StreamHandler()]
stream = sys.stderr
assertRaises(ValueError, logging.basicConfig, filename='test.log',
stream=stream)
assertRaises(ValueError, logging.basicConfig, filename='test.log',
handlers=handlers)
assertRaises(ValueError, logging.basicConfig, stream=stream,
handlers=handlers)
# Issue 23207: test for invalid kwargs
assertRaises(ValueError, logging.basicConfig, loglevel=logging.INFO)
# Should pop both filename and filemode even if filename is None
logging.basicConfig(filename=None, filemode='a')
def test_handlers(self):
handlers = [
logging.StreamHandler(),
logging.StreamHandler(sys.stdout),
logging.StreamHandler(),
]
f = logging.Formatter()
handlers[2].setFormatter(f)
logging.basicConfig(handlers=handlers)
self.assertIs(handlers[0], logging.root.handlers[0])
self.assertIs(handlers[1], logging.root.handlers[1])
self.assertIs(handlers[2], logging.root.handlers[2])
self.assertIsNotNone(handlers[0].formatter)
self.assertIsNotNone(handlers[1].formatter)
self.assertIs(handlers[2].formatter, f)
self.assertIs(handlers[0].formatter, handlers[1].formatter)
def _test_log(self, method, level=None):
# logging.root has no handlers so basicConfig should be called
called = []
old_basic_config = logging.basicConfig
def my_basic_config(*a, **kw):
old_basic_config()
old_level = logging.root.level
logging.root.setLevel(100) # avoid having messages in stderr
self.addCleanup(logging.root.setLevel, old_level)
called.append((a, kw))
support.patch(self, logging, 'basicConfig', my_basic_config)
log_method = getattr(logging, method)
if level is not None:
log_method(level, "test me")
else:
log_method("test me")
# basicConfig was called with no arguments
self.assertEqual(called, [((), {})])
def test_log(self):
self._test_log('log', logging.WARNING)
def test_debug(self):
self._test_log('debug')
def test_info(self):
self._test_log('info')
def test_warning(self):
self._test_log('warning')
def test_error(self):
self._test_log('error')
def test_critical(self):
self._test_log('critical')
class LoggerAdapterTest(unittest.TestCase):
def setUp(self):
super(LoggerAdapterTest, self).setUp()
old_handler_list = logging._handlerList[:]
self.recording = RecordingHandler()
self.logger = logging.root
self.logger.addHandler(self.recording)
self.addCleanup(self.logger.removeHandler, self.recording)
self.addCleanup(self.recording.close)
def cleanup():
logging._handlerList[:] = old_handler_list
self.addCleanup(cleanup)
self.addCleanup(logging.shutdown)
self.adapter = logging.LoggerAdapter(logger=self.logger, extra=None)
def test_exception(self):
msg = 'testing exception: %r'
exc = None
try:
1 / 0
except ZeroDivisionError as e:
exc = e
self.adapter.exception(msg, self.recording)
self.assertEqual(len(self.recording.records), 1)
record = self.recording.records[0]
self.assertEqual(record.levelno, logging.ERROR)
self.assertEqual(record.msg, msg)
self.assertEqual(record.args, (self.recording,))
self.assertEqual(record.exc_info,
(exc.__class__, exc, exc.__traceback__))
def test_exception_excinfo(self):
try:
1 / 0
except ZeroDivisionError as e:
exc = e
self.adapter.exception('exc_info test', exc_info=exc)
self.assertEqual(len(self.recording.records), 1)
record = self.recording.records[0]
self.assertEqual(record.exc_info,
(exc.__class__, exc, exc.__traceback__))
def test_critical(self):
msg = 'critical test! %r'
self.adapter.critical(msg, self.recording)
self.assertEqual(len(self.recording.records), 1)
record = self.recording.records[0]
self.assertEqual(record.levelno, logging.CRITICAL)
self.assertEqual(record.msg, msg)
self.assertEqual(record.args, (self.recording,))
def test_is_enabled_for(self):
old_disable = self.adapter.logger.manager.disable
self.adapter.logger.manager.disable = 33
self.addCleanup(setattr, self.adapter.logger.manager, 'disable',
old_disable)
self.assertFalse(self.adapter.isEnabledFor(32))
def test_has_handlers(self):
self.assertTrue(self.adapter.hasHandlers())
for handler in self.logger.handlers:
self.logger.removeHandler(handler)
self.assertFalse(self.logger.hasHandlers())
self.assertFalse(self.adapter.hasHandlers())
def test_nested(self):
class Adapter(logging.LoggerAdapter):
prefix = 'Adapter'
def process(self, msg, kwargs):
return f"{self.prefix} {msg}", kwargs
msg = 'Adapters can be nested, yo.'
adapter = Adapter(logger=self.logger, extra=None)
adapter_adapter = Adapter(logger=adapter, extra=None)
adapter_adapter.prefix = 'AdapterAdapter'
self.assertEqual(repr(adapter), repr(adapter_adapter))
adapter_adapter.log(logging.CRITICAL, msg, self.recording)
self.assertEqual(len(self.recording.records), 1)
record = self.recording.records[0]
self.assertEqual(record.levelno, logging.CRITICAL)
self.assertEqual(record.msg, f"Adapter AdapterAdapter {msg}")
self.assertEqual(record.args, (self.recording,))
orig_manager = adapter_adapter.manager
self.assertIs(adapter.manager, orig_manager)
self.assertIs(self.logger.manager, orig_manager)
temp_manager = object()
try:
adapter_adapter.manager = temp_manager
self.assertIs(adapter_adapter.manager, temp_manager)
self.assertIs(adapter.manager, temp_manager)
self.assertIs(self.logger.manager, temp_manager)
finally:
adapter_adapter.manager = orig_manager
self.assertIs(adapter_adapter.manager, orig_manager)
self.assertIs(adapter.manager, orig_manager)
self.assertIs(self.logger.manager, orig_manager)
class LoggerTest(BaseTest):
def setUp(self):
super(LoggerTest, self).setUp()
self.recording = RecordingHandler()
self.logger = logging.Logger(name='blah')
self.logger.addHandler(self.recording)
self.addCleanup(self.logger.removeHandler, self.recording)
self.addCleanup(self.recording.close)
self.addCleanup(logging.shutdown)
def test_set_invalid_level(self):
self.assertRaises(TypeError, self.logger.setLevel, object())
def test_exception(self):
msg = 'testing exception: %r'
exc = None
try:
1 / 0
except ZeroDivisionError as e:
exc = e
self.logger.exception(msg, self.recording)
self.assertEqual(len(self.recording.records), 1)
record = self.recording.records[0]
self.assertEqual(record.levelno, logging.ERROR)
self.assertEqual(record.msg, msg)
self.assertEqual(record.args, (self.recording,))
self.assertEqual(record.exc_info,
(exc.__class__, exc, exc.__traceback__))
def test_log_invalid_level_with_raise(self):
with support.swap_attr(logging, 'raiseExceptions', True):
self.assertRaises(TypeError, self.logger.log, '10', 'test message')
def test_log_invalid_level_no_raise(self):
with support.swap_attr(logging, 'raiseExceptions', False):
self.logger.log('10', 'test message') # no exception happens
def test_find_caller_with_stack_info(self):
called = []
support.patch(self, logging.traceback, 'print_stack',
lambda f, file: called.append(file.getvalue()))
self.logger.findCaller(stack_info=True)
self.assertEqual(len(called), 1)
self.assertEqual('Stack (most recent call last):\n', called[0])
def test_make_record_with_extra_overwrite(self):
name = 'my record'
level = 13
fn = lno = msg = args = exc_info = func = sinfo = None
rv = logging._logRecordFactory(name, level, fn, lno, msg, args,
exc_info, func, sinfo)
for key in ('message', 'asctime') + tuple(rv.__dict__.keys()):
extra = {key: 'some value'}
self.assertRaises(KeyError, self.logger.makeRecord, name, level,
fn, lno, msg, args, exc_info,
extra=extra, sinfo=sinfo)
def test_make_record_with_extra_no_overwrite(self):
name = 'my record'
level = 13
fn = lno = msg = args = exc_info = func = sinfo = None
extra = {'valid_key': 'some value'}
result = self.logger.makeRecord(name, level, fn, lno, msg, args,
exc_info, extra=extra, sinfo=sinfo)
self.assertIn('valid_key', result.__dict__)
def test_has_handlers(self):
self.assertTrue(self.logger.hasHandlers())
for handler in self.logger.handlers:
self.logger.removeHandler(handler)
self.assertFalse(self.logger.hasHandlers())
def test_has_handlers_no_propagate(self):
child_logger = logging.getLogger('blah.child')
child_logger.propagate = False
self.assertFalse(child_logger.hasHandlers())
def test_is_enabled_for(self):
old_disable = self.logger.manager.disable
self.logger.manager.disable = 23
self.addCleanup(setattr, self.logger.manager, 'disable', old_disable)
self.assertFalse(self.logger.isEnabledFor(22))
def test_root_logger_aliases(self):
root = logging.getLogger()
self.assertIs(root, logging.root)
self.assertIs(root, logging.getLogger(None))
self.assertIs(root, logging.getLogger(''))
self.assertIs(root, logging.getLogger('foo').root)
self.assertIs(root, logging.getLogger('foo.bar').root)
self.assertIs(root, logging.getLogger('foo').parent)
self.assertIsNot(root, logging.getLogger('\0'))
self.assertIsNot(root, logging.getLogger('foo.bar').parent)
def test_invalid_names(self):
self.assertRaises(TypeError, logging.getLogger, any)
self.assertRaises(TypeError, logging.getLogger, b'foo')
class BaseFileTest(BaseTest):
"Base class for handler tests that write log files"
def setUp(self):
BaseTest.setUp(self)
fd, self.fn = tempfile.mkstemp(".log", "test_logging-2-")
os.close(fd)
self.rmfiles = []
def tearDown(self):
for fn in self.rmfiles:
os.unlink(fn)
if os.path.exists(self.fn):
os.unlink(self.fn)
BaseTest.tearDown(self)
def assertLogFile(self, filename):
"Assert a log file is there and register it for deletion"
self.assertTrue(os.path.exists(filename),
msg="Log file %r does not exist" % filename)
self.rmfiles.append(filename)
class FileHandlerTest(BaseFileTest):
def test_delay(self):
os.unlink(self.fn)
fh = logging.FileHandler(self.fn, delay=True)
self.assertIsNone(fh.stream)
self.assertFalse(os.path.exists(self.fn))
fh.handle(logging.makeLogRecord({}))
self.assertIsNotNone(fh.stream)
self.assertTrue(os.path.exists(self.fn))
fh.close()
class RotatingFileHandlerTest(BaseFileTest):
def next_rec(self):
return logging.LogRecord('n', logging.DEBUG, 'p', 1,
self.next_message(), None, None, None)
def test_should_not_rollover(self):
# If maxbytes is zero rollover never occurs
rh = logging.handlers.RotatingFileHandler(self.fn, maxBytes=0)
self.assertFalse(rh.shouldRollover(None))
rh.close()
def test_should_rollover(self):
rh = logging.handlers.RotatingFileHandler(self.fn, maxBytes=1)
self.assertTrue(rh.shouldRollover(self.next_rec()))
rh.close()
def test_file_created(self):
# checks that the file is created and assumes it was created
# by us
rh = logging.handlers.RotatingFileHandler(self.fn)
rh.emit(self.next_rec())
self.assertLogFile(self.fn)
rh.close()
def test_rollover_filenames(self):
def namer(name):
return name + ".test"
rh = logging.handlers.RotatingFileHandler(
self.fn, backupCount=2, maxBytes=1)
rh.namer = namer
rh.emit(self.next_rec())
self.assertLogFile(self.fn)
rh.emit(self.next_rec())
self.assertLogFile(namer(self.fn + ".1"))
rh.emit(self.next_rec())
self.assertLogFile(namer(self.fn + ".2"))
self.assertFalse(os.path.exists(namer(self.fn + ".3")))
rh.close()
@support.requires_zlib
def test_rotator(self):
def namer(name):
return name + ".gz"
def rotator(source, dest):
with open(source, "rb") as sf:
data = sf.read()
compressed = zlib.compress(data, 9)
with open(dest, "wb") as df:
df.write(compressed)
os.remove(source)
rh = logging.handlers.RotatingFileHandler(
self.fn, backupCount=2, maxBytes=1)
rh.rotator = rotator
rh.namer = namer
m1 = self.next_rec()
rh.emit(m1)
self.assertLogFile(self.fn)
m2 = self.next_rec()
rh.emit(m2)
fn = namer(self.fn + ".1")
self.assertLogFile(fn)
newline = os.linesep
with open(fn, "rb") as f:
compressed = f.read()
data = zlib.decompress(compressed)
self.assertEqual(data.decode("ascii"), m1.msg + newline)
rh.emit(self.next_rec())
fn = namer(self.fn + ".2")
self.assertLogFile(fn)
with open(fn, "rb") as f:
compressed = f.read()
data = zlib.decompress(compressed)
self.assertEqual(data.decode("ascii"), m1.msg + newline)
rh.emit(self.next_rec())
fn = namer(self.fn + ".2")
with open(fn, "rb") as f:
compressed = f.read()
data = zlib.decompress(compressed)
self.assertEqual(data.decode("ascii"), m2.msg + newline)
self.assertFalse(os.path.exists(namer(self.fn + ".3")))
rh.close()
class TimedRotatingFileHandlerTest(BaseFileTest):
# other test methods added below
def test_rollover(self):
fh = logging.handlers.TimedRotatingFileHandler(self.fn, 'S',
backupCount=1)
fmt = logging.Formatter('%(asctime)s %(message)s')
fh.setFormatter(fmt)
r1 = logging.makeLogRecord({'msg': 'testing - initial'})
fh.emit(r1)
self.assertLogFile(self.fn)
time.sleep(1.1) # a little over a second ...
r2 = logging.makeLogRecord({'msg': 'testing - after delay'})
fh.emit(r2)
fh.close()
# At this point, we should have a recent rotated file which we
# can test for the existence of. However, in practice, on some
# machines which run really slowly, we don't know how far back
# in time to go to look for the log file. So, we go back a fair
# bit, and stop as soon as we see a rotated file. In theory this
# could of course still fail, but the chances are lower.
found = False
now = datetime.datetime.now()
GO_BACK = 5 * 60 # seconds
for secs in range(GO_BACK):
prev = now - datetime.timedelta(seconds=secs)
fn = self.fn + prev.strftime(".%Y-%m-%d_%H-%M-%S")
found = os.path.exists(fn)
if found:
self.rmfiles.append(fn)
break
msg = 'No rotated files found, went back %d seconds' % GO_BACK
if not found:
# print additional diagnostics
dn, fn = os.path.split(self.fn)
files = [f for f in os.listdir(dn) if f.startswith(fn)]
print('Test time: %s' % now.strftime("%Y-%m-%d %H-%M-%S"), file=sys.stderr)
print('The only matching files are: %s' % files, file=sys.stderr)
for f in files:
print('Contents of %s:' % f)
path = os.path.join(dn, f)
with open(path, 'r') as tf:
print(tf.read())
self.assertTrue(found, msg=msg)
def test_invalid(self):
assertRaises = self.assertRaises
assertRaises(ValueError, logging.handlers.TimedRotatingFileHandler,
self.fn, 'X', delay=True)
assertRaises(ValueError, logging.handlers.TimedRotatingFileHandler,
self.fn, 'W', delay=True)
assertRaises(ValueError, logging.handlers.TimedRotatingFileHandler,
self.fn, 'W7', delay=True)
def test_compute_rollover_daily_attime(self):
currentTime = 0
atTime = datetime.time(12, 0, 0)
rh = logging.handlers.TimedRotatingFileHandler(
self.fn, when='MIDNIGHT', interval=1, backupCount=0, utc=True,
atTime=atTime)
try:
actual = rh.computeRollover(currentTime)
self.assertEqual(actual, currentTime + 12 * 60 * 60)
actual = rh.computeRollover(currentTime + 13 * 60 * 60)
self.assertEqual(actual, currentTime + 36 * 60 * 60)
finally:
rh.close()
#@unittest.skipIf(True, 'Temporarily skipped while failures investigated.')
def test_compute_rollover_weekly_attime(self):
currentTime = int(time.time())
today = currentTime - currentTime % 86400
atTime = datetime.time(12, 0, 0)
wday = time.gmtime(today).tm_wday
for day in range(7):
rh = logging.handlers.TimedRotatingFileHandler(
self.fn, when='W%d' % day, interval=1, backupCount=0, utc=True,
atTime=atTime)
try:
if wday > day:
# The rollover day has already passed this week, so we
# go over into next week
expected = (7 - wday + day)
else:
expected = (day - wday)
# At this point expected is in days from now, convert to seconds
expected *= 24 * 60 * 60
# Add in the rollover time
expected += 12 * 60 * 60
# Add in adjustment for today
expected += today
actual = rh.computeRollover(today)
if actual != expected:
print('failed in timezone: %d' % time.timezone)
print('local vars: %s' % locals())
self.assertEqual(actual, expected)
if day == wday:
# goes into following week
expected += 7 * 24 * 60 * 60
actual = rh.computeRollover(today + 13 * 60 * 60)
if actual != expected:
print('failed in timezone: %d' % time.timezone)
print('local vars: %s' % locals())
self.assertEqual(actual, expected)
finally:
rh.close()
def secs(**kw):
return datetime.timedelta(**kw) // datetime.timedelta(seconds=1)
for when, exp in (('S', 1),
('M', 60),
('H', 60 * 60),
('D', 60 * 60 * 24),
('MIDNIGHT', 60 * 60 * 24),
# current time (epoch start) is a Thursday, W0 means Monday
('W0', secs(days=4, hours=24)),
):
def test_compute_rollover(self, when=when, exp=exp):
rh = logging.handlers.TimedRotatingFileHandler(
self.fn, when=when, interval=1, backupCount=0, utc=True)
currentTime = 0.0
actual = rh.computeRollover(currentTime)
if exp != actual:
# Failures occur on some systems for MIDNIGHT and W0.
# Print detailed calculation for MIDNIGHT so we can try to see
# what's going on
if when == 'MIDNIGHT':
try:
if rh.utc:
t = time.gmtime(currentTime)
else:
t = time.localtime(currentTime)
currentHour = t[3]
currentMinute = t[4]
currentSecond = t[5]
# r is the number of seconds left between now and midnight
r = logging.handlers._MIDNIGHT - ((currentHour * 60 +
currentMinute) * 60 +
currentSecond)
result = currentTime + r
print('t: %s (%s)' % (t, rh.utc), file=sys.stderr)
print('currentHour: %s' % currentHour, file=sys.stderr)
print('currentMinute: %s' % currentMinute, file=sys.stderr)
print('currentSecond: %s' % currentSecond, file=sys.stderr)
print('r: %s' % r, file=sys.stderr)
print('result: %s' % result, file=sys.stderr)
except Exception:
print('exception in diagnostic code: %s' % sys.exc_info()[1], file=sys.stderr)
self.assertEqual(exp, actual)
rh.close()
setattr(TimedRotatingFileHandlerTest, "test_compute_rollover_%s" % when, test_compute_rollover)
@unittest.skipUnless(win32evtlog, 'win32evtlog/win32evtlogutil/pywintypes required for this test.')
class NTEventLogHandlerTest(BaseTest):
def test_basic(self):
logtype = 'Application'
elh = win32evtlog.OpenEventLog(None, logtype)
num_recs = win32evtlog.GetNumberOfEventLogRecords(elh)
try:
h = logging.handlers.NTEventLogHandler('test_logging')
except pywintypes.error as e:
if e.winerror == 5: # access denied
raise unittest.SkipTest('Insufficient privileges to run test')
raise
r = logging.makeLogRecord({'msg': 'Test Log Message'})
h.handle(r)
h.close()
# Now see if the event is recorded
self.assertLess(num_recs, win32evtlog.GetNumberOfEventLogRecords(elh))
flags = win32evtlog.EVENTLOG_BACKWARDS_READ | \
win32evtlog.EVENTLOG_SEQUENTIAL_READ
found = False
GO_BACK = 100
events = win32evtlog.ReadEventLog(elh, flags, GO_BACK)
for e in events:
if e.SourceName != 'test_logging':
continue
msg = win32evtlogutil.SafeFormatMessage(e, logtype)
if msg != 'Test Log Message\r\n':
continue
found = True
break
msg = 'Record not found in event log, went back %d records' % GO_BACK
self.assertTrue(found, msg=msg)
class MiscTestCase(unittest.TestCase):
def test__all__(self):
blacklist = {'logThreads', 'logMultiprocessing',
'logProcesses', 'currentframe',
'PercentStyle', 'StrFormatStyle', 'StringTemplateStyle',
'Filterer', 'PlaceHolder', 'Manager', 'RootLogger',
'root', 'threading'}
support.check__all__(self, logging, blacklist=blacklist)
# Set the locale to the platform-dependent default. I have no idea
# why the test does this, but in any case we save the current locale
# first and restore it at the end.
@support.run_with_locale('LC_ALL', '')
def test_main():
tests = [
BuiltinLevelsTest, BasicFilterTest, CustomLevelsAndFiltersTest,
HandlerTest, MemoryHandlerTest, ConfigFileTest, SocketHandlerTest,
DatagramHandlerTest, MemoryTest, EncodingTest, WarningsTest,
ConfigDictTest, ManagerTest, FormatterTest, BufferingFormatterTest,
StreamHandlerTest, LogRecordFactoryTest, ChildLoggerTest,
QueueHandlerTest, ShutdownTest, ModuleLevelMiscTest, BasicConfigTest,
LoggerAdapterTest, LoggerTest, SMTPHandlerTest, FileHandlerTest,
RotatingFileHandlerTest, LastResortTest, LogRecordTest,
ExceptionTest, SysLogHandlerTest, IPv6SysLogHandlerTest, HTTPHandlerTest,
NTEventLogHandlerTest, TimedRotatingFileHandlerTest,
UnixSocketHandlerTest, UnixDatagramHandlerTest, UnixSysLogHandlerTest,
MiscTestCase
]
if False and hasattr(logging.handlers, 'QueueListener'):
tests.append(QueueListenerTest)
support.run_unittest(*tests)
if __name__ == "__main__":
test_main()
| 158,641 | 4,526 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_tempfile.py | # tempfile.py unit tests.
import tempfile
import errno
import io
import os
import signal
import sys
import re
import warnings
import contextlib
import weakref
from unittest import mock
import unittest
from test import support
from encodings import utf_16
from test.support import script_helper
if hasattr(os, 'stat'):
import stat
has_stat = 1
else:
has_stat = 0
has_textmode = (tempfile._text_openflags != tempfile._bin_openflags)
has_spawnl = hasattr(os, 'spawnl')
# TEST_FILES may need to be tweaked for systems depending on the maximum
# number of files that can be opened at one time (see ulimit -n)
if sys.platform.startswith('openbsd'):
TEST_FILES = 48
else:
TEST_FILES = 100
if __name__ == "PYOBJ.COM":
from test import tf_inherit_check
# This is organized as one test for each chunk of code in tempfile.py,
# in order of their appearance in the file. Testing which requires
# threads is not done here.
class TestLowLevelInternals(unittest.TestCase):
def test_infer_return_type_singles(self):
self.assertIs(str, tempfile._infer_return_type(''))
self.assertIs(bytes, tempfile._infer_return_type(b''))
self.assertIs(str, tempfile._infer_return_type(None))
def test_infer_return_type_multiples(self):
self.assertIs(str, tempfile._infer_return_type('', ''))
self.assertIs(bytes, tempfile._infer_return_type(b'', b''))
with self.assertRaises(TypeError):
tempfile._infer_return_type('', b'')
with self.assertRaises(TypeError):
tempfile._infer_return_type(b'', '')
def test_infer_return_type_multiples_and_none(self):
self.assertIs(str, tempfile._infer_return_type(None, ''))
self.assertIs(str, tempfile._infer_return_type('', None))
self.assertIs(str, tempfile._infer_return_type(None, None))
self.assertIs(bytes, tempfile._infer_return_type(b'', None))
self.assertIs(bytes, tempfile._infer_return_type(None, b''))
with self.assertRaises(TypeError):
tempfile._infer_return_type('', None, b'')
with self.assertRaises(TypeError):
tempfile._infer_return_type(b'', None, '')
# Common functionality.
class BaseTestCase(unittest.TestCase):
str_check = re.compile(r"^[a-z0-9_-]{8}$")
b_check = re.compile(br"^[a-z0-9_-]{8}$")
def setUp(self):
self._warnings_manager = support.check_warnings()
self._warnings_manager.__enter__()
warnings.filterwarnings("ignore", category=RuntimeWarning,
message="mktemp", module=__name__)
def tearDown(self):
self._warnings_manager.__exit__(None, None, None)
def nameCheck(self, name, dir, pre, suf):
(ndir, nbase) = os.path.split(name)
npre = nbase[:len(pre)]
nsuf = nbase[len(nbase)-len(suf):]
if dir is not None:
self.assertIs(type(name), str if type(dir) is str else bytes,
"unexpected return type")
if pre is not None:
self.assertIs(type(name), str if type(pre) is str else bytes,
"unexpected return type")
if suf is not None:
self.assertIs(type(name), str if type(suf) is str else bytes,
"unexpected return type")
if (dir, pre, suf) == (None, None, None):
self.assertIs(type(name), str, "default return type must be str")
# check for equality of the absolute paths!
self.assertEqual(os.path.abspath(ndir), os.path.abspath(dir),
"file %r not in directory %r" % (name, dir))
self.assertEqual(npre, pre,
"file %r does not begin with %r" % (nbase, pre))
self.assertEqual(nsuf, suf,
"file %r does not end with %r" % (nbase, suf))
nbase = nbase[len(pre):len(nbase)-len(suf)]
check = self.str_check if isinstance(nbase, str) else self.b_check
self.assertTrue(check.match(nbase),
"random characters %r do not match %r"
% (nbase, check.pattern))
class TestExports(BaseTestCase):
def test_exports(self):
# There are no surprising symbols in the tempfile module
dict = tempfile.__dict__
expected = {
"cosmo": 1,
"NamedTemporaryFile" : 1,
"TemporaryFile" : 1,
"mkstemp" : 1,
"mkdtemp" : 1,
"mktemp" : 1,
"TMP_MAX" : 1,
"gettempprefix" : 1,
"gettempprefixb" : 1,
"gettempdir" : 1,
"gettempdirb" : 1,
"tempdir" : 1,
"template" : 1,
"SpooledTemporaryFile" : 1,
"TemporaryDirectory" : 1,
}
unexp = []
for key in dict:
if key[0] != '_' and key not in expected:
unexp.append(key)
self.assertTrue(len(unexp) == 0,
"unexpected keys: %s" % unexp)
class TestRandomNameSequence(BaseTestCase):
"""Test the internal iterator object _RandomNameSequence."""
def setUp(self):
self.r = tempfile._RandomNameSequence()
super().setUp()
def test_get_six_char_str(self):
# _RandomNameSequence returns a six-character string
s = next(self.r)
self.nameCheck(s, '', '', '')
def test_many(self):
# _RandomNameSequence returns no duplicate strings (stochastic)
dict = {}
r = self.r
for i in range(TEST_FILES):
s = next(r)
self.nameCheck(s, '', '', '')
self.assertNotIn(s, dict)
dict[s] = 1
def supports_iter(self):
# _RandomNameSequence supports the iterator protocol
i = 0
r = self.r
for s in r:
i += 1
if i == 20:
break
@unittest.skipUnless(hasattr(os, 'fork'),
"os.fork is required for this test")
def test_process_awareness(self):
# ensure that the random source differs between
# child and parent.
read_fd, write_fd = os.pipe()
pid = None
try:
pid = os.fork()
if not pid:
# child process
os.close(read_fd)
os.write(write_fd, next(self.r).encode("ascii"))
os.close(write_fd)
# bypass the normal exit handlers- leave those to
# the parent.
os._exit(0)
# parent process
parent_value = next(self.r)
child_value = os.read(read_fd, len(parent_value)).decode("ascii")
finally:
if pid:
# best effort to ensure the process can't bleed out
# via any bugs above
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
# Read the process exit status to avoid zombie process
os.waitpid(pid, 0)
os.close(read_fd)
os.close(write_fd)
self.assertNotEqual(child_value, parent_value)
class TestCandidateTempdirList(BaseTestCase):
"""Test the internal function _candidate_tempdir_list."""
def test_nonempty_list(self):
# _candidate_tempdir_list returns a nonempty list of strings
cand = tempfile._candidate_tempdir_list()
self.assertFalse(len(cand) == 0)
for c in cand:
self.assertIsInstance(c, str)
def test_wanted_dirs(self):
# _candidate_tempdir_list contains the expected directories
# Make sure the interesting environment variables are all set.
with support.EnvironmentVarGuard() as env:
for envname in 'TMPDIR', 'TEMP', 'TMP':
dirname = os.getenv(envname)
if not dirname:
env[envname] = os.path.abspath(envname)
cand = tempfile._candidate_tempdir_list()
for envname in 'TMPDIR', 'TEMP', 'TMP':
dirname = os.getenv(envname)
if not dirname: raise ValueError
self.assertIn(dirname, cand)
try:
dirname = os.getcwd()
except (AttributeError, OSError):
dirname = os.curdir
self.assertIn(dirname, cand)
# Not practical to try to verify the presence of OS-specific
# paths in this list.
# We test _get_default_tempdir some more by testing gettempdir.
class TestGetDefaultTempdir(BaseTestCase):
"""Test _get_default_tempdir()."""
def test_no_files_left_behind(self):
# use a private empty directory
with tempfile.TemporaryDirectory() as our_temp_directory:
# force _get_default_tempdir() to consider our empty directory
def our_candidate_list():
return [our_temp_directory]
with support.swap_attr(tempfile, "_candidate_tempdir_list",
our_candidate_list):
# verify our directory is empty after _get_default_tempdir()
tempfile._get_default_tempdir()
self.assertEqual(os.listdir(our_temp_directory), [])
def raise_OSError(*args, **kwargs):
raise OSError()
with support.swap_attr(io, "open", raise_OSError):
# test again with failing io.open()
with self.assertRaises(FileNotFoundError):
tempfile._get_default_tempdir()
self.assertEqual(os.listdir(our_temp_directory), [])
def bad_writer(*args, **kwargs):
fp = orig_open(*args, **kwargs)
fp.write = raise_OSError
return fp
with support.swap_attr(io, "open", bad_writer) as orig_open:
# test again with failing write()
with self.assertRaises(FileNotFoundError):
tempfile._get_default_tempdir()
self.assertEqual(os.listdir(our_temp_directory), [])
class TestGetCandidateNames(BaseTestCase):
"""Test the internal function _get_candidate_names."""
def test_retval(self):
# _get_candidate_names returns a _RandomNameSequence object
obj = tempfile._get_candidate_names()
self.assertIsInstance(obj, tempfile._RandomNameSequence)
def test_same_thing(self):
# _get_candidate_names always returns the same object
a = tempfile._get_candidate_names()
b = tempfile._get_candidate_names()
self.assertTrue(a is b)
@contextlib.contextmanager
def _inside_empty_temp_dir():
dir = tempfile.mkdtemp()
try:
with support.swap_attr(tempfile, 'tempdir', dir):
yield
finally:
support.rmtree(dir)
def _mock_candidate_names(*names):
return support.swap_attr(tempfile,
'_get_candidate_names',
lambda: iter(names))
class TestBadTempdir:
def test_read_only_directory(self):
with _inside_empty_temp_dir():
oldmode = mode = os.stat(tempfile.tempdir).st_mode
mode &= ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
os.chmod(tempfile.tempdir, mode)
try:
if os.access(tempfile.tempdir, os.W_OK):
self.skipTest("can't set the directory read-only")
with self.assertRaises(PermissionError):
self.make_temp()
self.assertEqual(os.listdir(tempfile.tempdir), [])
finally:
os.chmod(tempfile.tempdir, oldmode)
def test_nonexisting_directory(self):
with _inside_empty_temp_dir():
tempdir = os.path.join(tempfile.tempdir, 'nonexistent')
with support.swap_attr(tempfile, 'tempdir', tempdir):
with self.assertRaises(FileNotFoundError):
self.make_temp()
def test_non_directory(self):
with _inside_empty_temp_dir():
tempdir = os.path.join(tempfile.tempdir, 'file')
open(tempdir, 'wb').close()
with support.swap_attr(tempfile, 'tempdir', tempdir):
with self.assertRaises((NotADirectoryError, FileNotFoundError)):
self.make_temp()
class TestMkstempInner(TestBadTempdir, BaseTestCase):
"""Test the internal function _mkstemp_inner."""
class mkstemped:
_bflags = tempfile._bin_openflags
_tflags = tempfile._text_openflags
_close = os.close
_unlink = os.unlink
def __init__(self, dir, pre, suf, bin):
if bin: flags = self._bflags
else: flags = self._tflags
output_type = tempfile._infer_return_type(dir, pre, suf)
(self.fd, self.name) = tempfile._mkstemp_inner(dir, pre, suf, flags, output_type)
def write(self, str):
os.write(self.fd, str)
def __del__(self):
self._close(self.fd)
self._unlink(self.name)
def do_create(self, dir=None, pre=None, suf=None, bin=1):
output_type = tempfile._infer_return_type(dir, pre, suf)
if dir is None:
if output_type is str:
dir = tempfile.gettempdir()
else:
dir = tempfile.gettempdirb()
if pre is None:
pre = output_type()
if suf is None:
suf = output_type()
file = self.mkstemped(dir, pre, suf, bin)
self.nameCheck(file.name, dir, pre, suf)
return file
def test_basic(self):
# _mkstemp_inner can create files
self.do_create().write(b"blat")
self.do_create(pre="a").write(b"blat")
self.do_create(suf="b").write(b"blat")
self.do_create(pre="a", suf="b").write(b"blat")
self.do_create(pre="aa", suf=".txt").write(b"blat")
def test_basic_with_bytes_names(self):
# _mkstemp_inner can create files when given name parts all
# specified as bytes.
dir_b = tempfile.gettempdirb()
self.do_create(dir=dir_b, suf=b"").write(b"blat")
self.do_create(dir=dir_b, pre=b"a").write(b"blat")
self.do_create(dir=dir_b, suf=b"b").write(b"blat")
self.do_create(dir=dir_b, pre=b"a", suf=b"b").write(b"blat")
self.do_create(dir=dir_b, pre=b"aa", suf=b".txt").write(b"blat")
# Can't mix str & binary types in the args.
with self.assertRaises(TypeError):
self.do_create(dir="", suf=b"").write(b"blat")
with self.assertRaises(TypeError):
self.do_create(dir=dir_b, pre="").write(b"blat")
with self.assertRaises(TypeError):
self.do_create(dir=dir_b, pre=b"", suf="").write(b"blat")
def test_basic_many(self):
# _mkstemp_inner can create many files (stochastic)
extant = list(range(TEST_FILES))
for i in extant:
extant[i] = self.do_create(pre="aa")
def test_choose_directory(self):
# _mkstemp_inner can create files in a user-selected directory
dir = tempfile.mkdtemp()
try:
self.do_create(dir=dir).write(b"blat")
finally:
os.rmdir(dir)
@unittest.skipUnless(has_stat, 'os.stat not available')
def test_file_mode(self):
# _mkstemp_inner creates files with the proper mode
file = self.do_create()
mode = stat.S_IMODE(os.stat(file.name).st_mode)
expected = 0o600
if sys.platform == 'win32':
# There's no distinction among 'user', 'group' and 'world';
# replicate the 'user' bits.
user = expected >> 6
expected = user * (1 + 8 + 64)
self.assertEqual(mode, expected)
@unittest.skipUnless(has_spawnl, 'os.spawnl not available')
def test_noinherit(self):
# _mkstemp_inner file handles are not inherited by child processes
if support.verbose:
v="v"
else:
v="q"
file = self.do_create()
self.assertEqual(os.get_inheritable(file.fd), False)
fd = "%d" % file.fd
try:
me = __file__
except NameError:
me = sys.argv[0]
# We have to exec something, so that FD_CLOEXEC will take
# effect. The core of this test is therefore in
# tf_inherit_check.py, which see.
tester = os.path.join(os.path.dirname(os.path.abspath(me)),
"tf_inherit_check.pyc")
# On Windows a spawn* /path/ with embedded spaces shouldn't be quoted,
# but an arg with embedded spaces should be decorated with double
# quotes on each end
if sys.platform == 'win32':
decorated = '"%s"' % sys.executable
tester = '"%s"' % tester
else:
decorated = sys.executable
retval = os.spawnl(os.P_WAIT, sys.executable, decorated, tester, v, fd)
self.assertFalse(retval < 0,
"child process caught fatal signal %d" % -retval)
self.assertFalse(retval > 0, "child process reports failure %d"%retval)
@unittest.skipUnless(has_textmode, "text mode not available")
def test_textmode(self):
# _mkstemp_inner can create files in text mode
# A text file is truncated at the first Ctrl+Z byte
f = self.do_create(bin=0)
f.write(b"blat\x1a")
f.write(b"extra\n")
os.lseek(f.fd, 0, os.SEEK_SET)
self.assertEqual(os.read(f.fd, 20), b"blat")
def make_temp(self):
return tempfile._mkstemp_inner(tempfile.gettempdir(),
tempfile.gettempprefix(),
'',
tempfile._bin_openflags,
str)
def test_collision_with_existing_file(self):
# _mkstemp_inner tries another name when a file with
# the chosen name already exists
with _inside_empty_temp_dir(), \
_mock_candidate_names('aaa', 'aaa', 'bbb'):
(fd1, name1) = self.make_temp()
os.close(fd1)
self.assertTrue(name1.endswith('aaa'))
(fd2, name2) = self.make_temp()
os.close(fd2)
self.assertTrue(name2.endswith('bbb'))
def test_collision_with_existing_directory(self):
# _mkstemp_inner tries another name when a directory with
# the chosen name already exists
with _inside_empty_temp_dir(), \
_mock_candidate_names('aaa', 'aaa', 'bbb'):
dir = tempfile.mkdtemp()
self.assertTrue(dir.endswith('aaa'))
(fd, name) = self.make_temp()
os.close(fd)
self.assertTrue(name.endswith('bbb'))
class TestGetTempPrefix(BaseTestCase):
"""Test gettempprefix()."""
def test_sane_template(self):
# gettempprefix returns a nonempty prefix string
p = tempfile.gettempprefix()
self.assertIsInstance(p, str)
self.assertGreater(len(p), 0)
pb = tempfile.gettempprefixb()
self.assertIsInstance(pb, bytes)
self.assertGreater(len(pb), 0)
def test_usable_template(self):
# gettempprefix returns a usable prefix string
# Create a temp directory, avoiding use of the prefix.
# Then attempt to create a file whose name is
# prefix + 'xxxxxx.xxx' in that directory.
p = tempfile.gettempprefix() + "xxxxxx.xxx"
d = tempfile.mkdtemp(prefix="")
try:
p = os.path.join(d, p)
fd = os.open(p, os.O_RDWR | os.O_CREAT)
os.close(fd)
os.unlink(p)
finally:
os.rmdir(d)
class TestGetTempDir(BaseTestCase):
"""Test gettempdir()."""
def test_directory_exists(self):
# gettempdir returns a directory which exists
for d in (tempfile.gettempdir(), tempfile.gettempdirb()):
self.assertTrue(os.path.isabs(d) or d == os.curdir,
"%r is not an absolute path" % d)
self.assertTrue(os.path.isdir(d),
"%r is not a directory" % d)
def test_directory_writable(self):
# gettempdir returns a directory writable by the user
# sneaky: just instantiate a NamedTemporaryFile, which
# defaults to writing into the directory returned by
# gettempdir.
file = tempfile.NamedTemporaryFile()
file.write(b"blat")
file.close()
def test_same_thing(self):
# gettempdir always returns the same object
a = tempfile.gettempdir()
b = tempfile.gettempdir()
c = tempfile.gettempdirb()
self.assertTrue(a is b)
self.assertNotEqual(type(a), type(c))
self.assertEqual(a, os.fsdecode(c))
def test_case_sensitive(self):
# gettempdir should not flatten its case
# even on a case-insensitive file system
case_sensitive_tempdir = tempfile.mkdtemp("-Temp")
_tempdir, tempfile.tempdir = tempfile.tempdir, None
try:
with support.EnvironmentVarGuard() as env:
# Fake the first env var which is checked as a candidate
env["TMPDIR"] = case_sensitive_tempdir
self.assertEqual(tempfile.gettempdir(), case_sensitive_tempdir)
finally:
tempfile.tempdir = _tempdir
support.rmdir(case_sensitive_tempdir)
class TestMkstemp(BaseTestCase):
"""Test mkstemp()."""
def do_create(self, dir=None, pre=None, suf=None):
output_type = tempfile._infer_return_type(dir, pre, suf)
if dir is None:
if output_type is str:
dir = tempfile.gettempdir()
else:
dir = tempfile.gettempdirb()
if pre is None:
pre = output_type()
if suf is None:
suf = output_type()
(fd, name) = tempfile.mkstemp(dir=dir, prefix=pre, suffix=suf)
(ndir, nbase) = os.path.split(name)
adir = os.path.abspath(dir)
self.assertEqual(adir, ndir,
"Directory '%s' incorrectly returned as '%s'" % (adir, ndir))
try:
self.nameCheck(name, dir, pre, suf)
finally:
os.close(fd)
os.unlink(name)
def test_basic(self):
# mkstemp can create files
self.do_create()
self.do_create(pre="a")
self.do_create(suf="b")
self.do_create(pre="a", suf="b")
self.do_create(pre="aa", suf=".txt")
self.do_create(dir=".")
def test_basic_with_bytes_names(self):
# mkstemp can create files when given name parts all
# specified as bytes.
d = tempfile.gettempdirb()
self.do_create(dir=d, suf=b"")
self.do_create(dir=d, pre=b"a")
self.do_create(dir=d, suf=b"b")
self.do_create(dir=d, pre=b"a", suf=b"b")
self.do_create(dir=d, pre=b"aa", suf=b".txt")
self.do_create(dir=b".")
with self.assertRaises(TypeError):
self.do_create(dir=".", pre=b"aa", suf=b".txt")
with self.assertRaises(TypeError):
self.do_create(dir=b".", pre="aa", suf=b".txt")
with self.assertRaises(TypeError):
self.do_create(dir=b".", pre=b"aa", suf=".txt")
def test_choose_directory(self):
# mkstemp can create directories in a user-selected directory
dir = tempfile.mkdtemp()
try:
self.do_create(dir=dir)
finally:
os.rmdir(dir)
class TestMkdtemp(TestBadTempdir, BaseTestCase):
"""Test mkdtemp()."""
def make_temp(self):
return tempfile.mkdtemp()
def do_create(self, dir=None, pre=None, suf=None):
output_type = tempfile._infer_return_type(dir, pre, suf)
if dir is None:
if output_type is str:
dir = tempfile.gettempdir()
else:
dir = tempfile.gettempdirb()
if pre is None:
pre = output_type()
if suf is None:
suf = output_type()
name = tempfile.mkdtemp(dir=dir, prefix=pre, suffix=suf)
try:
self.nameCheck(name, dir, pre, suf)
return name
except:
os.rmdir(name)
raise
def test_basic(self):
# mkdtemp can create directories
os.rmdir(self.do_create())
os.rmdir(self.do_create(pre="a"))
os.rmdir(self.do_create(suf="b"))
os.rmdir(self.do_create(pre="a", suf="b"))
os.rmdir(self.do_create(pre="aa", suf=".txt"))
def test_basic_with_bytes_names(self):
# mkdtemp can create directories when given all binary parts
d = tempfile.gettempdirb()
os.rmdir(self.do_create(dir=d))
os.rmdir(self.do_create(dir=d, pre=b"a"))
os.rmdir(self.do_create(dir=d, suf=b"b"))
os.rmdir(self.do_create(dir=d, pre=b"a", suf=b"b"))
os.rmdir(self.do_create(dir=d, pre=b"aa", suf=b".txt"))
with self.assertRaises(TypeError):
os.rmdir(self.do_create(dir=d, pre="aa", suf=b".txt"))
with self.assertRaises(TypeError):
os.rmdir(self.do_create(dir=d, pre=b"aa", suf=".txt"))
with self.assertRaises(TypeError):
os.rmdir(self.do_create(dir="", pre=b"aa", suf=b".txt"))
def test_basic_many(self):
# mkdtemp can create many directories (stochastic)
extant = list(range(TEST_FILES))
try:
for i in extant:
extant[i] = self.do_create(pre="aa")
finally:
for i in extant:
if(isinstance(i, str)):
os.rmdir(i)
def test_choose_directory(self):
# mkdtemp can create directories in a user-selected directory
dir = tempfile.mkdtemp()
try:
os.rmdir(self.do_create(dir=dir))
finally:
os.rmdir(dir)
@unittest.skipUnless(has_stat, 'os.stat not available')
def test_mode(self):
# mkdtemp creates directories with the proper mode
dir = self.do_create()
try:
mode = stat.S_IMODE(os.stat(dir).st_mode)
mode &= 0o777 # Mask off sticky bits inherited from /tmp
expected = 0o700
if sys.platform == 'win32':
# There's no distinction among 'user', 'group' and 'world';
# replicate the 'user' bits.
user = expected >> 6
expected = user * (1 + 8 + 64)
self.assertEqual(mode, expected)
finally:
os.rmdir(dir)
def test_collision_with_existing_file(self):
# mkdtemp tries another name when a file with
# the chosen name already exists
with _inside_empty_temp_dir(), \
_mock_candidate_names('aaa', 'aaa', 'bbb'):
file = tempfile.NamedTemporaryFile(delete=False)
file.close()
self.assertTrue(file.name.endswith('aaa'))
dir = tempfile.mkdtemp()
self.assertTrue(dir.endswith('bbb'))
def test_collision_with_existing_directory(self):
# mkdtemp tries another name when a directory with
# the chosen name already exists
with _inside_empty_temp_dir(), \
_mock_candidate_names('aaa', 'aaa', 'bbb'):
dir1 = tempfile.mkdtemp()
self.assertTrue(dir1.endswith('aaa'))
dir2 = tempfile.mkdtemp()
self.assertTrue(dir2.endswith('bbb'))
class TestMktemp(BaseTestCase):
"""Test mktemp()."""
# For safety, all use of mktemp must occur in a private directory.
# We must also suppress the RuntimeWarning it generates.
def setUp(self):
self.dir = tempfile.mkdtemp()
super().setUp()
def tearDown(self):
if self.dir:
os.rmdir(self.dir)
self.dir = None
super().tearDown()
class mktemped:
_unlink = os.unlink
_bflags = tempfile._bin_openflags
def __init__(self, dir, pre, suf):
self.name = tempfile.mktemp(dir=dir, prefix=pre, suffix=suf)
# Create the file. This will raise an exception if it's
# mysteriously appeared in the meanwhile.
os.close(os.open(self.name, self._bflags, 0o600))
def __del__(self):
self._unlink(self.name)
def do_create(self, pre="", suf=""):
file = self.mktemped(self.dir, pre, suf)
self.nameCheck(file.name, self.dir, pre, suf)
return file
def test_basic(self):
# mktemp can choose usable file names
self.do_create()
self.do_create(pre="a")
self.do_create(suf="b")
self.do_create(pre="a", suf="b")
self.do_create(pre="aa", suf=".txt")
def test_many(self):
# mktemp can choose many usable file names (stochastic)
extant = list(range(TEST_FILES))
for i in extant:
extant[i] = self.do_create(pre="aa")
## def test_warning(self):
## # mktemp issues a warning when used
## warnings.filterwarnings("error",
## category=RuntimeWarning,
## message="mktemp")
## self.assertRaises(RuntimeWarning,
## tempfile.mktemp, dir=self.dir)
# We test _TemporaryFileWrapper by testing NamedTemporaryFile.
class TestNamedTemporaryFile(BaseTestCase):
"""Test NamedTemporaryFile()."""
def do_create(self, dir=None, pre="", suf="", delete=True):
if dir is None:
dir = tempfile.gettempdir()
file = tempfile.NamedTemporaryFile(dir=dir, prefix=pre, suffix=suf,
delete=delete)
self.nameCheck(file.name, dir, pre, suf)
return file
def test_basic(self):
# NamedTemporaryFile can create files
self.do_create()
self.do_create(pre="a")
self.do_create(suf="b")
self.do_create(pre="a", suf="b")
self.do_create(pre="aa", suf=".txt")
def test_method_lookup(self):
# Issue #18879: Looking up a temporary file method should keep it
# alive long enough.
f = self.do_create()
wr = weakref.ref(f)
write = f.write
write2 = f.write
del f
write(b'foo')
del write
write2(b'bar')
del write2
if support.check_impl_detail(cpython=True):
# No reference cycle was created.
self.assertIsNone(wr())
def test_iter(self):
# Issue #23700: getting iterator from a temporary file should keep
# it alive as long as it's being iterated over
lines = [b'spam\n', b'eggs\n', b'beans\n']
def make_file():
f = tempfile.NamedTemporaryFile(mode='w+b')
f.write(b''.join(lines))
f.seek(0)
return f
for i, l in enumerate(make_file()):
self.assertEqual(l, lines[i])
self.assertEqual(i, len(lines) - 1)
def test_creates_named(self):
# NamedTemporaryFile creates files with names
f = tempfile.NamedTemporaryFile()
self.assertTrue(os.path.exists(f.name),
"NamedTemporaryFile %s does not exist" % f.name)
def test_del_on_close(self):
# A NamedTemporaryFile is deleted when closed
dir = tempfile.mkdtemp()
try:
f = tempfile.NamedTemporaryFile(dir=dir)
f.write(b'blat')
f.close()
self.assertFalse(os.path.exists(f.name),
"NamedTemporaryFile %s exists after close" % f.name)
finally:
os.rmdir(dir)
def test_dis_del_on_close(self):
# Tests that delete-on-close can be disabled
dir = tempfile.mkdtemp()
tmp = None
try:
f = tempfile.NamedTemporaryFile(dir=dir, delete=False)
tmp = f.name
f.write(b'blat')
f.close()
self.assertTrue(os.path.exists(f.name),
"NamedTemporaryFile %s missing after close" % f.name)
finally:
if tmp is not None:
os.unlink(tmp)
os.rmdir(dir)
def test_multiple_close(self):
# A NamedTemporaryFile can be closed many times without error
f = tempfile.NamedTemporaryFile()
f.write(b'abc\n')
f.close()
f.close()
f.close()
def test_context_manager(self):
# A NamedTemporaryFile can be used as a context manager
with tempfile.NamedTemporaryFile() as f:
self.assertTrue(os.path.exists(f.name))
self.assertFalse(os.path.exists(f.name))
def use_closed():
with f:
pass
self.assertRaises(ValueError, use_closed)
def test_no_leak_fd(self):
# Issue #21058: don't leak file descriptor when io.open() fails
closed = []
os_close = os.close
def close(fd):
closed.append(fd)
os_close(fd)
with mock.patch('os.close', side_effect=close):
with mock.patch('io.open', side_effect=ValueError):
self.assertRaises(ValueError, tempfile.NamedTemporaryFile)
self.assertEqual(len(closed), 1)
def test_bad_mode(self):
dir = tempfile.mkdtemp()
self.addCleanup(support.rmtree, dir)
with self.assertRaises(ValueError):
tempfile.NamedTemporaryFile(mode='wr', dir=dir)
with self.assertRaises(TypeError):
tempfile.NamedTemporaryFile(mode=2, dir=dir)
self.assertEqual(os.listdir(dir), [])
# How to test the mode and bufsize parameters?
class TestSpooledTemporaryFile(BaseTestCase):
"""Test SpooledTemporaryFile()."""
def do_create(self, max_size=0, dir=None, pre="", suf=""):
if dir is None:
dir = tempfile.gettempdir()
file = tempfile.SpooledTemporaryFile(max_size=max_size, dir=dir, prefix=pre, suffix=suf)
return file
def test_basic(self):
# SpooledTemporaryFile can create files
f = self.do_create()
self.assertFalse(f._rolled)
f = self.do_create(max_size=100, pre="a", suf=".txt")
self.assertFalse(f._rolled)
def test_del_on_close(self):
# A SpooledTemporaryFile is deleted when closed
dir = tempfile.mkdtemp()
try:
f = tempfile.SpooledTemporaryFile(max_size=10, dir=dir)
self.assertFalse(f._rolled)
f.write(b'blat ' * 5)
self.assertTrue(f._rolled)
filename = f.name
f.close()
self.assertFalse(isinstance(filename, str) and os.path.exists(filename),
"SpooledTemporaryFile %s exists after close" % filename)
finally:
os.rmdir(dir)
def test_rewrite_small(self):
# A SpooledTemporaryFile can be written to multiple within the max_size
f = self.do_create(max_size=30)
self.assertFalse(f._rolled)
for i in range(5):
f.seek(0, 0)
f.write(b'x' * 20)
self.assertFalse(f._rolled)
def test_write_sequential(self):
# A SpooledTemporaryFile should hold exactly max_size bytes, and roll
# over afterward
f = self.do_create(max_size=30)
self.assertFalse(f._rolled)
f.write(b'x' * 20)
self.assertFalse(f._rolled)
f.write(b'x' * 10)
self.assertFalse(f._rolled)
f.write(b'x')
self.assertTrue(f._rolled)
def test_writelines(self):
# Verify writelines with a SpooledTemporaryFile
f = self.do_create()
f.writelines((b'x', b'y', b'z'))
f.seek(0)
buf = f.read()
self.assertEqual(buf, b'xyz')
def test_writelines_sequential(self):
# A SpooledTemporaryFile should hold exactly max_size bytes, and roll
# over afterward
f = self.do_create(max_size=35)
f.writelines((b'x' * 20, b'x' * 10, b'x' * 5))
self.assertFalse(f._rolled)
f.write(b'x')
self.assertTrue(f._rolled)
def test_sparse(self):
# A SpooledTemporaryFile that is written late in the file will extend
# when that occurs
f = self.do_create(max_size=30)
self.assertFalse(f._rolled)
f.seek(100, 0)
self.assertFalse(f._rolled)
f.write(b'x')
self.assertTrue(f._rolled)
def test_fileno(self):
# A SpooledTemporaryFile should roll over to a real file on fileno()
f = self.do_create(max_size=30)
self.assertFalse(f._rolled)
self.assertTrue(f.fileno() > 0)
self.assertTrue(f._rolled)
def test_multiple_close_before_rollover(self):
# A SpooledTemporaryFile can be closed many times without error
f = tempfile.SpooledTemporaryFile()
f.write(b'abc\n')
self.assertFalse(f._rolled)
f.close()
f.close()
f.close()
def test_multiple_close_after_rollover(self):
# A SpooledTemporaryFile can be closed many times without error
f = tempfile.SpooledTemporaryFile(max_size=1)
f.write(b'abc\n')
self.assertTrue(f._rolled)
f.close()
f.close()
f.close()
def test_bound_methods(self):
# It should be OK to steal a bound method from a SpooledTemporaryFile
# and use it independently; when the file rolls over, those bound
# methods should continue to function
f = self.do_create(max_size=30)
read = f.read
write = f.write
seek = f.seek
write(b"a" * 35)
write(b"b" * 35)
seek(0, 0)
self.assertEqual(read(70), b'a'*35 + b'b'*35)
def test_properties(self):
f = tempfile.SpooledTemporaryFile(max_size=10)
f.write(b'x' * 10)
self.assertFalse(f._rolled)
self.assertEqual(f.mode, 'w+b')
self.assertIsNone(f.name)
with self.assertRaises(AttributeError):
f.newlines
with self.assertRaises(AttributeError):
f.encoding
f.write(b'x')
self.assertTrue(f._rolled)
self.assertEqual(f.mode, 'rb+')
self.assertIsNotNone(f.name)
with self.assertRaises(AttributeError):
f.newlines
with self.assertRaises(AttributeError):
f.encoding
def test_text_mode(self):
# Creating a SpooledTemporaryFile with a text mode should produce
# a file object reading and writing (Unicode) text strings.
f = tempfile.SpooledTemporaryFile(mode='w+', max_size=10)
f.write("abc\n")
f.seek(0)
self.assertEqual(f.read(), "abc\n")
f.write("def\n")
f.seek(0)
self.assertEqual(f.read(), "abc\ndef\n")
self.assertFalse(f._rolled)
self.assertEqual(f.mode, 'w+')
self.assertIsNone(f.name)
self.assertIsNone(f.newlines)
self.assertIsNone(f.encoding)
f.write("xyzzy\n")
f.seek(0)
self.assertEqual(f.read(), "abc\ndef\nxyzzy\n")
# Check that Ctrl+Z doesn't truncate the file
f.write("foo\x1abar\n")
f.seek(0)
self.assertEqual(f.read(), "abc\ndef\nxyzzy\nfoo\x1abar\n")
self.assertTrue(f._rolled)
self.assertEqual(f.mode, 'w+')
self.assertIsNotNone(f.name)
self.assertEqual(f.newlines, os.linesep)
self.assertIsNotNone(f.encoding)
def test_text_newline_and_encoding(self):
f = tempfile.SpooledTemporaryFile(mode='w+', max_size=10,
newline='', encoding='utf-8')
f.write("\u039B\r\n")
f.seek(0)
self.assertEqual(f.read(), "\u039B\r\n")
self.assertFalse(f._rolled)
self.assertEqual(f.mode, 'w+')
self.assertIsNone(f.name)
self.assertIsNone(f.newlines)
self.assertIsNone(f.encoding)
f.write("\u039B" * 20 + "\r\n")
f.seek(0)
self.assertEqual(f.read(), "\u039B\r\n" + ("\u039B" * 20) + "\r\n")
self.assertTrue(f._rolled)
self.assertEqual(f.mode, 'w+')
self.assertIsNotNone(f.name)
self.assertIsNotNone(f.newlines)
self.assertEqual(f.encoding, 'utf-8')
def test_context_manager_before_rollover(self):
# A SpooledTemporaryFile can be used as a context manager
with tempfile.SpooledTemporaryFile(max_size=1) as f:
self.assertFalse(f._rolled)
self.assertFalse(f.closed)
self.assertTrue(f.closed)
def use_closed():
with f:
pass
self.assertRaises(ValueError, use_closed)
def test_context_manager_during_rollover(self):
# A SpooledTemporaryFile can be used as a context manager
with tempfile.SpooledTemporaryFile(max_size=1) as f:
self.assertFalse(f._rolled)
f.write(b'abc\n')
f.flush()
self.assertTrue(f._rolled)
self.assertFalse(f.closed)
self.assertTrue(f.closed)
def use_closed():
with f:
pass
self.assertRaises(ValueError, use_closed)
def test_context_manager_after_rollover(self):
# A SpooledTemporaryFile can be used as a context manager
f = tempfile.SpooledTemporaryFile(max_size=1)
f.write(b'abc\n')
f.flush()
self.assertTrue(f._rolled)
with f:
self.assertFalse(f.closed)
self.assertTrue(f.closed)
def use_closed():
with f:
pass
self.assertRaises(ValueError, use_closed)
def test_truncate_with_size_parameter(self):
# A SpooledTemporaryFile can be truncated to zero size
f = tempfile.SpooledTemporaryFile(max_size=10)
f.write(b'abcdefg\n')
f.seek(0)
f.truncate()
self.assertFalse(f._rolled)
self.assertEqual(f._file.getvalue(), b'')
# A SpooledTemporaryFile can be truncated to a specific size
f = tempfile.SpooledTemporaryFile(max_size=10)
f.write(b'abcdefg\n')
f.truncate(4)
self.assertFalse(f._rolled)
self.assertEqual(f._file.getvalue(), b'abcd')
# A SpooledTemporaryFile rolls over if truncated to large size
f = tempfile.SpooledTemporaryFile(max_size=10)
f.write(b'abcdefg\n')
f.truncate(20)
self.assertTrue(f._rolled)
if has_stat:
self.assertEqual(os.fstat(f.fileno()).st_size, 20)
if tempfile.NamedTemporaryFile is not tempfile.TemporaryFile:
class TestTemporaryFile(BaseTestCase):
"""Test TemporaryFile()."""
def test_basic(self):
# TemporaryFile can create files
# No point in testing the name params - the file has no name.
tempfile.TemporaryFile()
def test_has_no_name(self):
# TemporaryFile creates files with no names (on this system)
dir = tempfile.mkdtemp()
f = tempfile.TemporaryFile(dir=dir)
f.write(b'blat')
# Sneaky: because this file has no name, it should not prevent
# us from removing the directory it was created in.
try:
os.rmdir(dir)
except:
# cleanup
f.close()
os.rmdir(dir)
raise
def test_multiple_close(self):
# A TemporaryFile can be closed many times without error
f = tempfile.TemporaryFile()
f.write(b'abc\n')
f.close()
f.close()
f.close()
# How to test the mode and bufsize parameters?
def test_mode_and_encoding(self):
def roundtrip(input, *args, **kwargs):
with tempfile.TemporaryFile(*args, **kwargs) as fileobj:
fileobj.write(input)
fileobj.seek(0)
self.assertEqual(input, fileobj.read())
roundtrip(b"1234", "w+b")
roundtrip("abdc\n", "w+")
# roundtrip("\u039B", "w+", encoding="utf-16")
roundtrip("foo\r\n", "w+", newline="")
def test_no_leak_fd(self):
# Issue #21058: don't leak file descriptor when io.open() fails
closed = []
os_close = os.close
def close(fd):
closed.append(fd)
os_close(fd)
with mock.patch('os.close', side_effect=close):
with mock.patch('io.open', side_effect=ValueError):
self.assertRaises(ValueError, tempfile.TemporaryFile)
self.assertEqual(len(closed), 1)
# Helper for test_del_on_shutdown
class NulledModules:
def __init__(self, *modules):
self.refs = [mod.__dict__ for mod in modules]
self.contents = [ref.copy() for ref in self.refs]
def __enter__(self):
for d in self.refs:
for key in d:
d[key] = None
def __exit__(self, *exc_info):
for d, c in zip(self.refs, self.contents):
d.clear()
d.update(c)
class TestTemporaryDirectory(BaseTestCase):
"""Test TemporaryDirectory()."""
def do_create(self, dir=None, pre="", suf="", recurse=1):
if dir is None:
dir = tempfile.gettempdir()
tmp = tempfile.TemporaryDirectory(dir=dir, prefix=pre, suffix=suf)
self.nameCheck(tmp.name, dir, pre, suf)
# Create a subdirectory and some files
if recurse:
d1 = self.do_create(tmp.name, pre, suf, recurse-1)
d1.name = None
with open(os.path.join(tmp.name, "test.txt"), "wb") as f:
f.write(b"Hello world!")
return tmp
def test_mkdtemp_failure(self):
# Check no additional exception if mkdtemp fails
# Previously would raise AttributeError instead
# (noted as part of Issue #10188)
with tempfile.TemporaryDirectory() as nonexistent:
pass
with self.assertRaises(FileNotFoundError) as cm:
tempfile.TemporaryDirectory(dir=nonexistent)
self.assertEqual(cm.exception.errno, errno.ENOENT)
def test_explicit_cleanup(self):
# A TemporaryDirectory is deleted when cleaned up
dir = tempfile.mkdtemp()
try:
d = self.do_create(dir=dir)
self.assertTrue(os.path.exists(d.name),
"TemporaryDirectory %s does not exist" % d.name)
d.cleanup()
self.assertFalse(os.path.exists(d.name),
"TemporaryDirectory %s exists after cleanup" % d.name)
finally:
os.rmdir(dir)
@support.skip_unless_symlink
def test_cleanup_with_symlink_to_a_directory(self):
# cleanup() should not follow symlinks to directories (issue #12464)
d1 = self.do_create()
d2 = self.do_create(recurse=0)
# Symlink d1/foo -> d2
os.symlink(d2.name, os.path.join(d1.name, "foo"))
# This call to cleanup() should not follow the "foo" symlink
d1.cleanup()
self.assertFalse(os.path.exists(d1.name),
"TemporaryDirectory %s exists after cleanup" % d1.name)
self.assertTrue(os.path.exists(d2.name),
"Directory pointed to by a symlink was deleted")
self.assertEqual(os.listdir(d2.name), ['test.txt'],
"Contents of the directory pointed to by a symlink "
"were deleted")
d2.cleanup()
@support.cpython_only
def test_del_on_collection(self):
# A TemporaryDirectory is deleted when garbage collected
dir = tempfile.mkdtemp()
try:
d = self.do_create(dir=dir)
name = d.name
del d # Rely on refcounting to invoke __del__
self.assertFalse(os.path.exists(name),
"TemporaryDirectory %s exists after __del__" % name)
finally:
os.rmdir(dir)
def test_del_on_shutdown(self):
# A TemporaryDirectory may be cleaned up during shutdown
with self.do_create() as dir:
for mod in ('builtins', 'os', 'shutil', 'sys', 'tempfile', 'warnings'):
code = """if True:
import builtins
import os
import shutil
import sys
import tempfile
import warnings
tmp = tempfile.TemporaryDirectory(dir={dir!r})
sys.stdout.buffer.write(tmp.name.encode())
tmp2 = os.path.join(tmp.name, 'test_dir')
os.mkdir(tmp2)
with open(os.path.join(tmp2, "test.txt"), "w") as f:
f.write("Hello world!")
{mod}.tmp = tmp
warnings.filterwarnings("always", category=ResourceWarning)
""".format(dir=dir, mod=mod)
rc, out, err = script_helper.assert_python_ok("-c", code)
tmp_name = out.decode().strip()
self.assertFalse(os.path.exists(tmp_name),
"TemporaryDirectory %s exists after cleanup" % tmp_name)
err = err.decode('utf-8', 'backslashreplace')
self.assertNotIn("Exception ", err)
self.assertIn("ResourceWarning: Implicitly cleaning up", err)
def test_exit_on_shutdown(self):
# Issue #22427
with self.do_create() as dir:
code = """if True:
import sys
import tempfile
import warnings
def generator():
with tempfile.TemporaryDirectory(dir={dir!r}) as tmp:
yield tmp
g = generator()
sys.stdout.buffer.write(next(g).encode())
warnings.filterwarnings("always", category=ResourceWarning)
""".format(dir=dir)
rc, out, err = script_helper.assert_python_ok("-c", code)
tmp_name = out.decode().strip()
self.assertFalse(os.path.exists(tmp_name),
"TemporaryDirectory %s exists after cleanup" % tmp_name)
err = err.decode('utf-8', 'backslashreplace')
self.assertNotIn("Exception ", err)
self.assertIn("ResourceWarning: Implicitly cleaning up", err)
def test_warnings_on_cleanup(self):
# ResourceWarning will be triggered by __del__
with self.do_create() as dir:
d = self.do_create(dir=dir, recurse=3)
name = d.name
# Check for the resource warning
with support.check_warnings(('Implicitly', ResourceWarning), quiet=False):
warnings.filterwarnings("always", category=ResourceWarning)
del d
support.gc_collect()
self.assertFalse(os.path.exists(name),
"TemporaryDirectory %s exists after __del__" % name)
def test_multiple_close(self):
# Can be cleaned-up many times without error
d = self.do_create()
d.cleanup()
d.cleanup()
d.cleanup()
def test_context_manager(self):
# Can be used as a context manager
d = self.do_create()
with d as name:
self.assertTrue(os.path.exists(name))
self.assertEqual(name, d.name)
self.assertFalse(os.path.exists(name))
if __name__ == "__main__":
unittest.main()
| 51,703 | 1,464 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_symbol.py | import unittest
from test import support
import os
import sys
import subprocess
SYMBOL_FILE = support.findfile('symbol.py')
GRAMMAR_FILE = os.path.join(os.path.dirname(__file__),
'..', '..', 'Include', 'graminit.h')
TEST_PY_FILE = 'symbol_test.py'
class TestSymbolGeneration(unittest.TestCase):
def _copy_file_without_generated_symbols(self, source_file, dest_file):
with open(source_file) as fp:
lines = fp.readlines()
with open(dest_file, 'w') as fp:
fp.writelines(lines[:lines.index("#--start constants--\n") + 1])
fp.writelines(lines[lines.index("#--end constants--\n"):])
def _generate_symbols(self, grammar_file, target_symbol_py_file):
proc = subprocess.Popen([sys.executable,
SYMBOL_FILE,
grammar_file,
target_symbol_py_file], stderr=subprocess.PIPE)
stderr = proc.communicate()[1]
return proc.returncode, stderr
def compare_files(self, file1, file2):
with open(file1) as fp:
lines1 = fp.readlines()
with open(file2) as fp:
lines2 = fp.readlines()
self.assertEqual(lines1, lines2)
@unittest.skipIf(not os.path.exists(GRAMMAR_FILE),
'test only works from source build directory')
def test_real_grammar_and_symbol_file(self):
output = support.TESTFN
self.addCleanup(support.unlink, output)
self._copy_file_without_generated_symbols(SYMBOL_FILE, output)
exitcode, stderr = self._generate_symbols(GRAMMAR_FILE, output)
self.assertEqual(b'', stderr)
self.assertEqual(0, exitcode)
self.compare_files(SYMBOL_FILE, output)
if __name__ == "__main__":
unittest.main()
| 1,880 | 55 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_select.py | import errno
import os
import select
import cosmo
import sys
import unittest
from test import support
@unittest.skipIf((sys.platform[:3]=='win'),
"can't easily test on this system")
class SelectTestCase(unittest.TestCase):
class Nope:
pass
class Almost:
def fileno(self):
return 'fileno'
def test_error_conditions(self):
self.assertRaises(TypeError, select.select, 1, 2, 3)
self.assertRaises(TypeError, select.select, [self.Nope()], [], [])
self.assertRaises(TypeError, select.select, [self.Almost()], [], [])
self.assertRaises(TypeError, select.select, [], [], [], "not a number")
self.assertRaises(ValueError, select.select, [], [], [], -1)
# Issue #12367: http://www.freebsd.org/cgi/query-pr.cgi?pr=kern/155606
@unittest.skipIf(cosmo.MODE in ('tiny', 'rel'),
"fails on missing .py file in rel mode")
@unittest.skipIf(sys.platform.startswith('freebsd'),
'skip because of a FreeBSD bug: kern/155606')
def test_errno(self):
with open(__file__, 'rb') as fp:
fd = fp.fileno()
fp.close()
try:
select.select([fd], [], [], 0)
except OSError as err:
self.assertEqual(err.errno, errno.EBADF)
else:
self.fail("exception not raised")
def test_returned_list_identity(self):
# See issue #8329
r, w, x = select.select([], [], [], 1)
self.assertIsNot(r, w)
self.assertIsNot(r, x)
self.assertIsNot(w, x)
@unittest.skip("[jart] this test sucks")
def test_select(self):
cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done'
p = os.popen(cmd, 'r')
for tout in (0, 1, 2, 4, 8, 16) + (None,)*10:
if support.verbose:
print('timeout =', tout)
rfd, wfd, xfd = select.select([p], [], [], tout)
if (rfd, wfd, xfd) == ([], [], []):
continue
if (rfd, wfd, xfd) == ([p], [], []):
line = p.readline()
if support.verbose:
print(repr(line))
if not line:
if support.verbose:
print('EOF')
break
continue
self.fail('Unexpected return values from select():', rfd, wfd, xfd)
p.close()
# Issue 16230: Crash on select resized list
def test_select_mutated(self):
a = []
class F:
def fileno(self):
del a[-1]
return sys.__stdout__.fileno()
a[:] = [F()] * 10
self.assertEqual(select.select([], a, []), ([], a[:5], []))
def tearDownModule():
support.reap_children()
if __name__ == "__main__":
unittest.main()
| 2,882 | 87 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_structseq.py | import os
import time
import unittest
class StructSeqTest(unittest.TestCase):
def test_tuple(self):
t = time.gmtime()
self.assertIsInstance(t, tuple)
astuple = tuple(t)
self.assertEqual(len(t), len(astuple))
self.assertEqual(t, astuple)
# Check that slicing works the same way; at one point, slicing t[i:j] with
# 0 < i < j could produce NULLs in the result.
for i in range(-len(t), len(t)):
self.assertEqual(t[i:], astuple[i:])
for j in range(-len(t), len(t)):
self.assertEqual(t[i:j], astuple[i:j])
for j in range(-len(t), len(t)):
self.assertEqual(t[:j], astuple[:j])
self.assertRaises(IndexError, t.__getitem__, -len(t)-1)
self.assertRaises(IndexError, t.__getitem__, len(t))
for i in range(-len(t), len(t)-1):
self.assertEqual(t[i], astuple[i])
def test_repr(self):
t = time.gmtime()
self.assertTrue(repr(t))
t = time.gmtime(0)
self.assertEqual(repr(t),
"time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, "
"tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)")
# os.stat() gives a complicated struct sequence.
st = os.stat(__file__)
rep = repr(st)
self.assertTrue(rep.startswith("os.stat_result"))
self.assertIn("st_mode=", rep)
self.assertIn("st_ino=", rep)
self.assertIn("st_dev=", rep)
def test_concat(self):
t1 = time.gmtime()
t2 = t1 + tuple(t1)
for i in range(len(t1)):
self.assertEqual(t2[i], t2[i+len(t1)])
def test_repeat(self):
t1 = time.gmtime()
t2 = 3 * t1
for i in range(len(t1)):
self.assertEqual(t2[i], t2[i+len(t1)])
self.assertEqual(t2[i], t2[i+2*len(t1)])
def test_contains(self):
t1 = time.gmtime()
for item in t1:
self.assertIn(item, t1)
self.assertNotIn(-42, t1)
def test_hash(self):
t1 = time.gmtime()
self.assertEqual(hash(t1), hash(tuple(t1)))
def test_cmp(self):
t1 = time.gmtime()
t2 = type(t1)(t1)
self.assertEqual(t1, t2)
self.assertTrue(not (t1 < t2))
self.assertTrue(t1 <= t2)
self.assertTrue(not (t1 > t2))
self.assertTrue(t1 >= t2)
self.assertTrue(not (t1 != t2))
def test_fields(self):
t = time.gmtime()
self.assertEqual(len(t), t.n_sequence_fields)
self.assertEqual(t.n_unnamed_fields, 0)
self.assertEqual(t.n_fields, time._STRUCT_TM_ITEMS)
def test_constructor(self):
t = time.struct_time
self.assertRaises(TypeError, t)
self.assertRaises(TypeError, t, None)
self.assertRaises(TypeError, t, "123")
self.assertRaises(TypeError, t, "123", dict={})
self.assertRaises(TypeError, t, "123456789", dict=None)
s = "123456789"
self.assertEqual("".join(t(s)), s)
def test_eviltuple(self):
class Exc(Exception):
pass
# Devious code could crash structseqs' constructors
class C:
def __getitem__(self, i):
raise Exc
def __len__(self):
return 9
self.assertRaises(Exc, time.struct_time, C())
def test_reduce(self):
t = time.gmtime()
x = t.__reduce__()
def test_extended_getslice(self):
# Test extended slicing by comparing with list slicing.
t = time.gmtime()
L = list(t)
indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300)
for start in indices:
for stop in indices:
# Skip step 0 (invalid)
for step in indices[1:]:
self.assertEqual(list(t[start:stop:step]),
L[start:stop:step])
if __name__ == "__main__":
unittest.main()
| 3,964 | 127 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_hashlib.py | # Test hashlib module
#
# $Id$
#
# Copyright (C) 2005-2010 Gregory P. Smith ([email protected])
# Licensed to PSF under a Contributor Agreement.
#
import array
from binascii import unhexlify
import hashlib
import importlib
import itertools
import os
import sys
try:
import _thread
import threading
except ImportError:
threading = None
import unittest
import warnings
from test import support
from test.support import _4G, bigmemtest, import_fresh_module
from http.client import HTTPException
# if __name__ == 'PYOBJ.COM':
# import _sha3 # what a horror show
# Were we compiled --with-pydebug or with #define Py_DEBUG?
COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
# [jart] wut
c_hashlib = import_fresh_module('hashlib', fresh=['_hashlib'])
py_hashlib = import_fresh_module('hashlib', blocked=['_hashlib'])
try:
import _sha3
except ImportError:
_sha3 = None
requires_sha3 = unittest.skipUnless(_sha3, 'requires _sha3')
def hexstr(s):
assert isinstance(s, bytes), repr(s)
h = "0123456789abcdef"
r = ''
for i in s:
r += h[(i >> 4) & 0xF] + h[i & 0xF]
return r
def read_vectors(hash_name):
# [jart] modified to not phone home
with open('/zip/.python/test/%s.txt' % (hash_name)) as testdata:
for line in testdata:
line = line.strip()
if line.startswith('#') or not line:
continue
parts = line.split(',')
parts[0] = bytes.fromhex(parts[0])
yield parts
class HashLibTestCase(unittest.TestCase):
shakes = {'shake_128', 'shake_256'}
supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
'sha224', 'SHA224', 'sha256', 'SHA256',
'sha384', 'SHA384', 'sha512', 'SHA512',
# 'sha3_224', 'sha3_256', 'sha3_384',
# 'sha3_512', 'shake_128', 'shake_256',
'blake2b256',
)
# Issue #14693: fallback modules are always compiled under POSIX
# [jart] don't care about sha3 don't care don't care
_warn_on_extension_import = False # os.name == 'posix' or COMPILED_WITH_PYDEBUG
def _conditional_import_module(self, module_name):
"""Import a module and return a reference to it or None on failure."""
try:
return importlib.import_module(module_name)
except ModuleNotFoundError as error:
if self._warn_on_extension_import:
warnings.warn('Did a C extension fail to compile? %s' % error)
return None
def __init__(self, *args, **kwargs):
algorithms = set()
for algorithm in self.supported_hash_names:
algorithms.add(algorithm.lower())
self.constructors_to_test = {}
for algorithm in algorithms:
self.constructors_to_test[algorithm] = set()
# For each algorithm, test the direct constructor and the use
# of hashlib.new given the algorithm name.
for algorithm, constructors in self.constructors_to_test.items():
constructors.add(getattr(hashlib, algorithm))
def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm, **kwargs):
if data is None:
return hashlib.new(_alg, **kwargs)
return hashlib.new(_alg, data, **kwargs)
constructors.add(_test_algorithm_via_hashlib_new)
_hashlib = self._conditional_import_module('_hashlib')
if _hashlib:
# These two algorithms should always be present when this module
# is compiled. If not, something was compiled wrong.
self.assertTrue(hasattr(_hashlib, 'mbedtls_md5'))
self.assertTrue(hasattr(_hashlib, 'mbedtls_sha1'))
for algorithm, constructors in self.constructors_to_test.items():
constructor = getattr(_hashlib, 'mbedtls_'+algorithm, None)
if constructor:
constructors.add(constructor)
def add_builtin_constructor(name):
constructor = getattr(hashlib, "__get_builtin_constructor")(name)
self.constructors_to_test[name].add(constructor)
_md5 = self._conditional_import_module('_md5')
if _md5:
add_builtin_constructor('md5')
_sha1 = self._conditional_import_module('_sha1')
if _sha1:
add_builtin_constructor('sha1')
_sha256 = self._conditional_import_module('_sha256')
if _sha256:
add_builtin_constructor('sha224')
add_builtin_constructor('sha256')
_sha512 = self._conditional_import_module('_sha512')
if _sha512:
add_builtin_constructor('sha384')
add_builtin_constructor('sha512')
_sha3 = self._conditional_import_module('_sha3')
if _sha3:
add_builtin_constructor('sha3_224')
add_builtin_constructor('sha3_256')
add_builtin_constructor('sha3_384')
add_builtin_constructor('sha3_512')
add_builtin_constructor('shake_128')
add_builtin_constructor('shake_256')
super(HashLibTestCase, self).__init__(*args, **kwargs)
@property
def hash_constructors(self):
constructors = self.constructors_to_test.values()
return itertools.chain.from_iterable(constructors)
@support.refcount_test
@unittest.skipIf(c_hashlib is None, 'Require _hashlib module')
def test_refleaks_in_hash___init__(self):
gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
sha1_hash = c_hashlib.new('sha1')
refs_before = gettotalrefcount()
for i in range(100):
sha1_hash.__init__('sha1')
self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
@unittest.skip('[jart] what')
def test_hash_array(self):
a = array.array("b", range(10))
for cons in self.hash_constructors:
c = cons(a)
if c.name in self.shakes:
c.hexdigest(16)
else:
c.hexdigest()
def test_algorithms_guaranteed(self):
self.assertEqual(hashlib.algorithms_guaranteed,
set(_algo for _algo in self.supported_hash_names
if _algo.islower()))
def test_algorithms_available(self):
self.assertTrue(set(hashlib.algorithms_guaranteed).
issubset(hashlib.algorithms_available))
@unittest.skip('[jart] dont care about sha3 dont care dont care')
def test_unknown_hash(self):
self.assertRaises(ValueError, hashlib.new, 'spam spam spam spam spam')
self.assertRaises(TypeError, hashlib.new, 1)
def test_get_builtin_constructor(self):
get_builtin_constructor = getattr(hashlib,
'__get_builtin_constructor')
builtin_constructor_cache = getattr(hashlib,
'__builtin_constructor_cache')
self.assertRaises(ValueError, get_builtin_constructor, 'test')
try:
import _md5
except ImportError:
self.skipTest("_md5 module not available")
# This forces an ImportError for "import _md5" statements
sys.modules['_md5'] = None
# clear the cache
builtin_constructor_cache.clear()
try:
self.assertRaises(ValueError, get_builtin_constructor, 'md5')
finally:
if '_md5' in locals():
sys.modules['_md5'] = _md5
else:
del sys.modules['_md5']
self.assertRaises(TypeError, get_builtin_constructor, 3)
constructor = get_builtin_constructor('md5')
self.assertIs(constructor, _md5.md5)
self.assertEqual(sorted(builtin_constructor_cache), ['MD5', 'md5'])
def test_hexdigest(self):
for cons in self.hash_constructors:
h = cons()
if h.name in self.shakes:
self.assertIsInstance(h.digest(16), bytes)
self.assertEqual(hexstr(h.digest(16)), h.hexdigest(16))
else:
self.assertIsInstance(h.digest(), bytes)
self.assertEqual(hexstr(h.digest()), h.hexdigest())
def test_digest_length_overflow(self):
# See issue #34922
large_sizes = (2**29, 2**32-10, 2**32+10, 2**61, 2**64-10, 2**64+10)
for cons in self.hash_constructors:
h = cons()
if h.name not in self.shakes:
continue
for digest in h.digest, h.hexdigest:
with self.assertRaises((ValueError, OverflowError)):
digest(-10)
for length in large_sizes:
with self.assertRaises((ValueError, OverflowError)):
digest(length)
def test_name_attribute(self):
for cons in self.hash_constructors:
h = cons()
self.assertIsInstance(h.name, str)
if h.name in self.supported_hash_names:
self.assertIn(h.name, self.supported_hash_names)
else:
self.assertNotIn(h.name, self.supported_hash_names)
self.assertEqual(h.name, hashlib.new(h.name).name)
def test_large_update(self):
aas = b'a' * 128
bees = b'b' * 127
cees = b'c' * 126
dees = b'd' * 2048 # HASHLIB_GIL_MINSIZE
for cons in self.hash_constructors:
m1 = cons()
m1.update(aas)
m1.update(bees)
m1.update(cees)
m1.update(dees)
if m1.name in self.shakes:
args = (16,)
else:
args = ()
m2 = cons()
m2.update(aas + bees + cees + dees)
self.assertEqual(m1.digest(*args), m2.digest(*args))
m3 = cons(aas + bees + cees + dees)
self.assertEqual(m1.digest(*args), m3.digest(*args))
# verify copy() doesn't touch original
m4 = cons(aas + bees + cees)
m4_digest = m4.digest(*args)
m4_copy = m4.copy()
m4_copy.update(dees)
self.assertEqual(m1.digest(*args), m4_copy.digest(*args))
self.assertEqual(m4.digest(*args), m4_digest)
def check(self, name, data, hexdigest, shake=False, **kwargs):
length = len(hexdigest)//2
hexdigest = hexdigest.lower()
constructors = self.constructors_to_test[name]
# 2 is for hashlib.name(...) and hashlib.new(name, ...)
self.assertGreaterEqual(len(constructors), 2)
for hash_object_constructor in constructors:
m = hash_object_constructor(data, **kwargs)
computed = m.hexdigest() if not shake else m.hexdigest(length)
self.assertEqual(
computed, hexdigest,
"Hash algorithm %s constructed using %s returned hexdigest"
" %r for %d byte input data that should have hashed to %r."
% (name, hash_object_constructor,
computed, len(data), hexdigest))
computed = m.digest() if not shake else m.digest(length)
digest = bytes.fromhex(hexdigest)
self.assertEqual(computed, digest)
if not shake:
self.assertEqual(len(digest), m.digest_size)
def check_no_unicode(self, algorithm_name):
# Unicode objects are not allowed as input.
constructors = self.constructors_to_test[algorithm_name]
for hash_object_constructor in constructors:
self.assertRaises(TypeError, hash_object_constructor, 'spam')
def test_no_unicode(self):
self.check_no_unicode('md5')
self.check_no_unicode('sha1')
self.check_no_unicode('sha224')
self.check_no_unicode('sha256')
self.check_no_unicode('sha384')
self.check_no_unicode('sha512')
@requires_sha3
def test_no_unicode_sha3(self):
self.check_no_unicode('sha3_224')
self.check_no_unicode('sha3_256')
self.check_no_unicode('sha3_384')
self.check_no_unicode('sha3_512')
self.check_no_unicode('shake_128')
self.check_no_unicode('shake_256')
def check_blocksize_name(self, name, block_size=0, digest_size=0,
digest_length=None):
constructors = self.constructors_to_test[name]
for hash_object_constructor in constructors:
m = hash_object_constructor()
self.assertEqual(m.block_size, block_size)
self.assertEqual(m.digest_size, digest_size)
if digest_length:
self.assertEqual(len(m.digest(digest_length)),
digest_length)
self.assertEqual(len(m.hexdigest(digest_length)),
2*digest_length)
else:
self.assertEqual(len(m.digest()), digest_size)
self.assertEqual(len(m.hexdigest()), 2*digest_size)
self.assertEqual(m.name, name)
# split for sha3_512 / _sha3.sha3 object
self.assertIn(name.split("_")[0], repr(m))
@unittest.skip('[jart] bad test')
def test_blocksize_name(self):
self.check_blocksize_name('md5', 64, 16)
self.check_blocksize_name('sha1', 64, 20)
self.check_blocksize_name('sha224', 64, 28)
self.check_blocksize_name('sha256', 64, 32)
self.check_blocksize_name('sha384', 128, 48)
self.check_blocksize_name('sha512', 128, 64)
@requires_sha3
def test_blocksize_name_sha3(self):
self.check_blocksize_name('sha3_224', 144, 28)
self.check_blocksize_name('sha3_256', 136, 32)
self.check_blocksize_name('sha3_384', 104, 48)
self.check_blocksize_name('sha3_512', 72, 64)
self.check_blocksize_name('shake_128', 168, 0, 32)
self.check_blocksize_name('shake_256', 136, 0, 64)
def check_sha3(self, name, capacity, rate, suffix):
constructors = self.constructors_to_test[name]
for hash_object_constructor in constructors:
m = hash_object_constructor()
self.assertEqual(capacity + rate, 1600)
self.assertEqual(m._capacity_bits, capacity)
self.assertEqual(m._rate_bits, rate)
self.assertEqual(m._suffix, suffix)
@requires_sha3
def test_extra_sha3(self):
self.check_sha3('sha3_224', 448, 1152, b'\x06')
self.check_sha3('sha3_256', 512, 1088, b'\x06')
self.check_sha3('sha3_384', 768, 832, b'\x06')
self.check_sha3('sha3_512', 1024, 576, b'\x06')
self.check_sha3('shake_128', 256, 1344, b'\x1f')
self.check_sha3('shake_256', 512, 1088, b'\x1f')
def test_case_md5_0(self):
self.check('md5', b'', 'd41d8cd98f00b204e9800998ecf8427e')
def test_case_md5_1(self):
self.check('md5', b'abc', '900150983cd24fb0d6963f7d28e17f72')
def test_case_md5_2(self):
self.check('md5',
b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
'd174ab98d277d9f5a5611c2c9f419d9f')
@unittest.skipIf(sys.maxsize < _4G + 5, 'test cannot run on 32-bit systems')
@bigmemtest(size=_4G + 5, memuse=1, dry_run=False)
def test_case_md5_huge(self, size):
self.check('md5', b'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d')
@unittest.skipIf(sys.maxsize < _4G - 1, 'test cannot run on 32-bit systems')
@bigmemtest(size=_4G - 1, memuse=1, dry_run=False)
def test_case_md5_uintmax(self, size):
self.check('md5', b'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3')
# use the three examples from Federal Information Processing Standards
# Publication 180-1, Secure Hash Standard, 1995 April 17
# http://www.itl.nist.gov/div897/pubs/fip180-1.htm
def test_case_sha1_0(self):
self.check('sha1', b"",
"da39a3ee5e6b4b0d3255bfef95601890afd80709")
def test_case_sha1_1(self):
self.check('sha1', b"abc",
"a9993e364706816aba3e25717850c26c9cd0d89d")
def test_case_sha1_2(self):
self.check('sha1',
b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"84983e441c3bd26ebaae4aa1f95129e5e54670f1")
def test_case_sha1_3(self):
self.check('sha1', b"a" * 1000000,
"34aa973cd4c4daa4f61eeb2bdbad27316534016f")
# use the examples from Federal Information Processing Standards
# Publication 180-2, Secure Hash Standard, 2002 August 1
# http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
def test_case_sha224_0(self):
self.check('sha224', b"",
"d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")
def test_case_sha224_1(self):
self.check('sha224', b"abc",
"23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7")
def test_case_sha224_2(self):
self.check('sha224',
b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525")
def test_case_sha224_3(self):
self.check('sha224', b"a" * 1000000,
"20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67")
def test_case_sha256_0(self):
self.check('sha256', b"",
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
def test_case_sha256_1(self):
self.check('sha256', b"abc",
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
def test_case_sha256_2(self):
self.check('sha256',
b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1")
def test_case_sha256_3(self):
self.check('sha256', b"a" * 1000000,
"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0")
def test_case_sha384_0(self):
self.check('sha384', b"",
"38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da"+
"274edebfe76f65fbd51ad2f14898b95b")
def test_case_sha384_1(self):
self.check('sha384', b"abc",
"cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"+
"8086072ba1e7cc2358baeca134c825a7")
def test_case_sha384_2(self):
self.check('sha384',
b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712"+
"fcc7c71a557e2db966c3e9fa91746039")
def test_case_sha384_3(self):
self.check('sha384', b"a" * 1000000,
"9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b"+
"07b8b3dc38ecc4ebae97ddd87f3d8985")
def test_case_sha512_0(self):
self.check('sha512', b"",
"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"+
"47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")
def test_case_sha512_1(self):
self.check('sha512', b"abc",
"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"+
"2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f")
def test_case_sha512_2(self):
self.check('sha512',
b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"+
"501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909")
def test_case_sha512_3(self):
self.check('sha512', b"a" * 1000000,
"e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"+
"de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b")
@requires_sha3
def test_case_sha3_224_0(self):
self.check('sha3_224', b"",
"6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7")
@requires_sha3
def test_case_sha3_224_vector(self):
for msg, md in read_vectors('sha3_224'):
self.check('sha3_224', msg, md)
@requires_sha3
def test_case_sha3_256_0(self):
self.check('sha3_256', b"",
"a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a")
@requires_sha3
def test_case_sha3_256_vector(self):
for msg, md in read_vectors('sha3_256'):
self.check('sha3_256', msg, md)
@requires_sha3
def test_case_sha3_384_0(self):
self.check('sha3_384', b"",
"0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2a"+
"c3713831264adb47fb6bd1e058d5f004")
@requires_sha3
def test_case_sha3_384_vector(self):
for msg, md in read_vectors('sha3_384'):
self.check('sha3_384', msg, md)
@requires_sha3
def test_case_sha3_512_0(self):
self.check('sha3_512', b"",
"a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a6"+
"15b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26")
@requires_sha3
def test_case_sha3_512_vector(self):
for msg, md in read_vectors('sha3_512'):
self.check('sha3_512', msg, md)
@requires_sha3
def test_case_shake_128_0(self):
self.check('shake_128', b"",
"7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26",
True)
self.check('shake_128', b"", "7f9c", True)
@requires_sha3
def test_case_shake128_vector(self):
for msg, md in read_vectors('shake_128'):
self.check('shake_128', msg, md, True)
@requires_sha3
def test_case_shake_256_0(self):
self.check('shake_256', b"",
"46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762f",
True)
self.check('shake_256', b"", "46b9", True)
@requires_sha3
def test_case_shake256_vector(self):
for msg, md in read_vectors('shake_256'):
self.check('shake_256', msg, md, True)
def test_gil(self):
# Check things work fine with an input larger than the size required
# for multithreaded operation (which is hardwired to 2048).
gil_minsize = 2048
for cons in self.hash_constructors:
m = cons()
m.update(b'1')
m.update(b'#' * gil_minsize)
m.update(b'1')
m = cons(b'x' * gil_minsize)
m.update(b'1')
m = hashlib.md5()
m.update(b'1')
m.update(b'#' * gil_minsize)
m.update(b'1')
self.assertEqual(m.hexdigest(), 'cb1e1a2cbc80be75e19935d621fb9b21')
m = hashlib.md5(b'x' * gil_minsize)
self.assertEqual(m.hexdigest(), 'cfb767f225d58469c5de3632a8803958')
@unittest.skipUnless(threading, 'Threading required for this test.')
@support.reap_threads
def test_threaded_hashing(self):
# Updating the same hash object from several threads at once
# using data chunk sizes containing the same byte sequences.
#
# If the internal locks are working to prevent multiple
# updates on the same object from running at once, the resulting
# hash will be the same as doing it single threaded upfront.
hasher = hashlib.sha1()
num_threads = 5
smallest_data = b'swineflu'
data = smallest_data * 200000
expected_hash = hashlib.sha1(data*num_threads).hexdigest()
def hash_in_chunks(chunk_size):
index = 0
while index < len(data):
hasher.update(data[index:index + chunk_size])
index += chunk_size
threads = []
for threadnum in range(num_threads):
chunk_size = len(data) // (10 ** threadnum)
self.assertGreater(chunk_size, 0)
self.assertEqual(chunk_size % len(smallest_data), 0)
thread = threading.Thread(target=hash_in_chunks,
args=(chunk_size,))
threads.append(thread)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
self.assertEqual(expected_hash, hasher.hexdigest())
if __name__ == "__main__":
unittest.main()
| 24,471 | 635 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_modulefinder.py | import os
import errno
import importlib.machinery
import py_compile
import shutil
import unittest
import tempfile
from test import support
import modulefinder
TEST_DIR = tempfile.mkdtemp()
TEST_PATH = [TEST_DIR, os.path.dirname(tempfile.__file__)]
# Each test description is a list of 5 items:
#
# 1. a module name that will be imported by modulefinder
# 2. a list of module names that modulefinder is required to find
# 3. a list of module names that modulefinder should complain
# about because they are not found
# 4. a list of module names that modulefinder should complain
# about because they MAY be not found
# 5. a string specifying packages to create; the format is obvious imo.
#
# Each package will be created in TEST_DIR, and TEST_DIR will be
# removed after the tests again.
# Modulefinder searches in a path that contains TEST_DIR, plus
# the standard Lib directory.
maybe_test = [
"a.module",
["a", "a.module", "sys",
"b"],
["c"], ["b.something"],
"""\
a/__init__.py
a/module.py
from b import something
from c import something
b/__init__.py
from sys import *
"""]
maybe_test_new = [
"a.module",
["a", "a.module", "sys",
"b", "__future__"],
["c"], ["b.something"],
"""\
a/__init__.py
a/module.py
from b import something
from c import something
b/__init__.py
from __future__ import absolute_import
from sys import *
"""]
package_test = [
"a.module",
["a", "a.b", "a.c", "a.module", "mymodule", "sys"],
["blahblah", "c"], [],
"""\
mymodule.py
a/__init__.py
import blahblah
from a import b
import c
a/module.py
import sys
from a import b as x
from a.c import sillyname
a/b.py
a/c.py
from a.module import x
import mymodule as sillyname
from sys import version_info
"""]
absolute_import_test = [
"a.module",
["a", "a.module",
"b", "b.x", "b.y", "b.z",
"__future__", "sys", "gc"],
["blahblah", "z"], [],
"""\
mymodule.py
a/__init__.py
a/module.py
from __future__ import absolute_import
import sys # sys
import blahblah # fails
import gc # gc
import b.x # b.x
from b import y # b.y
from b.z import * # b.z.*
a/gc.py
a/sys.py
import mymodule
a/b/__init__.py
a/b/x.py
a/b/y.py
a/b/z.py
b/__init__.py
import z
b/unused.py
b/x.py
b/y.py
b/z.py
"""]
relative_import_test = [
"a.module",
["__future__",
"a", "a.module",
"a.b", "a.b.y", "a.b.z",
"a.b.c", "a.b.c.moduleC",
"a.b.c.d", "a.b.c.e",
"a.b.x",
"gc"],
[], [],
"""\
mymodule.py
a/__init__.py
from .b import y, z # a.b.y, a.b.z
a/module.py
from __future__ import absolute_import # __future__
import gc # gc
a/gc.py
a/sys.py
a/b/__init__.py
from ..b import x # a.b.x
#from a.b.c import moduleC
from .c import moduleC # a.b.moduleC
a/b/x.py
a/b/y.py
a/b/z.py
a/b/g.py
a/b/c/__init__.py
from ..c import e # a.b.c.e
a/b/c/moduleC.py
from ..c import d # a.b.c.d
a/b/c/d.py
a/b/c/e.py
a/b/c/x.py
"""]
relative_import_test_2 = [
"a.module",
["a", "a.module",
"a.sys",
"a.b", "a.b.y", "a.b.z",
"a.b.c", "a.b.c.d",
"a.b.c.e",
"a.b.c.moduleC",
"a.b.c.f",
"a.b.x",
"a.another"],
[], [],
"""\
mymodule.py
a/__init__.py
from . import sys # a.sys
a/another.py
a/module.py
from .b import y, z # a.b.y, a.b.z
a/gc.py
a/sys.py
a/b/__init__.py
from .c import moduleC # a.b.c.moduleC
from .c import d # a.b.c.d
a/b/x.py
a/b/y.py
a/b/z.py
a/b/c/__init__.py
from . import e # a.b.c.e
a/b/c/moduleC.py
#
from . import f # a.b.c.f
from .. import x # a.b.x
from ... import another # a.another
a/b/c/d.py
a/b/c/e.py
a/b/c/f.py
"""]
relative_import_test_3 = [
"a.module",
["a", "a.module"],
["a.bar"],
[],
"""\
a/__init__.py
def foo(): pass
a/module.py
from . import foo
from . import bar
"""]
relative_import_test_4 = [
"a.module",
["a", "a.module"],
[],
[],
"""\
a/__init__.py
def foo(): pass
a/module.py
from . import *
"""]
bytecode_test = [
"a",
["a"],
[],
[],
""
]
def open_file(path):
dirname = os.path.dirname(path)
try:
os.makedirs(dirname)
except OSError as e:
if e.errno != errno.EEXIST:
raise
return open(path, "w")
def create_package(source):
ofi = None
try:
for line in source.splitlines():
if line.startswith(" ") or line.startswith("\t"):
ofi.write(line.strip() + "\n")
else:
if ofi:
ofi.close()
ofi = open_file(os.path.join(TEST_DIR, line.strip()))
finally:
if ofi:
ofi.close()
class ModuleFinderTest(unittest.TestCase):
def _do_test(self, info, report=False, debug=0, replace_paths=[]):
import_this, modules, missing, maybe_missing, source = info
create_package(source)
try:
mf = modulefinder.ModuleFinder(path=TEST_PATH, debug=debug,
replace_paths=replace_paths)
mf.import_hook(import_this)
if report:
mf.report()
## # This wouldn't work in general when executed several times:
## opath = sys.path[:]
## sys.path = TEST_PATH
## try:
## __import__(import_this)
## except:
## import traceback; traceback.print_exc()
## sys.path = opath
## return
modules = sorted(set(modules))
found = sorted(mf.modules)
# check if we found what we expected, not more, not less
self.assertEqual(found, modules)
# check for missing and maybe missing modules
bad, maybe = mf.any_missing_maybe()
self.assertEqual(bad, missing)
self.assertEqual(maybe, maybe_missing)
finally:
shutil.rmtree(TEST_DIR)
def test_package(self):
self._do_test(package_test)
def test_maybe(self):
self._do_test(maybe_test)
def test_maybe_new(self):
self._do_test(maybe_test_new)
def test_absolute_imports(self):
self._do_test(absolute_import_test)
def test_relative_imports(self):
self._do_test(relative_import_test)
def test_relative_imports_2(self):
self._do_test(relative_import_test_2)
def test_relative_imports_3(self):
self._do_test(relative_import_test_3)
def test_relative_imports_4(self):
self._do_test(relative_import_test_4)
def test_bytecode(self):
base_path = os.path.join(TEST_DIR, 'a')
source_path = base_path + importlib.machinery.SOURCE_SUFFIXES[0]
bytecode_path = base_path + importlib.machinery.BYTECODE_SUFFIXES[0]
with open_file(source_path) as file:
file.write('testing_modulefinder = True\n')
py_compile.compile(source_path, cfile=bytecode_path)
os.remove(source_path)
self._do_test(bytecode_test)
def test_replace_paths(self):
old_path = os.path.join(TEST_DIR, 'a', 'module.py')
new_path = os.path.join(TEST_DIR, 'a', 'spam.py')
with support.captured_stdout() as output:
self._do_test(maybe_test, debug=2,
replace_paths=[(old_path, new_path)])
output = output.getvalue()
expected = "co_filename %r changed to %r" % (old_path, new_path)
self.assertIn(expected, output)
def test_extended_opargs(self):
extended_opargs_test = [
"a",
["a", "b"],
[], [],
"""\
a.py
%r
import b
b.py
""" % list(range(2**16))] # 2**16 constants
self._do_test(extended_opargs_test)
if __name__ == "__main__":
unittest.main()
| 9,272 | 338 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/sample_doctest_no_docstrings.py | # This is a sample module used for testing doctest.
#
# This module is for testing how doctest handles a module with no
# docstrings.
class Foo(object):
# A class with no docstring.
def __init__(self):
pass
| 227 | 13 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_compare.py | import unittest
class Empty:
def __repr__(self):
return '<Empty>'
class Cmp:
def __init__(self,arg):
self.arg = arg
def __repr__(self):
return '<Cmp %s>' % self.arg
def __eq__(self, other):
return self.arg == other
class Anything:
def __eq__(self, other):
return True
def __ne__(self, other):
return False
class ComparisonTest(unittest.TestCase):
set1 = [2, 2.0, 2, 2+0j, Cmp(2.0)]
set2 = [[1], (3,), None, Empty()]
candidates = set1 + set2
def test_comparisons(self):
for a in self.candidates:
for b in self.candidates:
if ((a in self.set1) and (b in self.set1)) or a is b:
self.assertEqual(a, b)
else:
self.assertNotEqual(a, b)
def test_id_comparisons(self):
# Ensure default comparison compares id() of args
L = []
for i in range(10):
L.insert(len(L)//2, Empty())
for a in L:
for b in L:
self.assertEqual(a == b, id(a) == id(b),
'a=%r, b=%r' % (a, b))
def test_ne_defaults_to_not_eq(self):
a = Cmp(1)
b = Cmp(1)
c = Cmp(2)
self.assertIs(a == b, True)
self.assertIs(a != b, False)
self.assertIs(a != c, True)
def test_ne_high_priority(self):
"""object.__ne__() should allow reflected __ne__() to be tried"""
calls = []
class Left:
# Inherits object.__ne__()
def __eq__(*args):
calls.append('Left.__eq__')
return NotImplemented
class Right:
def __eq__(*args):
calls.append('Right.__eq__')
return NotImplemented
def __ne__(*args):
calls.append('Right.__ne__')
return NotImplemented
Left() != Right()
self.assertSequenceEqual(calls, ['Left.__eq__', 'Right.__ne__'])
def test_ne_low_priority(self):
"""object.__ne__() should not invoke reflected __eq__()"""
calls = []
class Base:
# Inherits object.__ne__()
def __eq__(*args):
calls.append('Base.__eq__')
return NotImplemented
class Derived(Base): # Subclassing forces higher priority
def __eq__(*args):
calls.append('Derived.__eq__')
return NotImplemented
def __ne__(*args):
calls.append('Derived.__ne__')
return NotImplemented
Base() != Derived()
self.assertSequenceEqual(calls, ['Derived.__ne__', 'Base.__eq__'])
def test_other_delegation(self):
"""No default delegation between operations except __ne__()"""
ops = (
('__eq__', lambda a, b: a == b),
('__lt__', lambda a, b: a < b),
('__le__', lambda a, b: a <= b),
('__gt__', lambda a, b: a > b),
('__ge__', lambda a, b: a >= b),
)
for name, func in ops:
with self.subTest(name):
def unexpected(*args):
self.fail('Unexpected operator method called')
class C:
__ne__ = unexpected
for other, _ in ops:
if other != name:
setattr(C, other, unexpected)
if name == '__eq__':
self.assertIs(func(C(), object()), False)
else:
self.assertRaises(TypeError, func, C(), object())
def test_issue_1393(self):
x = lambda: None
self.assertEqual(x, Anything())
self.assertEqual(Anything(), x)
y = object()
self.assertEqual(y, Anything())
self.assertEqual(Anything(), y)
if __name__ == '__main__':
unittest.main()
| 3,914 | 125 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_tix.py | import unittest
from test import support
import sys
# Skip this test if the _tkinter module wasn't built.
_tkinter = support.import_module('_tkinter')
# Skip test if tk cannot be initialized.
support.requires('gui')
from tkinter import tix, TclError
class TestTix(unittest.TestCase):
def setUp(self):
try:
self.root = tix.Tk()
except TclError:
if sys.platform.startswith('win'):
self.fail('Tix should always be available on Windows')
self.skipTest('Tix not available')
else:
self.addCleanup(self.root.destroy)
def test_tix_available(self):
# this test is just here to make setUp run
pass
if __name__ == '__main__':
unittest.main()
| 756 | 33 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_cmd_line_script.py | # tests command line execution of scripts
import contextlib
import importlib
import importlib.machinery
import zipimport
import unittest
import sys
import os
import os.path
import py_compile
import subprocess
import io
import textwrap
from test import support
from test.support.script_helper import (
make_pkg, make_script, make_zip_pkg, make_zip_script,
assert_python_ok, assert_python_failure, spawn_python, kill_python)
verbose = support.verbose
example_args = ['test1', 'test2', 'test3']
test_source = """\
# Script may be run with optimisation enabled, so don't rely on assert
# statements being executed
def assertEqual(lhs, rhs):
if lhs != rhs:
raise AssertionError('%r != %r' % (lhs, rhs))
def assertIdentical(lhs, rhs):
if lhs is not rhs:
raise AssertionError('%r is not %r' % (lhs, rhs))
# Check basic code execution
result = ['Top level assignment']
def f():
result.append('Lower level reference')
f()
assertEqual(result, ['Top level assignment', 'Lower level reference'])
# Check population of magic variables
assertEqual(__name__, '__main__')
from importlib.machinery import BuiltinImporter
_loader = __loader__ if __loader__ is BuiltinImporter else type(__loader__)
print('__loader__==%a' % _loader)
print('__file__==%a' % __file__)
print('__cached__==%a' % __cached__)
print('__package__==%r' % __package__)
# Check PEP 451 details
import os.path
if __package__ is not None:
print('__main__ was located through the import system')
assertIdentical(__spec__.loader, __loader__)
expected_spec_name = os.path.splitext(os.path.basename(__file__))[0]
if __package__:
expected_spec_name = __package__ + "." + expected_spec_name
assertEqual(__spec__.name, expected_spec_name)
assertEqual(__spec__.parent, __package__)
assertIdentical(__spec__.submodule_search_locations, None)
assertEqual(__spec__.origin, __file__)
if __spec__.cached is not None:
assertEqual(__spec__.cached, __cached__)
# Check the sys module
import sys
assertIdentical(globals(), sys.modules[__name__].__dict__)
if __spec__ is not None:
# XXX: We're not currently making __main__ available under its real name
pass # assertIdentical(globals(), sys.modules[__spec__.name].__dict__)
from test import test_cmd_line_script
example_args_list = test_cmd_line_script.example_args
assertEqual(sys.argv[1:], example_args_list)
print('sys.argv[0]==%a' % sys.argv[0])
print('sys.path[0]==%a' % sys.path[0])
# Check the working directory
import os
print('cwd==%a' % os.getcwd())
"""
def _make_test_script(script_dir, script_basename, source=test_source):
to_return = make_script(script_dir, script_basename, source)
importlib.invalidate_caches()
return to_return
def _make_test_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
source=test_source, depth=1):
to_return = make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
source, depth)
importlib.invalidate_caches()
return to_return
# There's no easy way to pass the script directory in to get
# -m to work (avoiding that is the whole point of making
# directories and zipfiles executable!)
# So we fake it for testing purposes with a custom launch script
launch_source = """\
import sys, os.path, runpy
sys.path.insert(0, %s)
runpy._run_module_as_main(%r)
"""
def _make_launch_script(script_dir, script_basename, module_name, path=None):
if path is None:
path = "os.path.dirname(__file__)"
else:
path = repr(path)
source = launch_source % (path, module_name)
to_return = make_script(script_dir, script_basename, source)
importlib.invalidate_caches()
return to_return
class CmdLineTest(unittest.TestCase):
def _check_output(self, script_name, exit_code, data,
expected_file, expected_argv0,
expected_path0, expected_package,
expected_loader):
if verbose > 1:
print("Output from test script %r:" % script_name)
print(repr(data))
self.assertEqual(exit_code, 0)
printed_loader = '__loader__==%a' % expected_loader
printed_file = '__file__==%a' % expected_file
printed_package = '__package__==%r' % expected_package
printed_argv0 = 'sys.argv[0]==%a' % expected_argv0
printed_path0 = 'sys.path[0]==%a' % expected_path0
printed_cwd = 'cwd==%a' % os.getcwd()
if verbose > 1:
print('Expected output:')
print(printed_file)
print(printed_package)
print(printed_argv0)
print(printed_cwd)
self.assertIn(printed_loader.encode('utf-8'), data)
self.assertIn(printed_file.encode('utf-8'), data)
self.assertIn(printed_package.encode('utf-8'), data)
self.assertIn(printed_argv0.encode('utf-8'), data)
self.assertIn(printed_path0.encode('utf-8'), data)
self.assertIn(printed_cwd.encode('utf-8'), data)
def _check_script(self, script_name, expected_file,
expected_argv0, expected_path0,
expected_package, expected_loader,
*cmd_line_switches):
run_args = [*support.optim_args_from_interpreter_flags(),
*cmd_line_switches, script_name, *example_args]
rc, out, err = assert_python_ok(*run_args, __isolated=False)
self._check_output(script_name, rc, out + err, expected_file,
expected_argv0, expected_path0,
expected_package, expected_loader)
def _check_import_error(self, script_name, expected_msg,
*cmd_line_switches):
run_args = cmd_line_switches + (script_name,)
rc, out, err = assert_python_failure(*run_args)
if verbose > 1:
print('Output from test script %r:' % script_name)
print(repr(err))
print('Expected output: %r' % expected_msg)
self.assertIn(expected_msg.encode('utf-8'), err)
def test_dash_c_loader(self):
rc, out, err = assert_python_ok("-c", "print(__loader__)")
expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8")
self.assertIn(expected, out)
def test_stdin_loader(self):
# Unfortunately, there's no way to automatically test the fully
# interactive REPL, since that code path only gets executed when
# stdin is an interactive tty.
p = spawn_python()
try:
p.stdin.write(b"print(__loader__)\n")
p.stdin.flush()
finally:
out = kill_python(p)
expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8")
self.assertIn(expected, out)
@contextlib.contextmanager
def interactive_python(self, separate_stderr=False):
if separate_stderr:
p = spawn_python('-i', bufsize=1, stderr=subprocess.PIPE)
stderr = p.stderr
else:
p = spawn_python('-i', bufsize=1, stderr=subprocess.STDOUT)
stderr = p.stdout
try:
# Drain stderr until prompt
while True:
data = stderr.read(4)
if data == b">>> ":
break
stderr.readline()
yield p
finally:
kill_python(p)
stderr.close()
def check_repl_stdout_flush(self, separate_stderr=False):
with self.interactive_python(separate_stderr) as p:
p.stdin.write(b"print('foo')\n")
p.stdin.flush()
self.assertEqual(b'foo', p.stdout.readline().strip())
def check_repl_stderr_flush(self, separate_stderr=False):
with self.interactive_python(separate_stderr) as p:
p.stdin.write(b"1/0\n")
p.stdin.flush()
stderr = p.stderr if separate_stderr else p.stdout
self.assertIn(b'Traceback ', stderr.readline())
self.assertIn(b'File "<stdin>"', stderr.readline())
self.assertIn(b'ZeroDivisionError', stderr.readline())
@unittest.skipIf(True, "TODO: find out why this freezes")
def test_repl_stdout_flush(self):
self.check_repl_stdout_flush()
@unittest.skipIf(True, "TODO: find out why this freezes")
def test_repl_stdout_flush_separate_stderr(self):
self.check_repl_stdout_flush(True)
@unittest.skipIf(True, "TODO: find out why this freezes")
def test_repl_stderr_flush(self):
self.check_repl_stderr_flush()
@unittest.skipIf(True, "TODO: find out why this freezes")
def test_repl_stderr_flush_separate_stderr(self):
self.check_repl_stderr_flush(True)
def test_basic_script(self):
with support.temp_dir() as script_dir:
script_name = _make_test_script(script_dir, 'script')
self._check_script(script_name, script_name, script_name,
script_dir, None,
importlib.machinery.SourceFileLoader)
@unittest.skipIf(True, "[jart] Breaks Landlock LSM due to EXDEV")
def test_script_compiled(self):
with support.temp_dir() as script_dir:
script_name = _make_test_script(script_dir, 'script')
py_compile.compile(script_name, doraise=True)
os.remove(script_name)
pyc_file = support.make_legacy_pyc(script_name)
self._check_script(pyc_file, pyc_file,
pyc_file, script_dir, None,
importlib.machinery.SourcelessFileLoader)
def test_directory(self):
with support.temp_dir() as script_dir:
script_name = _make_test_script(script_dir, '__main__')
self._check_script(script_dir, script_name, script_dir,
script_dir, '',
importlib.machinery.SourceFileLoader)
@unittest.skipIf(True, "[jart] Breaks Landlock LSM due to EXDEV")
def test_directory_compiled(self):
with support.temp_dir() as script_dir:
script_name = _make_test_script(script_dir, '__main__')
py_compile.compile(script_name, doraise=True)
os.remove(script_name)
pyc_file = support.make_legacy_pyc(script_name)
self._check_script(script_dir, pyc_file, script_dir,
script_dir, '',
importlib.machinery.SourcelessFileLoader)
def test_directory_error(self):
with support.temp_dir() as script_dir:
msg = "can't find '__main__' module in %r" % script_dir
self._check_import_error(script_dir, msg)
def test_zipfile(self):
with support.temp_dir() as script_dir:
script_name = _make_test_script(script_dir, '__main__')
zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name)
self._check_script(zip_name, run_name, zip_name, zip_name, '',
zipimport.zipimporter)
@unittest.skipIf(True, "[jart] Breaks Landlock LSM due to EXDEV")
def test_zipfile_compiled(self):
with support.temp_dir() as script_dir:
script_name = _make_test_script(script_dir, '__main__')
compiled_name = py_compile.compile(script_name, doraise=True)
zip_name, run_name = make_zip_script(script_dir, 'test_zip', compiled_name)
self._check_script(zip_name, run_name, zip_name, zip_name, '',
zipimport.zipimporter)
@unittest.skipIf(True, "[jart] Breaks Landlock LSM due to EXDEV")
def test_zipfile_error(self):
with support.temp_dir() as script_dir:
script_name = _make_test_script(script_dir, 'not_main')
zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name)
msg = "can't find '__main__' module in %r" % zip_name
self._check_import_error(zip_name, msg)
def test_module_in_package(self):
with support.temp_dir() as script_dir:
pkg_dir = os.path.join(script_dir, 'test_pkg')
make_pkg(pkg_dir)
script_name = _make_test_script(pkg_dir, 'script')
launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script')
self._check_script(launch_name, script_name, script_name,
script_dir, 'test_pkg',
importlib.machinery.SourceFileLoader)
def test_module_in_package_in_zipfile(self):
with support.temp_dir() as script_dir:
zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script')
launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script', zip_name)
self._check_script(launch_name, run_name, run_name,
zip_name, 'test_pkg', zipimport.zipimporter)
def test_module_in_subpackage_in_zipfile(self):
with support.temp_dir() as script_dir:
zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script', depth=2)
launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.test_pkg.script', zip_name)
self._check_script(launch_name, run_name, run_name,
zip_name, 'test_pkg.test_pkg',
zipimport.zipimporter)
def test_package(self):
with support.temp_dir() as script_dir:
pkg_dir = os.path.join(script_dir, 'test_pkg')
make_pkg(pkg_dir)
script_name = _make_test_script(pkg_dir, '__main__')
launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
self._check_script(launch_name, script_name,
script_name, script_dir, 'test_pkg',
importlib.machinery.SourceFileLoader)
@unittest.skipIf(True, "[jart] Breaks Landlock LSM due to EXDEV")
def test_package_compiled(self):
with support.temp_dir() as script_dir:
pkg_dir = os.path.join(script_dir, 'test_pkg')
make_pkg(pkg_dir)
script_name = _make_test_script(pkg_dir, '__main__')
compiled_name = py_compile.compile(script_name, doraise=True)
os.remove(script_name)
pyc_file = support.make_legacy_pyc(script_name)
launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
self._check_script(launch_name, pyc_file,
pyc_file, script_dir, 'test_pkg',
importlib.machinery.SourcelessFileLoader)
def test_package_error(self):
with support.temp_dir() as script_dir:
pkg_dir = os.path.join(script_dir, 'test_pkg')
make_pkg(pkg_dir)
msg = ("'test_pkg' is a package and cannot "
"be directly executed")
launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
self._check_import_error(launch_name, msg)
def test_package_recursion(self):
with support.temp_dir() as script_dir:
pkg_dir = os.path.join(script_dir, 'test_pkg')
make_pkg(pkg_dir)
main_dir = os.path.join(pkg_dir, '__main__')
make_pkg(main_dir)
msg = ("Cannot use package as __main__ module; "
"'test_pkg' is a package and cannot "
"be directly executed")
launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
self._check_import_error(launch_name, msg)
def test_issue8202(self):
# Make sure package __init__ modules see "-m" in sys.argv0 while
# searching for the module to execute
with support.temp_dir() as script_dir:
with support.change_cwd(path=script_dir):
pkg_dir = os.path.join(script_dir, 'test_pkg')
make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])")
script_name = _make_test_script(pkg_dir, 'script')
rc, out, err = assert_python_ok('-m', 'test_pkg.script', *example_args, __isolated=False)
if verbose > 1:
print(repr(out))
expected = "init_argv0==%r" % '-m'
self.assertIn(expected.encode('utf-8'), out)
self._check_output(script_name, rc, out,
script_name, script_name, '', 'test_pkg',
importlib.machinery.SourceFileLoader)
def test_issue8202_dash_c_file_ignored(self):
# Make sure a "-c" file in the current directory
# does not alter the value of sys.path[0]
with support.temp_dir() as script_dir:
with support.change_cwd(path=script_dir):
with open("-c", "w") as f:
f.write("data")
rc, out, err = assert_python_ok('-c',
'import sys; print("sys.path[0]==%r" % sys.path[0])',
__isolated=False)
if verbose > 1:
print(repr(out))
expected = "sys.path[0]==%r" % ''
self.assertIn(expected.encode('utf-8'), out)
def test_issue8202_dash_m_file_ignored(self):
# Make sure a "-m" file in the current directory
# does not alter the value of sys.path[0]
with support.temp_dir() as script_dir:
script_name = _make_test_script(script_dir, 'other')
with support.change_cwd(path=script_dir):
with open("-m", "w") as f:
f.write("data")
rc, out, err = assert_python_ok('-m', 'other', *example_args,
__isolated=False)
self._check_output(script_name, rc, out,
script_name, script_name, '', '',
importlib.machinery.SourceFileLoader)
@contextlib.contextmanager
def setup_test_pkg(self, *args):
with support.temp_dir() as script_dir, \
support.change_cwd(path=script_dir):
pkg_dir = os.path.join(script_dir, 'test_pkg')
make_pkg(pkg_dir, *args)
yield pkg_dir
def check_dash_m_failure(self, *args):
rc, out, err = assert_python_failure('-m', *args, __isolated=False)
if verbose > 1:
print(repr(out))
self.assertEqual(rc, 1)
return err
def test_dash_m_error_code_is_one(self):
# If a module is invoked with the -m command line flag
# and results in an error that the return code to the
# shell is '1'
with self.setup_test_pkg() as pkg_dir:
script_name = _make_test_script(pkg_dir, 'other',
"if __name__ == '__main__': raise ValueError")
err = self.check_dash_m_failure('test_pkg.other', *example_args)
self.assertIn(b'ValueError', err)
@unittest.skipIf(True, "TODO: fix regex match for error message")
def test_dash_m_errors(self):
# Exercise error reporting for various invalid package executions
tests = (
('builtins', br'No code object available'),
('builtins.x', br'Error while finding module specification.*'
br'AttributeError'),
('builtins.x.y', br'Error while finding module specification.*'
br'ModuleNotFoundError.*No module named.*not a package'),
('os.path', br'loader.*cannot handle'),
('importlib', br'No module named.*'
br'is a package and cannot be directly executed'),
('importlib.nonexistant', br'No module named'),
('.unittest', br'Relative module names not supported'),
)
for name, regex in tests:
with self.subTest(name):
rc, _, err = assert_python_failure('-m', name)
self.assertEqual(rc, 1)
self.assertRegex(err, regex)
self.assertNotIn(b'Traceback', err)
@unittest.skipIf(True, "TODO: fix regex match for error message")
def test_dash_m_bad_pyc(self):
with support.temp_dir() as script_dir, \
support.change_cwd(path=script_dir):
os.mkdir('test_pkg')
# Create invalid *.pyc as empty file
with open('test_pkg/__init__.pyc', 'wb'):
pass
err = self.check_dash_m_failure('test_pkg')
self.assertRegex(err,
br'Error while finding module specification.*'
br'ImportError.*bad magic number')
self.assertNotIn(b'is a package', err)
self.assertNotIn(b'Traceback', err)
def test_dash_m_init_traceback(self):
# These were wrapped in an ImportError and tracebacks were
# suppressed; see Issue 14285
exceptions = (ImportError, AttributeError, TypeError, ValueError)
for exception in exceptions:
exception = exception.__name__
init = "raise {0}('Exception in __init__.py')".format(exception)
with self.subTest(exception), \
self.setup_test_pkg(init) as pkg_dir:
err = self.check_dash_m_failure('test_pkg')
self.assertIn(exception.encode('ascii'), err)
self.assertIn(b'Exception in __init__.py', err)
self.assertIn(b'Traceback', err)
def test_dash_m_main_traceback(self):
# Ensure that an ImportError's traceback is reported
with self.setup_test_pkg() as pkg_dir:
main = "raise ImportError('Exception in __main__ module')"
_make_test_script(pkg_dir, '__main__', main)
err = self.check_dash_m_failure('test_pkg')
self.assertIn(b'ImportError', err)
self.assertIn(b'Exception in __main__ module', err)
self.assertIn(b'Traceback', err)
def test_pep_409_verbiage(self):
# Make sure PEP 409 syntax properly suppresses
# the context of an exception
script = textwrap.dedent("""\
try:
raise ValueError
except:
raise NameError from None
""")
with support.temp_dir() as script_dir:
script_name = _make_test_script(script_dir, 'script', script)
exitcode, stdout, stderr = assert_python_failure(script_name)
text = stderr.decode('ascii').split('\n')
self.assertEqual(len(text), 4)
self.assertTrue(text[0].startswith('Traceback'))
self.assertTrue(text[1].startswith(' File '))
self.assertTrue(text[3].startswith('NameError'))
def test_non_ascii(self):
# Mac OS X denies the creation of a file with an invalid UTF-8 name.
# Windows allows creating a name with an arbitrary bytes name, but
# Python cannot a undecodable bytes argument to a subprocess.
if (support.TESTFN_UNDECODABLE
and sys.platform not in ('win32', 'darwin')):
name = os.fsdecode(support.TESTFN_UNDECODABLE)
elif support.TESTFN_NONASCII:
name = support.TESTFN_NONASCII
else:
self.skipTest("need support.TESTFN_NONASCII")
# Issue #16218
source = 'print(ascii(__file__))\n'
script_name = _make_test_script(os.curdir, name, source)
self.addCleanup(support.unlink, script_name)
rc, stdout, stderr = assert_python_ok(script_name)
self.assertEqual(
ascii(script_name),
stdout.rstrip().decode('ascii'),
'stdout=%r stderr=%r' % (stdout, stderr))
self.assertEqual(0, rc)
def test_issue20500_exit_with_exception_value(self):
script = textwrap.dedent("""\
import sys
error = None
try:
raise ValueError('some text')
except ValueError as err:
error = err
if error:
sys.exit(error)
""")
with support.temp_dir() as script_dir:
script_name = _make_test_script(script_dir, 'script', script)
exitcode, stdout, stderr = assert_python_failure(script_name)
text = stderr.decode('ascii')
self.assertEqual(text, "some text")
def test_syntaxerror_unindented_caret_position(self):
script = "1 + 1 = 2\n"
with support.temp_dir() as script_dir:
script_name = _make_test_script(script_dir, 'script', script)
exitcode, stdout, stderr = assert_python_failure(script_name)
text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read()
# Confirm that the caret is located under the first 1 character
self.assertIn("\n 1 + 1 = 2\n ^", text)
def test_syntaxerror_indented_caret_position(self):
script = textwrap.dedent("""\
if True:
1 + 1 = 2
""")
with support.temp_dir() as script_dir:
script_name = _make_test_script(script_dir, 'script', script)
exitcode, stdout, stderr = assert_python_failure(script_name)
text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read()
# Confirm that the caret is located under the first 1 character
self.assertIn("\n 1 + 1 = 2\n ^", text)
# Try the same with a form feed at the start of the indented line
script = (
"if True:\n"
"\f 1 + 1 = 2\n"
)
script_name = _make_test_script(script_dir, "script", script)
exitcode, stdout, stderr = assert_python_failure(script_name)
text = io.TextIOWrapper(io.BytesIO(stderr), "ascii").read()
self.assertNotIn("\f", text)
self.assertIn("\n 1 + 1 = 2\n ^", text)
def test_consistent_sys_path_for_direct_execution(self):
# This test case ensures that the following all give the same
# sys.path configuration:
#
# ./python -s script_dir/__main__.py
# ./python -s script_dir
# ./python -I script_dir
script = textwrap.dedent("""\
import sys
for entry in sys.path:
print(entry)
""")
# Always show full path diffs on errors
self.maxDiff = None
with support.temp_dir() as work_dir, support.temp_dir() as script_dir:
script_name = _make_test_script(script_dir, '__main__', script)
# Reference output comes from directly executing __main__.py
# We omit PYTHONPATH and user site to align with isolated mode
p = spawn_python("-Es", script_name, cwd=work_dir)
out_by_name = kill_python(p).decode().splitlines()
self.assertEqual(out_by_name[0], script_dir)
self.assertNotIn(work_dir, out_by_name)
# Directory execution should give the same output
p = spawn_python("-Es", script_dir, cwd=work_dir)
out_by_dir = kill_python(p).decode().splitlines()
self.assertEqual(out_by_dir, out_by_name)
# As should directory execution in isolated mode
p = spawn_python("-I", script_dir, cwd=work_dir)
out_by_dir_isolated = kill_python(p).decode().splitlines()
self.assertEqual(out_by_dir_isolated, out_by_dir, out_by_name)
def test_consistent_sys_path_for_module_execution(self):
# This test case ensures that the following both give the same
# sys.path configuration:
# ./python -sm script_pkg.__main__
# ./python -sm script_pkg
#
# And that this fails as unable to find the package:
# ./python -Im script_pkg
script = textwrap.dedent("""\
import sys
for entry in sys.path:
print(entry)
""")
# Always show full path diffs on errors
self.maxDiff = None
with support.temp_dir() as work_dir:
script_dir = os.path.join(work_dir, "script_pkg")
os.mkdir(script_dir)
script_name = _make_test_script(script_dir, '__main__', script)
# Reference output comes from `-m script_pkg.__main__`
# We omit PYTHONPATH and user site to better align with the
# direct execution test cases
p = spawn_python("-sm", "script_pkg.__main__", cwd=work_dir)
out_by_module = kill_python(p).decode().splitlines()
self.assertEqual(out_by_module[0], '')
self.assertNotIn(script_dir, out_by_module)
# Package execution should give the same output
p = spawn_python("-sm", "script_pkg", cwd=work_dir)
out_by_package = kill_python(p).decode().splitlines()
self.assertEqual(out_by_package, out_by_module)
# Isolated mode should fail with an import error
exitcode, stdout, stderr = assert_python_failure(
"-Im", "script_pkg", cwd=work_dir
)
traceback_lines = stderr.decode().splitlines()
self.assertIn("No module named script_pkg", traceback_lines[-1])
def test_main():
support.run_unittest(CmdLineTest)
support.reap_children()
if __name__ == '__main__':
test_main()
| 29,572 | 660 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/ann_module.py |
"""
The module for testing variable annotations.
Empty lines above are for good reason (testing for correct line numbers)
"""
from typing import Optional
__annotations__[1] = 2
class C:
x = 5; y: Optional['C'] = None
from typing import Tuple
x: int = 5; y: str = x; f: Tuple[int, int]
class M(type):
__annotations__['123'] = 123
o: type = object
(pars): bool = True
class D(C):
j: str = 'hi'; k: str= 'bye'
from types import new_class
h_class = new_class('H', (C,))
j_class = new_class('J')
class F():
z: int = 5
def __init__(self, x):
pass
class Y(F):
def __init__(self):
super(F, self).__init__(123)
class Meta(type):
def __new__(meta, name, bases, namespace):
return super().__new__(meta, name, bases, namespace)
class S(metaclass = Meta):
x: str = 'something'
y: str = 'something else'
def foo(x: int = 10):
def bar(y: List[str]):
x: str = 'yes'
bar()
| 953 | 54 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_traceback.py | """Test cases for traceback module"""
from collections import namedtuple
from io import StringIO
import linecache
import sys
import cosmo
import unittest
import re
from test import support
from test.support import TESTFN, Error, captured_output, unlink, cpython_only
from test.support.script_helper import assert_python_ok
import textwrap
import traceback
test_code = namedtuple('code', ['co_filename', 'co_name'])
test_frame = namedtuple('frame', ['f_code', 'f_globals', 'f_locals'])
test_tb = namedtuple('tb', ['tb_frame', 'tb_lineno', 'tb_next'])
class TracebackCases(unittest.TestCase):
# For now, a very minimal set of tests. I want to be sure that
# formatting of SyntaxErrors works based on changes for 2.1.
def get_exception_format(self, func, exc):
try:
func()
except exc as value:
return traceback.format_exception_only(exc, value)
else:
raise ValueError("call did not raise exception")
def syntax_error_with_caret(self):
compile("def fact(x):\n\treturn x!\n", "?", "exec")
def syntax_error_with_caret_2(self):
compile("1 +\n", "?", "exec")
def syntax_error_bad_indentation(self):
compile("def spam():\n print(1)\n print(2)", "?", "exec")
def syntax_error_with_caret_non_ascii(self):
compile('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', "?", "exec")
def syntax_error_bad_indentation2(self):
compile(" print(2)", "?", "exec")
def test_caret(self):
err = self.get_exception_format(self.syntax_error_with_caret,
SyntaxError)
self.assertEqual(len(err), 4)
self.assertTrue(err[1].strip() == "return x!")
self.assertIn("^", err[2]) # third line has caret
self.assertEqual(err[1].find("!"), err[2].find("^")) # in the right place
err = self.get_exception_format(self.syntax_error_with_caret_2,
SyntaxError)
self.assertIn("^", err[2]) # third line has caret
self.assertEqual(err[2].count('\n'), 1) # and no additional newline
self.assertEqual(err[1].find("+"), err[2].find("^")) # in the right place
err = self.get_exception_format(self.syntax_error_with_caret_non_ascii,
SyntaxError)
self.assertIn("^", err[2]) # third line has caret
self.assertEqual(err[2].count('\n'), 1) # and no additional newline
self.assertEqual(err[1].find("+"), err[2].find("^")) # in the right place
def test_nocaret(self):
exc = SyntaxError("error", ("x.py", 23, None, "bad syntax"))
err = traceback.format_exception_only(SyntaxError, exc)
self.assertEqual(len(err), 3)
self.assertEqual(err[1].strip(), "bad syntax")
def test_bad_indentation(self):
err = self.get_exception_format(self.syntax_error_bad_indentation,
IndentationError)
self.assertEqual(len(err), 4)
self.assertEqual(err[1].strip(), "print(2)")
self.assertIn("^", err[2])
self.assertEqual(err[1].find(")"), err[2].find("^"))
err = self.get_exception_format(self.syntax_error_bad_indentation2,
IndentationError)
self.assertEqual(len(err), 4)
self.assertEqual(err[1].strip(), "print(2)")
self.assertIn("^", err[2])
self.assertEqual(err[1].find("p"), err[2].find("^"))
def test_base_exception(self):
# Test that exceptions derived from BaseException are formatted right
e = KeyboardInterrupt()
lst = traceback.format_exception_only(e.__class__, e)
self.assertEqual(lst, ['KeyboardInterrupt\n'])
def test_format_exception_only_bad__str__(self):
class X(Exception):
def __str__(self):
1/0
err = traceback.format_exception_only(X, X())
self.assertEqual(len(err), 1)
str_value = '<unprintable %s object>' % X.__name__
if X.__module__ in ('__main__', 'builtins'):
str_name = X.__qualname__
else:
str_name = '.'.join([X.__module__, X.__qualname__])
self.assertEqual(err[0], "%s: %s\n" % (str_name, str_value))
def test_encoded_file(self):
# Test that tracebacks are correctly printed for encoded source files:
# - correct line number (Issue2384)
# - respect file encoding (Issue3975)
import tempfile, sys, subprocess, os
# The spawned subprocess has its stdout redirected to a PIPE, and its
# encoding may be different from the current interpreter, on Windows
# at least.
process = subprocess.Popen([sys.executable, "-c",
"import sys; print(sys.stdout.encoding)"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, stderr = process.communicate()
output_encoding = str(stdout, 'ascii').splitlines()[0]
def do_test(firstlines, message, charset, lineno):
# Raise the message in a subprocess, and catch the output
try:
with open(TESTFN, "w", encoding=charset) as output:
output.write("""{0}if 1:
import traceback;
raise RuntimeError('{1}')
""".format(firstlines, message))
process = subprocess.Popen([sys.executable, TESTFN],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = process.communicate()
stdout = stdout.decode(output_encoding).splitlines()
finally:
unlink(TESTFN)
# The source lines are encoded with the 'backslashreplace' handler
encoded_message = message.encode(output_encoding,
'backslashreplace')
# and we just decoded them with the output_encoding.
message_ascii = encoded_message.decode(output_encoding)
err_line = "raise RuntimeError('{0}')".format(message_ascii)
err_msg = "RuntimeError: {0}".format(message_ascii)
self.assertIn(("line %s" % lineno), stdout[1],
"Invalid line number: {0!r} instead of {1}".format(
stdout[1], lineno))
self.assertTrue(stdout[2].endswith(err_line),
"Invalid traceback line: {0!r} instead of {1!r}".format(
stdout[2], err_line))
self.assertTrue(stdout[3] == err_msg,
"Invalid error message: {0!r} instead of {1!r}".format(
stdout[3], err_msg))
do_test("", "foo", "utf-8", 3)
for charset in ("utf-8",): # "ascii", "iso-8859-1", "utf-8", "GBK"):
if charset == "ascii":
text = "foo"
elif charset == "GBK":
text = "\u4E02\u5100"
else:
text = "h\xe9 ho"
do_test("# coding: {0}\n".format(charset),
text, charset, 4)
do_test("#!shebang\n# coding: {0}\n".format(charset),
text, charset, 5)
do_test(" \t\f\n# coding: {0}\n".format(charset),
text, charset, 5)
# Issue #18960: coding spec should have no effect
do_test("x=0\n# coding: GBK\n", "h\xe9 ho", 'utf-8', 5)
@support.requires_type_collecting
def test_print_traceback_at_exit(self):
# Issue #22599: Ensure that it is possible to use the traceback module
# to display an exception at Python exit
code = textwrap.dedent("""
import sys
import traceback
class PrintExceptionAtExit(object):
def __init__(self):
try:
x = 1 / 0
except Exception:
self.exc_info = sys.exc_info()
# self.exc_info[1] (traceback) contains frames:
# explicitly clear the reference to self in the current
# frame to break a reference cycle
self = None
def __del__(self):
traceback.print_exception(*self.exc_info)
# Keep a reference in the module namespace to call the destructor
# when the module is unloaded
obj = PrintExceptionAtExit()
""")
rc, stdout, stderr = assert_python_ok('-c', code)
expected = [b'Traceback (most recent call last):',
b' File "<string>", line 8, in __init__',
b'ZeroDivisionError: division by zero']
self.assertEqual(stderr.splitlines(), expected)
def test_print_exception(self):
output = StringIO()
traceback.print_exception(
Exception, Exception("projector"), None, file=output
)
self.assertEqual(output.getvalue(), "Exception: projector\n")
@unittest.skipIf("tiny" in cosmo.MODE, "")
class TracebackFormatTests(unittest.TestCase):
def some_exception(self):
raise KeyError('blah')
@cpython_only
def check_traceback_format(self, cleanup_func=None):
from _testcapi import traceback_print
try:
self.some_exception()
except KeyError:
type_, value, tb = sys.exc_info()
if cleanup_func is not None:
# Clear the inner frames, not this one
cleanup_func(tb.tb_next)
traceback_fmt = 'Traceback (most recent call last):\n' + \
''.join(traceback.format_tb(tb))
file_ = StringIO()
traceback_print(tb, file_)
python_fmt = file_.getvalue()
# Call all _tb and _exc functions
with captured_output("stderr") as tbstderr:
traceback.print_tb(tb)
tbfile = StringIO()
traceback.print_tb(tb, file=tbfile)
with captured_output("stderr") as excstderr:
traceback.print_exc()
excfmt = traceback.format_exc()
excfile = StringIO()
traceback.print_exc(file=excfile)
else:
raise Error("unable to create test traceback string")
# Make sure that Python and the traceback module format the same thing
self.assertEqual(traceback_fmt, python_fmt)
# Now verify the _tb func output
self.assertEqual(tbstderr.getvalue(), tbfile.getvalue())
# Now verify the _exc func output
self.assertEqual(excstderr.getvalue(), excfile.getvalue())
self.assertEqual(excfmt, excfile.getvalue())
# Make sure that the traceback is properly indented.
tb_lines = python_fmt.splitlines()
self.assertEqual(len(tb_lines), 5)
banner = tb_lines[0]
location, source_line = tb_lines[-2:]
self.assertTrue(banner.startswith('Traceback'))
self.assertTrue(location.startswith(' File'))
self.assertTrue(source_line.startswith(' raise'))
def test_traceback_format(self):
self.check_traceback_format()
def test_traceback_format_with_cleared_frames(self):
# Check that traceback formatting also works with a clear()ed frame
def cleanup_tb(tb):
tb.tb_frame.clear()
self.check_traceback_format(cleanup_tb)
def test_stack_format(self):
# Verify _stack functions. Note we have to use _getframe(1) to
# compare them without this frame appearing in the output
with captured_output("stderr") as ststderr:
traceback.print_stack(sys._getframe(1))
stfile = StringIO()
traceback.print_stack(sys._getframe(1), file=stfile)
self.assertEqual(ststderr.getvalue(), stfile.getvalue())
stfmt = traceback.format_stack(sys._getframe(1))
self.assertEqual(ststderr.getvalue(), "".join(stfmt))
def test_print_stack(self):
def prn():
traceback.print_stack()
with captured_output("stderr") as stderr:
prn()
lineno = prn.__code__.co_firstlineno
self.assertEqual(stderr.getvalue().splitlines()[-4:], [
' File "%s", line %d, in test_print_stack' % (__file__.replace(".pyc", ".py"), lineno+3),
' prn()',
' File "%s", line %d, in prn' % (__file__.replace(".pyc", ".py"), lineno+1),
' traceback.print_stack()',
])
# issue 26823 - Shrink recursive tracebacks
def _check_recursive_traceback_display(self, render_exc):
# Always show full diffs when this test fails
# Note that rearranging things may require adjusting
# the relative line numbers in the expected tracebacks
self.maxDiff = None
# Check hitting the recursion limit
def f():
f()
with captured_output("stderr") as stderr_f:
try:
f()
except RecursionError as exc:
render_exc()
else:
self.fail("no recursion occurred")
lineno_f = f.__code__.co_firstlineno
result_f = (
'Traceback (most recent call last):\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_f+5}, in _check_recursive_traceback_display\n'
' f()\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_f+1}, in f\n'
' f()\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_f+1}, in f\n'
' f()\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_f+1}, in f\n'
' f()\n'
# XXX: The following line changes depending on whether the tests
# are run through the interactive interpreter or with -m
# It also varies depending on the platform (stack size)
# Fortunately, we don't care about exactness here, so we use regex
r' \[Previous line repeated (\d+) more times\]' '\n'
'RecursionError: maximum recursion depth exceeded\n'
)
expected = result_f.splitlines()
actual = stderr_f.getvalue().splitlines()
# Check the output text matches expectations
# 2nd last line contains the repetition count
self.assertEqual(actual[:-2], expected[:-2])
self.assertRegex(actual[-2], expected[-2])
# last line can have additional text appended
self.assertIn(expected[-1], actual[-1])
# Check the recursion count is roughly as expected
rec_limit = sys.getrecursionlimit()
self.assertIn(int(re.search(r"\d+", actual[-2]).group()), range(rec_limit-60, rec_limit))
# Check a known (limited) number of recursive invocations
def g(count=10):
if count:
return g(count-1)
raise ValueError
with captured_output("stderr") as stderr_g:
try:
g()
except ValueError as exc:
render_exc()
else:
self.fail("no value error was raised")
lineno_g = g.__code__.co_firstlineno
result_g = (
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_g+2}, in g\n'
' return g(count-1)\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_g+2}, in g\n'
' return g(count-1)\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_g+2}, in g\n'
' return g(count-1)\n'
' [Previous line repeated 7 more times]\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_g+3}, in g\n'
' raise ValueError\n'
'ValueError\n'
)
tb_line = (
'Traceback (most recent call last):\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_g+7}, in _check_recursive_traceback_display\n'
' g()\n'
)
expected = (tb_line + result_g).splitlines()
actual = stderr_g.getvalue().splitlines()
self.assertEqual(actual, expected)
# Check 2 different repetitive sections
def h(count=10):
if count:
return h(count-1)
g()
with captured_output("stderr") as stderr_h:
try:
h()
except ValueError as exc:
render_exc()
else:
self.fail("no value error was raised")
lineno_h = h.__code__.co_firstlineno
result_h = (
'Traceback (most recent call last):\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_h+7}, in _check_recursive_traceback_display\n'
' h()\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_h+2}, in h\n'
' return h(count-1)\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_h+2}, in h\n'
' return h(count-1)\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_h+2}, in h\n'
' return h(count-1)\n'
' [Previous line repeated 7 more times]\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_h+3}, in h\n'
' g()\n'
)
expected = (result_h + result_g).splitlines()
actual = stderr_h.getvalue().splitlines()
self.assertEqual(actual, expected)
# Check the boundary conditions. First, test just below the cutoff.
with captured_output("stderr") as stderr_g:
try:
g(traceback._RECURSIVE_CUTOFF)
except ValueError as exc:
render_exc()
else:
self.fail("no error raised")
result_g = (
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_g+2}, in g\n'
' return g(count-1)\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_g+2}, in g\n'
' return g(count-1)\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_g+2}, in g\n'
' return g(count-1)\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_g+3}, in g\n'
' raise ValueError\n'
'ValueError\n'
)
tb_line = (
'Traceback (most recent call last):\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_g+71}, in _check_recursive_traceback_display\n'
' g(traceback._RECURSIVE_CUTOFF)\n'
)
expected = (tb_line + result_g).splitlines()
actual = stderr_g.getvalue().splitlines()
self.assertEqual(actual, expected)
# Second, test just above the cutoff.
with captured_output("stderr") as stderr_g:
try:
g(traceback._RECURSIVE_CUTOFF + 1)
except ValueError as exc:
render_exc()
else:
self.fail("no error raised")
result_g = (
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_g+2}, in g\n'
' return g(count-1)\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_g+2}, in g\n'
' return g(count-1)\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_g+2}, in g\n'
' return g(count-1)\n'
' [Previous line repeated 1 more time]\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_g+3}, in g\n'
' raise ValueError\n'
'ValueError\n'
)
tb_line = (
'Traceback (most recent call last):\n'
f' File "{__file__.replace(".pyc", ".py")}", line {lineno_g+99}, in _check_recursive_traceback_display\n'
' g(traceback._RECURSIVE_CUTOFF + 1)\n'
)
expected = (tb_line + result_g).splitlines()
actual = stderr_g.getvalue().splitlines()
self.assertEqual(actual, expected)
@unittest.skip("regex doesn't match")
def test_recursive_traceback_python(self):
self._check_recursive_traceback_display(traceback.print_exc)
@unittest.skip("regex doesn't match")
@cpython_only
def test_recursive_traceback_cpython_internal(self):
from _testcapi import exception_print
def render_exc():
exc_type, exc_value, exc_tb = sys.exc_info()
exception_print(exc_value)
self._check_recursive_traceback_display(render_exc)
def test_format_stack(self):
def fmt():
return traceback.format_stack()
result = fmt()
lineno = fmt.__code__.co_firstlineno
self.assertEqual(result[-2:], [
' File "%s", line %d, in test_format_stack\n'
' result = fmt()\n' % (__file__.replace(".pyc", ".py"), lineno+2),
' File "%s", line %d, in fmt\n'
' return traceback.format_stack()\n' % (__file__.replace(".pyc", ".py"), lineno+1),
])
@cpython_only
def test_unhashable(self):
from _testcapi import exception_print
class UnhashableException(Exception):
def __eq__(self, other):
return True
ex1 = UnhashableException('ex1')
ex2 = UnhashableException('ex2')
try:
raise ex2 from ex1
except UnhashableException:
try:
raise ex1
except UnhashableException:
exc_type, exc_val, exc_tb = sys.exc_info()
with captured_output("stderr") as stderr_f:
exception_print(exc_val)
tb = stderr_f.getvalue().strip().splitlines()
self.assertEqual(11, len(tb))
self.assertEqual(context_message.strip(), tb[5])
self.assertIn('UnhashableException: ex2', tb[3])
self.assertIn('UnhashableException: ex1', tb[10])
cause_message = (
"\nThe above exception was the direct cause "
"of the following exception:\n\n")
context_message = (
"\nDuring handling of the above exception, "
"another exception occurred:\n\n")
boundaries = re.compile(
'(%s|%s)' % (re.escape(cause_message), re.escape(context_message)))
@unittest.skipIf("tiny" in cosmo.MODE, "")
class BaseExceptionReportingTests:
def get_exception(self, exception_or_callable):
if isinstance(exception_or_callable, Exception):
return exception_or_callable
try:
exception_or_callable()
except Exception as e:
return e
def zero_div(self):
1/0 # In zero_div
def check_zero_div(self, msg):
lines = msg.splitlines()
self.assertTrue(lines[-3].startswith(' File'))
self.assertIn('1/0 # In zero_div', lines[-2])
self.assertTrue(lines[-1].startswith('ZeroDivisionError'), lines[-1])
def test_simple(self):
try:
1/0 # Marker
except ZeroDivisionError as _:
e = _
lines = self.get_report(e).splitlines()
self.assertEqual(len(lines), 4)
self.assertTrue(lines[0].startswith('Traceback'))
self.assertTrue(lines[1].startswith(' File'))
self.assertIn('1/0 # Marker', lines[2])
self.assertTrue(lines[3].startswith('ZeroDivisionError'))
def test_cause(self):
def inner_raise():
try:
self.zero_div()
except ZeroDivisionError as e:
raise KeyError from e
def outer_raise():
inner_raise() # Marker
blocks = boundaries.split(self.get_report(outer_raise))
self.assertEqual(len(blocks), 3)
self.assertEqual(blocks[1], cause_message)
self.check_zero_div(blocks[0])
self.assertIn('inner_raise() # Marker', blocks[2])
def test_context(self):
def inner_raise():
try:
self.zero_div()
except ZeroDivisionError:
raise KeyError
def outer_raise():
inner_raise() # Marker
blocks = boundaries.split(self.get_report(outer_raise))
self.assertEqual(len(blocks), 3)
self.assertEqual(blocks[1], context_message)
self.check_zero_div(blocks[0])
self.assertIn('inner_raise() # Marker', blocks[2])
def test_context_suppression(self):
try:
try:
raise Exception
except:
raise ZeroDivisionError from None
except ZeroDivisionError as _:
e = _
lines = self.get_report(e).splitlines()
self.assertEqual(len(lines), 4)
self.assertTrue(lines[0].startswith('Traceback'))
self.assertTrue(lines[1].startswith(' File'))
self.assertIn('ZeroDivisionError from None', lines[2])
self.assertTrue(lines[3].startswith('ZeroDivisionError'))
def test_cause_and_context(self):
# When both a cause and a context are set, only the cause should be
# displayed and the context should be muted.
def inner_raise():
try:
self.zero_div()
except ZeroDivisionError as _e:
e = _e
try:
xyzzy
except NameError:
raise KeyError from e
def outer_raise():
inner_raise() # Marker
blocks = boundaries.split(self.get_report(outer_raise))
self.assertEqual(len(blocks), 3)
self.assertEqual(blocks[1], cause_message)
self.check_zero_div(blocks[0])
self.assertIn('inner_raise() # Marker', blocks[2])
def test_cause_recursive(self):
def inner_raise():
try:
try:
self.zero_div()
except ZeroDivisionError as e:
z = e
raise KeyError from e
except KeyError as e:
raise z from e
def outer_raise():
inner_raise() # Marker
blocks = boundaries.split(self.get_report(outer_raise))
self.assertEqual(len(blocks), 3)
self.assertEqual(blocks[1], cause_message)
# The first block is the KeyError raised from the ZeroDivisionError
self.assertIn('raise KeyError from e', blocks[0])
self.assertNotIn('1/0', blocks[0])
# The second block (apart from the boundary) is the ZeroDivisionError
# re-raised from the KeyError
self.assertIn('inner_raise() # Marker', blocks[2])
self.check_zero_div(blocks[2])
def test_syntax_error_offset_at_eol(self):
# See #10186.
def e():
raise SyntaxError('', ('', 0, 5, 'hello'))
msg = self.get_report(e).splitlines()
self.assertEqual(msg[-2], " ^")
def e():
exec("x = 5 | 4 |")
msg = self.get_report(e).splitlines()
self.assertEqual(msg[-2], ' ^')
def test_message_none(self):
# A message that looks like "None" should not be treated specially
err = self.get_report(Exception(None))
self.assertIn('Exception: None\n', err)
err = self.get_report(Exception('None'))
self.assertIn('Exception: None\n', err)
err = self.get_report(Exception())
self.assertIn('Exception\n', err)
err = self.get_report(Exception(''))
self.assertIn('Exception\n', err)
class PyExcReportingTests(BaseExceptionReportingTests, unittest.TestCase):
#
# This checks reporting through the 'traceback' module, with both
# format_exception() and print_exception().
#
def get_report(self, e):
e = self.get_exception(e)
s = ''.join(
traceback.format_exception(type(e), e, e.__traceback__))
with captured_output("stderr") as sio:
traceback.print_exception(type(e), e, e.__traceback__)
self.assertEqual(sio.getvalue(), s)
return s
class CExcReportingTests(BaseExceptionReportingTests, unittest.TestCase):
#
# This checks built-in reporting by the interpreter.
#
@cpython_only
def get_report(self, e):
from _testcapi import exception_print
e = self.get_exception(e)
with captured_output("stderr") as s:
exception_print(e)
return s.getvalue()
class LimitTests(unittest.TestCase):
''' Tests for limit argument.
It's enough to test extact_tb, extract_stack and format_exception '''
def last_raises1(self):
raise Exception('Last raised')
def last_raises2(self):
self.last_raises1()
def last_raises3(self):
self.last_raises2()
def last_raises4(self):
self.last_raises3()
def last_raises5(self):
self.last_raises4()
def last_returns_frame1(self):
return sys._getframe()
def last_returns_frame2(self):
return self.last_returns_frame1()
def last_returns_frame3(self):
return self.last_returns_frame2()
def last_returns_frame4(self):
return self.last_returns_frame3()
def last_returns_frame5(self):
return self.last_returns_frame4()
def test_extract_stack(self):
frame = self.last_returns_frame5()
def extract(**kwargs):
return traceback.extract_stack(frame, **kwargs)
def assertEqualExcept(actual, expected, ignore):
self.assertEqual(actual[:ignore], expected[:ignore])
self.assertEqual(actual[ignore+1:], expected[ignore+1:])
self.assertEqual(len(actual), len(expected))
with support.swap_attr(sys, 'tracebacklimit', 1000):
nolim = extract()
self.assertGreater(len(nolim), 5)
self.assertEqual(extract(limit=2), nolim[-2:])
assertEqualExcept(extract(limit=100), nolim[-100:], -5-1)
self.assertEqual(extract(limit=-2), nolim[:2])
assertEqualExcept(extract(limit=-100), nolim[:100], len(nolim)-5-1)
self.assertEqual(extract(limit=0), [])
del sys.tracebacklimit
assertEqualExcept(extract(), nolim, -5-1)
sys.tracebacklimit = 2
self.assertEqual(extract(), nolim[-2:])
self.assertEqual(extract(limit=3), nolim[-3:])
self.assertEqual(extract(limit=-3), nolim[:3])
sys.tracebacklimit = 0
self.assertEqual(extract(), [])
sys.tracebacklimit = -1
self.assertEqual(extract(), [])
def test_extract_tb(self):
try:
self.last_raises5()
except Exception:
exc_type, exc_value, tb = sys.exc_info()
def extract(**kwargs):
return traceback.extract_tb(tb, **kwargs)
with support.swap_attr(sys, 'tracebacklimit', 1000):
nolim = extract()
self.assertEqual(len(nolim), 5+1)
self.assertEqual(extract(limit=2), nolim[:2])
self.assertEqual(extract(limit=10), nolim)
self.assertEqual(extract(limit=-2), nolim[-2:])
self.assertEqual(extract(limit=-10), nolim)
self.assertEqual(extract(limit=0), [])
del sys.tracebacklimit
self.assertEqual(extract(), nolim)
sys.tracebacklimit = 2
self.assertEqual(extract(), nolim[:2])
self.assertEqual(extract(limit=3), nolim[:3])
self.assertEqual(extract(limit=-3), nolim[-3:])
sys.tracebacklimit = 0
self.assertEqual(extract(), [])
sys.tracebacklimit = -1
self.assertEqual(extract(), [])
def test_format_exception(self):
try:
self.last_raises5()
except Exception:
exc_type, exc_value, tb = sys.exc_info()
# [1:-1] to exclude "Traceback (...)" header and
# exception type and value
def extract(**kwargs):
return traceback.format_exception(exc_type, exc_value, tb, **kwargs)[1:-1]
with support.swap_attr(sys, 'tracebacklimit', 1000):
nolim = extract()
self.assertEqual(len(nolim), 5+1)
self.assertEqual(extract(limit=2), nolim[:2])
self.assertEqual(extract(limit=10), nolim)
self.assertEqual(extract(limit=-2), nolim[-2:])
self.assertEqual(extract(limit=-10), nolim)
self.assertEqual(extract(limit=0), [])
del sys.tracebacklimit
self.assertEqual(extract(), nolim)
sys.tracebacklimit = 2
self.assertEqual(extract(), nolim[:2])
self.assertEqual(extract(limit=3), nolim[:3])
self.assertEqual(extract(limit=-3), nolim[-3:])
sys.tracebacklimit = 0
self.assertEqual(extract(), [])
sys.tracebacklimit = -1
self.assertEqual(extract(), [])
class MiscTracebackCases(unittest.TestCase):
#
# Check non-printing functions in traceback module
#
def test_clear(self):
def outer():
middle()
def middle():
inner()
def inner():
i = 1
1/0
try:
outer()
except:
type_, value, tb = sys.exc_info()
# Initial assertion: there's one local in the inner frame.
inner_frame = tb.tb_next.tb_next.tb_next.tb_frame
self.assertEqual(len(inner_frame.f_locals), 1)
# Clear traceback frames
traceback.clear_frames(tb)
# Local variable dict should now be empty.
self.assertEqual(len(inner_frame.f_locals), 0)
@unittest.skipIf("tiny" in cosmo.MODE, "")
def test_extract_stack(self):
def extract():
return traceback.extract_stack()
result = extract()
lineno = extract.__code__.co_firstlineno
self.assertEqual(result[-2:], [
(__file__.replace(".pyc", ".py"), lineno+2, 'test_extract_stack', 'result = extract()'),
(__file__.replace(".pyc", ".py"), lineno+1, 'extract', 'return traceback.extract_stack()'),
])
class TestFrame(unittest.TestCase):
def test_basics(self):
linecache.clearcache()
linecache.lazycache("f", globals())
f = traceback.FrameSummary("f", 1, "dummy")
if ".pyc" not in __file__:
self.assertEqual(f,
("f", 1, "dummy", '"""Test cases for traceback module"""'))
self.assertEqual(tuple(f),
("f", 1, "dummy", '"""Test cases for traceback module"""'))
self.assertEqual(f, traceback.FrameSummary("f", 1, "dummy"))
self.assertEqual(f, tuple(f))
# Since tuple.__eq__ doesn't support FrameSummary, the equality
# operator fallbacks to FrameSummary.__eq__.
self.assertEqual(tuple(f), f)
self.assertIsNone(f.locals)
@unittest.skip
def test_lazy_lines(self):
linecache.clearcache()
f = traceback.FrameSummary("f", 1, "dummy", lookup_line=False)
self.assertEqual(None, f._line)
linecache.lazycache("f", globals())
self.assertEqual(
'"""Test cases for traceback module"""',
f.line)
def test_explicit_line(self):
f = traceback.FrameSummary("f", 1, "dummy", line="line")
self.assertEqual("line", f.line)
@unittest.skipIf("tiny" in cosmo.MODE, "")
class TestStack(unittest.TestCase):
def test_walk_stack(self):
def deeper():
return list(traceback.walk_stack(None))
s1 = list(traceback.walk_stack(None))
s2 = deeper()
self.assertEqual(len(s2) - len(s1), 1)
self.assertEqual(s2[1:], s1)
def test_walk_tb(self):
try:
1/0
except Exception:
_, _, tb = sys.exc_info()
s = list(traceback.walk_tb(tb))
self.assertEqual(len(s), 1)
def test_extract_stack(self):
s = traceback.StackSummary.extract(traceback.walk_stack(None))
self.assertIsInstance(s, traceback.StackSummary)
def test_extract_stack_limit(self):
s = traceback.StackSummary.extract(traceback.walk_stack(None), limit=5)
self.assertEqual(len(s), 5)
@unittest.skip
def test_extract_stack_lookup_lines(self):
linecache.clearcache()
linecache.updatecache('/foo.py', globals())
c = test_code('/foo.py', 'method')
f = test_frame(c, None, None)
s = traceback.StackSummary.extract(iter([(f, 6)]), lookup_lines=True)
linecache.clearcache()
self.assertEqual(s[0].line, "import sys")
@unittest.skip
def test_extract_stackup_deferred_lookup_lines(self):
linecache.clearcache()
c = test_code('/foo.py', 'method')
f = test_frame(c, None, None)
s = traceback.StackSummary.extract(iter([(f, 6)]), lookup_lines=False)
self.assertEqual({}, linecache.cache)
linecache.updatecache('/foo.py', globals())
self.assertEqual(s[0].line, "import sys")
def test_from_list(self):
s = traceback.StackSummary.from_list([('foo.py', 1, 'fred', 'line')])
self.assertEqual(
[' File "foo.py", line 1, in fred\n line\n'],
s.format())
def test_from_list_edited_stack(self):
s = traceback.StackSummary.from_list([('foo.py', 1, 'fred', 'line')])
s[0] = ('foo.py', 2, 'fred', 'line')
s2 = traceback.StackSummary.from_list(s)
self.assertEqual(
[' File "foo.py", line 2, in fred\n line\n'],
s2.format())
def test_format_smoke(self):
# For detailed tests see the format_list tests, which consume the same
# code.
s = traceback.StackSummary.from_list([('foo.py', 1, 'fred', 'line')])
self.assertEqual(
[' File "foo.py", line 1, in fred\n line\n'],
s.format())
def test_locals(self):
linecache.updatecache('/foo.py', globals())
c = test_code('/foo.py', 'method')
f = test_frame(c, globals(), {'something': 1})
s = traceback.StackSummary.extract(iter([(f, 6)]), capture_locals=True)
self.assertEqual(s[0].locals, {'something': '1'})
def test_no_locals(self):
linecache.updatecache('/foo.py', globals())
c = test_code('/foo.py', 'method')
f = test_frame(c, globals(), {'something': 1})
s = traceback.StackSummary.extract(iter([(f, 6)]))
self.assertEqual(s[0].locals, None)
def test_format_locals(self):
def some_inner(k, v):
a = 1
b = 2
return traceback.StackSummary.extract(
traceback.walk_stack(None), capture_locals=True, limit=1)
s = some_inner(3, 4)
self.assertEqual(
[' File "%s", line %d, in some_inner\n'
' traceback.walk_stack(None), capture_locals=True, limit=1)\n'
' a = 1\n'
' b = 2\n'
' k = 3\n'
' v = 4\n' % (__file__.replace(".pyc", ".py"), some_inner.__code__.co_firstlineno + 4)
], s.format())
class TestTracebackException(unittest.TestCase):
def test_smoke(self):
try:
1/0
except Exception:
exc_info = sys.exc_info()
exc = traceback.TracebackException(*exc_info)
expected_stack = traceback.StackSummary.extract(
traceback.walk_tb(exc_info[2]))
self.assertEqual(None, exc.__cause__)
self.assertEqual(None, exc.__context__)
self.assertEqual(False, exc.__suppress_context__)
self.assertEqual(expected_stack, exc.stack)
self.assertEqual(exc_info[0], exc.exc_type)
self.assertEqual(str(exc_info[1]), str(exc))
def test_from_exception(self):
# Check all the parameters are accepted.
def foo():
1/0
try:
foo()
except Exception as e:
exc_info = sys.exc_info()
self.expected_stack = traceback.StackSummary.extract(
traceback.walk_tb(exc_info[2]), limit=1, lookup_lines=False,
capture_locals=True)
self.exc = traceback.TracebackException.from_exception(
e, limit=1, lookup_lines=False, capture_locals=True)
expected_stack = self.expected_stack
exc = self.exc
self.assertEqual(None, exc.__cause__)
self.assertEqual(None, exc.__context__)
self.assertEqual(False, exc.__suppress_context__)
self.assertEqual(expected_stack, exc.stack)
self.assertEqual(exc_info[0], exc.exc_type)
self.assertEqual(str(exc_info[1]), str(exc))
def test_cause(self):
try:
try:
1/0
finally:
exc_info_context = sys.exc_info()
exc_context = traceback.TracebackException(*exc_info_context)
cause = Exception("cause")
raise Exception("uh oh") from cause
except Exception:
exc_info = sys.exc_info()
exc = traceback.TracebackException(*exc_info)
expected_stack = traceback.StackSummary.extract(
traceback.walk_tb(exc_info[2]))
exc_cause = traceback.TracebackException(Exception, cause, None)
self.assertEqual(exc_cause, exc.__cause__)
self.assertEqual(exc_context, exc.__context__)
self.assertEqual(True, exc.__suppress_context__)
self.assertEqual(expected_stack, exc.stack)
self.assertEqual(exc_info[0], exc.exc_type)
self.assertEqual(str(exc_info[1]), str(exc))
def test_context(self):
try:
try:
1/0
finally:
exc_info_context = sys.exc_info()
exc_context = traceback.TracebackException(*exc_info_context)
raise Exception("uh oh")
except Exception:
exc_info = sys.exc_info()
exc = traceback.TracebackException(*exc_info)
expected_stack = traceback.StackSummary.extract(
traceback.walk_tb(exc_info[2]))
self.assertEqual(None, exc.__cause__)
self.assertEqual(exc_context, exc.__context__)
self.assertEqual(False, exc.__suppress_context__)
self.assertEqual(expected_stack, exc.stack)
self.assertEqual(exc_info[0], exc.exc_type)
self.assertEqual(str(exc_info[1]), str(exc))
def test_unhashable(self):
class UnhashableException(Exception):
def __eq__(self, other):
return True
ex1 = UnhashableException('ex1')
ex2 = UnhashableException('ex2')
try:
raise ex2 from ex1
except UnhashableException:
try:
raise ex1
except UnhashableException:
exc_info = sys.exc_info()
exc = traceback.TracebackException(*exc_info)
formatted = list(exc.format())
self.assertIn('UnhashableException: ex2\n', formatted[2])
self.assertIn('UnhashableException: ex1\n', formatted[6])
def test_limit(self):
def recurse(n):
if n:
recurse(n-1)
else:
1/0
try:
recurse(10)
except Exception:
exc_info = sys.exc_info()
exc = traceback.TracebackException(*exc_info, limit=5)
expected_stack = traceback.StackSummary.extract(
traceback.walk_tb(exc_info[2]), limit=5)
self.assertEqual(expected_stack, exc.stack)
@unittest.skip
def test_lookup_lines(self):
linecache.clearcache()
e = Exception("uh oh")
c = test_code('/foo.py', 'method')
f = test_frame(c, None, None)
tb = test_tb(f, 6, None)
exc = traceback.TracebackException(Exception, e, tb, lookup_lines=False)
self.assertEqual({}, linecache.cache)
linecache.updatecache('/foo.py', globals())
self.assertEqual(exc.stack[0].line, "import sys")
def test_locals(self):
linecache.updatecache('/foo.py', globals())
e = Exception("uh oh")
c = test_code('/foo.py', 'method')
f = test_frame(c, globals(), {'something': 1, 'other': 'string'})
tb = test_tb(f, 6, None)
exc = traceback.TracebackException(
Exception, e, tb, capture_locals=True)
self.assertEqual(
exc.stack[0].locals, {'something': '1', 'other': "'string'"})
def test_no_locals(self):
linecache.updatecache('/foo.py', globals())
e = Exception("uh oh")
c = test_code('/foo.py', 'method')
f = test_frame(c, globals(), {'something': 1})
tb = test_tb(f, 6, None)
exc = traceback.TracebackException(Exception, e, tb)
self.assertEqual(exc.stack[0].locals, None)
def test_traceback_header(self):
# do not print a traceback header if exc_traceback is None
# see issue #24695
exc = traceback.TracebackException(Exception, Exception("haven"), None)
self.assertEqual(list(exc.format()), ["Exception: haven\n"])
class MiscTest(unittest.TestCase):
def test_all(self):
expected = set()
blacklist = {'print_list'}
for name in dir(traceback):
if name.startswith('_') or name in blacklist:
continue
module_object = getattr(traceback, name)
if getattr(module_object, '__module__', None) == 'traceback':
expected.add(name)
self.assertCountEqual(traceback.__all__, expected)
if __name__ == "__main__":
unittest.main()
| 45,651 | 1,180 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_contextlib.py | """Unit tests for contextlib.py, and other context managers."""
import io
import sys
import tempfile
import unittest
from contextlib import * # Tests __all__
from test import support
try:
import _thread
import threading
except ImportError:
threading = None
class TestAbstractContextManager(unittest.TestCase):
def test_enter(self):
class DefaultEnter(AbstractContextManager):
def __exit__(self, *args):
super().__exit__(*args)
manager = DefaultEnter()
self.assertIs(manager.__enter__(), manager)
def test_exit_is_abstract(self):
class MissingExit(AbstractContextManager):
pass
with self.assertRaises(TypeError):
MissingExit()
def test_structural_subclassing(self):
class ManagerFromScratch:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
return None
self.assertTrue(issubclass(ManagerFromScratch, AbstractContextManager))
class DefaultEnter(AbstractContextManager):
def __exit__(self, *args):
super().__exit__(*args)
self.assertTrue(issubclass(DefaultEnter, AbstractContextManager))
class NoEnter(ManagerFromScratch):
__enter__ = None
self.assertFalse(issubclass(NoEnter, AbstractContextManager))
class NoExit(ManagerFromScratch):
__exit__ = None
self.assertFalse(issubclass(NoExit, AbstractContextManager))
class ContextManagerTestCase(unittest.TestCase):
def test_contextmanager_plain(self):
state = []
@contextmanager
def woohoo():
state.append(1)
yield 42
state.append(999)
with woohoo() as x:
self.assertEqual(state, [1])
self.assertEqual(x, 42)
state.append(x)
self.assertEqual(state, [1, 42, 999])
def test_contextmanager_finally(self):
state = []
@contextmanager
def woohoo():
state.append(1)
try:
yield 42
finally:
state.append(999)
with self.assertRaises(ZeroDivisionError):
with woohoo() as x:
self.assertEqual(state, [1])
self.assertEqual(x, 42)
state.append(x)
raise ZeroDivisionError()
self.assertEqual(state, [1, 42, 999])
def test_contextmanager_no_reraise(self):
@contextmanager
def whee():
yield
ctx = whee()
ctx.__enter__()
# Calling __exit__ should not result in an exception
self.assertFalse(ctx.__exit__(TypeError, TypeError("foo"), None))
def test_contextmanager_trap_yield_after_throw(self):
@contextmanager
def whoo():
try:
yield
except:
yield
ctx = whoo()
ctx.__enter__()
self.assertRaises(
RuntimeError, ctx.__exit__, TypeError, TypeError("foo"), None
)
def test_contextmanager_except(self):
state = []
@contextmanager
def woohoo():
state.append(1)
try:
yield 42
except ZeroDivisionError as e:
state.append(e.args[0])
self.assertEqual(state, [1, 42, 999])
with woohoo() as x:
self.assertEqual(state, [1])
self.assertEqual(x, 42)
state.append(x)
raise ZeroDivisionError(999)
self.assertEqual(state, [1, 42, 999])
def test_contextmanager_except_stopiter(self):
stop_exc = StopIteration('spam')
@contextmanager
def woohoo():
yield
try:
with self.assertWarnsRegex(DeprecationWarning,
"StopIteration"):
with woohoo():
raise stop_exc
except Exception as ex:
self.assertIs(ex, stop_exc)
else:
self.fail('StopIteration was suppressed')
def test_contextmanager_except_pep479(self):
code = """\
from __future__ import generator_stop
from contextlib import contextmanager
@contextmanager
def woohoo():
yield
"""
locals = {}
exec(code, locals, locals)
woohoo = locals['woohoo']
stop_exc = StopIteration('spam')
try:
with woohoo():
raise stop_exc
except Exception as ex:
self.assertIs(ex, stop_exc)
else:
self.fail('StopIteration was suppressed')
def test_contextmanager_do_not_unchain_non_stopiteration_exceptions(self):
@contextmanager
def test_issue29692():
try:
yield
except Exception as exc:
raise RuntimeError('issue29692:Chained') from exc
try:
with test_issue29692():
raise ZeroDivisionError
except Exception as ex:
self.assertIs(type(ex), RuntimeError)
self.assertEqual(ex.args[0], 'issue29692:Chained')
self.assertIsInstance(ex.__cause__, ZeroDivisionError)
try:
with test_issue29692():
raise StopIteration('issue29692:Unchained')
except Exception as ex:
self.assertIs(type(ex), StopIteration)
self.assertEqual(ex.args[0], 'issue29692:Unchained')
self.assertIsNone(ex.__cause__)
def _create_contextmanager_attribs(self):
def attribs(**kw):
def decorate(func):
for k,v in kw.items():
setattr(func,k,v)
return func
return decorate
@contextmanager
@attribs(foo='bar')
def baz(spam):
"""Whee!"""
return baz
def test_contextmanager_attribs(self):
baz = self._create_contextmanager_attribs()
self.assertEqual(baz.__name__,'baz')
self.assertEqual(baz.foo, 'bar')
@support.requires_docstrings
def test_contextmanager_doc_attrib(self):
baz = self._create_contextmanager_attribs()
self.assertEqual(baz.__doc__, "Whee!")
@support.requires_docstrings
def test_instance_docstring_given_cm_docstring(self):
baz = self._create_contextmanager_attribs()(None)
self.assertEqual(baz.__doc__, "Whee!")
def test_keywords(self):
# Ensure no keyword arguments are inhibited
@contextmanager
def woohoo(self, func, args, kwds):
yield (self, func, args, kwds)
with woohoo(self=11, func=22, args=33, kwds=44) as target:
self.assertEqual(target, (11, 22, 33, 44))
class ClosingTestCase(unittest.TestCase):
@support.requires_docstrings
def test_instance_docs(self):
# Issue 19330: ensure context manager instances have good docstrings
cm_docstring = closing.__doc__
obj = closing(None)
self.assertEqual(obj.__doc__, cm_docstring)
def test_closing(self):
state = []
class C:
def close(self):
state.append(1)
x = C()
self.assertEqual(state, [])
with closing(x) as y:
self.assertEqual(x, y)
self.assertEqual(state, [1])
def test_closing_error(self):
state = []
class C:
def close(self):
state.append(1)
x = C()
self.assertEqual(state, [])
with self.assertRaises(ZeroDivisionError):
with closing(x) as y:
self.assertEqual(x, y)
1 / 0
self.assertEqual(state, [1])
class FileContextTestCase(unittest.TestCase):
def testWithOpen(self):
tfn = tempfile.mktemp()
try:
f = None
with open(tfn, "w") as f:
self.assertFalse(f.closed)
f.write("Booh\n")
self.assertTrue(f.closed)
f = None
with self.assertRaises(ZeroDivisionError):
with open(tfn, "r") as f:
self.assertFalse(f.closed)
self.assertEqual(f.read(), "Booh\n")
1 / 0
self.assertTrue(f.closed)
finally:
support.unlink(tfn)
@unittest.skipUnless(threading, 'Threading required for this test.')
class LockContextTestCase(unittest.TestCase):
def boilerPlate(self, lock, locked):
self.assertFalse(locked())
with lock:
self.assertTrue(locked())
self.assertFalse(locked())
with self.assertRaises(ZeroDivisionError):
with lock:
self.assertTrue(locked())
1 / 0
self.assertFalse(locked())
def testWithLock(self):
lock = threading.Lock()
self.boilerPlate(lock, lock.locked)
def testWithRLock(self):
lock = threading.RLock()
self.boilerPlate(lock, lock._is_owned)
def testWithCondition(self):
lock = threading.Condition()
def locked():
return lock._is_owned()
self.boilerPlate(lock, locked)
def testWithSemaphore(self):
lock = threading.Semaphore()
def locked():
if lock.acquire(False):
lock.release()
return False
else:
return True
self.boilerPlate(lock, locked)
def testWithBoundedSemaphore(self):
lock = threading.BoundedSemaphore()
def locked():
if lock.acquire(False):
lock.release()
return False
else:
return True
self.boilerPlate(lock, locked)
class mycontext(ContextDecorator):
"""Example decoration-compatible context manager for testing"""
started = False
exc = None
catch = False
def __enter__(self):
self.started = True
return self
def __exit__(self, *exc):
self.exc = exc
return self.catch
class TestContextDecorator(unittest.TestCase):
@support.requires_docstrings
def test_instance_docs(self):
# Issue 19330: ensure context manager instances have good docstrings
cm_docstring = mycontext.__doc__
obj = mycontext()
self.assertEqual(obj.__doc__, cm_docstring)
def test_contextdecorator(self):
context = mycontext()
with context as result:
self.assertIs(result, context)
self.assertTrue(context.started)
self.assertEqual(context.exc, (None, None, None))
def test_contextdecorator_with_exception(self):
context = mycontext()
with self.assertRaisesRegex(NameError, 'foo'):
with context:
raise NameError('foo')
self.assertIsNotNone(context.exc)
self.assertIs(context.exc[0], NameError)
context = mycontext()
context.catch = True
with context:
raise NameError('foo')
self.assertIsNotNone(context.exc)
self.assertIs(context.exc[0], NameError)
def test_decorator(self):
context = mycontext()
@context
def test():
self.assertIsNone(context.exc)
self.assertTrue(context.started)
test()
self.assertEqual(context.exc, (None, None, None))
def test_decorator_with_exception(self):
context = mycontext()
@context
def test():
self.assertIsNone(context.exc)
self.assertTrue(context.started)
raise NameError('foo')
with self.assertRaisesRegex(NameError, 'foo'):
test()
self.assertIsNotNone(context.exc)
self.assertIs(context.exc[0], NameError)
def test_decorating_method(self):
context = mycontext()
class Test(object):
@context
def method(self, a, b, c=None):
self.a = a
self.b = b
self.c = c
# these tests are for argument passing when used as a decorator
test = Test()
test.method(1, 2)
self.assertEqual(test.a, 1)
self.assertEqual(test.b, 2)
self.assertEqual(test.c, None)
test = Test()
test.method('a', 'b', 'c')
self.assertEqual(test.a, 'a')
self.assertEqual(test.b, 'b')
self.assertEqual(test.c, 'c')
test = Test()
test.method(a=1, b=2)
self.assertEqual(test.a, 1)
self.assertEqual(test.b, 2)
def test_typo_enter(self):
class mycontext(ContextDecorator):
def __unter__(self):
pass
def __exit__(self, *exc):
pass
with self.assertRaises(AttributeError):
with mycontext():
pass
def test_typo_exit(self):
class mycontext(ContextDecorator):
def __enter__(self):
pass
def __uxit__(self, *exc):
pass
with self.assertRaises(AttributeError):
with mycontext():
pass
def test_contextdecorator_as_mixin(self):
class somecontext(object):
started = False
exc = None
def __enter__(self):
self.started = True
return self
def __exit__(self, *exc):
self.exc = exc
class mycontext(somecontext, ContextDecorator):
pass
context = mycontext()
@context
def test():
self.assertIsNone(context.exc)
self.assertTrue(context.started)
test()
self.assertEqual(context.exc, (None, None, None))
def test_contextmanager_as_decorator(self):
@contextmanager
def woohoo(y):
state.append(y)
yield
state.append(999)
state = []
@woohoo(1)
def test(x):
self.assertEqual(state, [1])
state.append(x)
test('something')
self.assertEqual(state, [1, 'something', 999])
# Issue #11647: Ensure the decorated function is 'reusable'
state = []
test('something else')
self.assertEqual(state, [1, 'something else', 999])
class TestExitStack(unittest.TestCase):
@support.requires_docstrings
def test_instance_docs(self):
# Issue 19330: ensure context manager instances have good docstrings
cm_docstring = ExitStack.__doc__
obj = ExitStack()
self.assertEqual(obj.__doc__, cm_docstring)
def test_no_resources(self):
with ExitStack():
pass
def test_callback(self):
expected = [
((), {}),
((1,), {}),
((1,2), {}),
((), dict(example=1)),
((1,), dict(example=1)),
((1,2), dict(example=1)),
]
result = []
def _exit(*args, **kwds):
"""Test metadata propagation"""
result.append((args, kwds))
with ExitStack() as stack:
for args, kwds in reversed(expected):
if args and kwds:
f = stack.callback(_exit, *args, **kwds)
elif args:
f = stack.callback(_exit, *args)
elif kwds:
f = stack.callback(_exit, **kwds)
else:
f = stack.callback(_exit)
self.assertIs(f, _exit)
for wrapper in stack._exit_callbacks:
self.assertIs(wrapper.__wrapped__, _exit)
self.assertNotEqual(wrapper.__name__, _exit.__name__)
self.assertIsNone(wrapper.__doc__, _exit.__doc__)
self.assertEqual(result, expected)
def test_push(self):
exc_raised = ZeroDivisionError
def _expect_exc(exc_type, exc, exc_tb):
self.assertIs(exc_type, exc_raised)
def _suppress_exc(*exc_details):
return True
def _expect_ok(exc_type, exc, exc_tb):
self.assertIsNone(exc_type)
self.assertIsNone(exc)
self.assertIsNone(exc_tb)
class ExitCM(object):
def __init__(self, check_exc):
self.check_exc = check_exc
def __enter__(self):
self.fail("Should not be called!")
def __exit__(self, *exc_details):
self.check_exc(*exc_details)
with ExitStack() as stack:
stack.push(_expect_ok)
self.assertIs(stack._exit_callbacks[-1], _expect_ok)
cm = ExitCM(_expect_ok)
stack.push(cm)
self.assertIs(stack._exit_callbacks[-1].__self__, cm)
stack.push(_suppress_exc)
self.assertIs(stack._exit_callbacks[-1], _suppress_exc)
cm = ExitCM(_expect_exc)
stack.push(cm)
self.assertIs(stack._exit_callbacks[-1].__self__, cm)
stack.push(_expect_exc)
self.assertIs(stack._exit_callbacks[-1], _expect_exc)
stack.push(_expect_exc)
self.assertIs(stack._exit_callbacks[-1], _expect_exc)
1/0
def test_enter_context(self):
class TestCM(object):
def __enter__(self):
result.append(1)
def __exit__(self, *exc_details):
result.append(3)
result = []
cm = TestCM()
with ExitStack() as stack:
@stack.callback # Registered first => cleaned up last
def _exit():
result.append(4)
self.assertIsNotNone(_exit)
stack.enter_context(cm)
self.assertIs(stack._exit_callbacks[-1].__self__, cm)
result.append(2)
self.assertEqual(result, [1, 2, 3, 4])
def test_close(self):
result = []
with ExitStack() as stack:
@stack.callback
def _exit():
result.append(1)
self.assertIsNotNone(_exit)
stack.close()
result.append(2)
self.assertEqual(result, [1, 2])
def test_pop_all(self):
result = []
with ExitStack() as stack:
@stack.callback
def _exit():
result.append(3)
self.assertIsNotNone(_exit)
new_stack = stack.pop_all()
result.append(1)
result.append(2)
new_stack.close()
self.assertEqual(result, [1, 2, 3])
def test_exit_raise(self):
with self.assertRaises(ZeroDivisionError):
with ExitStack() as stack:
stack.push(lambda *exc: False)
1/0
def test_exit_suppress(self):
with ExitStack() as stack:
stack.push(lambda *exc: True)
1/0
def test_exit_exception_chaining_reference(self):
# Sanity check to make sure that ExitStack chaining matches
# actual nested with statements
class RaiseExc:
def __init__(self, exc):
self.exc = exc
def __enter__(self):
return self
def __exit__(self, *exc_details):
raise self.exc
class RaiseExcWithContext:
def __init__(self, outer, inner):
self.outer = outer
self.inner = inner
def __enter__(self):
return self
def __exit__(self, *exc_details):
try:
raise self.inner
except:
raise self.outer
class SuppressExc:
def __enter__(self):
return self
def __exit__(self, *exc_details):
type(self).saved_details = exc_details
return True
try:
with RaiseExc(IndexError):
with RaiseExcWithContext(KeyError, AttributeError):
with SuppressExc():
with RaiseExc(ValueError):
1 / 0
except IndexError as exc:
self.assertIsInstance(exc.__context__, KeyError)
self.assertIsInstance(exc.__context__.__context__, AttributeError)
# Inner exceptions were suppressed
self.assertIsNone(exc.__context__.__context__.__context__)
else:
self.fail("Expected IndexError, but no exception was raised")
# Check the inner exceptions
inner_exc = SuppressExc.saved_details[1]
self.assertIsInstance(inner_exc, ValueError)
self.assertIsInstance(inner_exc.__context__, ZeroDivisionError)
def test_exit_exception_chaining(self):
# Ensure exception chaining matches the reference behaviour
def raise_exc(exc):
raise exc
saved_details = None
def suppress_exc(*exc_details):
nonlocal saved_details
saved_details = exc_details
return True
try:
with ExitStack() as stack:
stack.callback(raise_exc, IndexError)
stack.callback(raise_exc, KeyError)
stack.callback(raise_exc, AttributeError)
stack.push(suppress_exc)
stack.callback(raise_exc, ValueError)
1 / 0
except IndexError as exc:
self.assertIsInstance(exc.__context__, KeyError)
self.assertIsInstance(exc.__context__.__context__, AttributeError)
# Inner exceptions were suppressed
self.assertIsNone(exc.__context__.__context__.__context__)
else:
self.fail("Expected IndexError, but no exception was raised")
# Check the inner exceptions
inner_exc = saved_details[1]
self.assertIsInstance(inner_exc, ValueError)
self.assertIsInstance(inner_exc.__context__, ZeroDivisionError)
def test_exit_exception_non_suppressing(self):
# http://bugs.python.org/issue19092
def raise_exc(exc):
raise exc
def suppress_exc(*exc_details):
return True
try:
with ExitStack() as stack:
stack.callback(lambda: None)
stack.callback(raise_exc, IndexError)
except Exception as exc:
self.assertIsInstance(exc, IndexError)
else:
self.fail("Expected IndexError, but no exception was raised")
try:
with ExitStack() as stack:
stack.callback(raise_exc, KeyError)
stack.push(suppress_exc)
stack.callback(raise_exc, IndexError)
except Exception as exc:
self.assertIsInstance(exc, KeyError)
else:
self.fail("Expected KeyError, but no exception was raised")
def test_exit_exception_with_correct_context(self):
# http://bugs.python.org/issue20317
@contextmanager
def gets_the_context_right(exc):
try:
yield
finally:
raise exc
exc1 = Exception(1)
exc2 = Exception(2)
exc3 = Exception(3)
exc4 = Exception(4)
# The contextmanager already fixes the context, so prior to the
# fix, ExitStack would try to fix it *again* and get into an
# infinite self-referential loop
try:
with ExitStack() as stack:
stack.enter_context(gets_the_context_right(exc4))
stack.enter_context(gets_the_context_right(exc3))
stack.enter_context(gets_the_context_right(exc2))
raise exc1
except Exception as exc:
self.assertIs(exc, exc4)
self.assertIs(exc.__context__, exc3)
self.assertIs(exc.__context__.__context__, exc2)
self.assertIs(exc.__context__.__context__.__context__, exc1)
self.assertIsNone(
exc.__context__.__context__.__context__.__context__)
def test_exit_exception_with_existing_context(self):
# Addresses a lack of test coverage discovered after checking in a
# fix for issue 20317 that still contained debugging code.
def raise_nested(inner_exc, outer_exc):
try:
raise inner_exc
finally:
raise outer_exc
exc1 = Exception(1)
exc2 = Exception(2)
exc3 = Exception(3)
exc4 = Exception(4)
exc5 = Exception(5)
try:
with ExitStack() as stack:
stack.callback(raise_nested, exc4, exc5)
stack.callback(raise_nested, exc2, exc3)
raise exc1
except Exception as exc:
self.assertIs(exc, exc5)
self.assertIs(exc.__context__, exc4)
self.assertIs(exc.__context__.__context__, exc3)
self.assertIs(exc.__context__.__context__.__context__, exc2)
self.assertIs(
exc.__context__.__context__.__context__.__context__, exc1)
self.assertIsNone(
exc.__context__.__context__.__context__.__context__.__context__)
def test_body_exception_suppress(self):
def suppress_exc(*exc_details):
return True
try:
with ExitStack() as stack:
stack.push(suppress_exc)
1/0
except IndexError as exc:
self.fail("Expected no exception, got IndexError")
def test_exit_exception_chaining_suppress(self):
with ExitStack() as stack:
stack.push(lambda *exc: True)
stack.push(lambda *exc: 1/0)
stack.push(lambda *exc: {}[1])
def test_excessive_nesting(self):
# The original implementation would die with RecursionError here
with ExitStack() as stack:
for i in range(10000):
stack.callback(int)
def test_instance_bypass(self):
class Example(object): pass
cm = Example()
cm.__exit__ = object()
stack = ExitStack()
self.assertRaises(AttributeError, stack.enter_context, cm)
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:
redirect_stream = None
orig_stream = None
@support.requires_docstrings
def test_instance_docs(self):
# Issue 19330: ensure context manager instances have good docstrings
cm_docstring = self.redirect_stream.__doc__
obj = self.redirect_stream(None)
self.assertEqual(obj.__doc__, cm_docstring)
def test_no_redirect_in_init(self):
orig_stdout = getattr(sys, self.orig_stream)
self.redirect_stream(None)
self.assertIs(getattr(sys, self.orig_stream), orig_stdout)
def test_redirect_to_string_io(self):
f = io.StringIO()
msg = "Consider an API like help(), which prints directly to stdout"
orig_stdout = getattr(sys, self.orig_stream)
with self.redirect_stream(f):
print(msg, file=getattr(sys, self.orig_stream))
self.assertIs(getattr(sys, self.orig_stream), orig_stdout)
s = f.getvalue().strip()
self.assertEqual(s, msg)
def test_enter_result_is_target(self):
f = io.StringIO()
with self.redirect_stream(f) as enter_result:
self.assertIs(enter_result, f)
def test_cm_is_reusable(self):
f = io.StringIO()
write_to_f = self.redirect_stream(f)
orig_stdout = getattr(sys, self.orig_stream)
with write_to_f:
print("Hello", end=" ", file=getattr(sys, self.orig_stream))
with write_to_f:
print("World!", file=getattr(sys, self.orig_stream))
self.assertIs(getattr(sys, self.orig_stream), orig_stdout)
s = f.getvalue()
self.assertEqual(s, "Hello World!\n")
def test_cm_is_reentrant(self):
f = io.StringIO()
write_to_f = self.redirect_stream(f)
orig_stdout = getattr(sys, self.orig_stream)
with write_to_f:
print("Hello", end=" ", file=getattr(sys, self.orig_stream))
with write_to_f:
print("World!", file=getattr(sys, self.orig_stream))
self.assertIs(getattr(sys, self.orig_stream), orig_stdout)
s = f.getvalue()
self.assertEqual(s, "Hello World!\n")
class TestRedirectStdout(TestRedirectStream, unittest.TestCase):
redirect_stream = redirect_stdout
orig_stream = "stdout"
class TestRedirectStderr(TestRedirectStream, unittest.TestCase):
redirect_stream = redirect_stderr
orig_stream = "stderr"
class TestSuppress(unittest.TestCase):
@support.requires_docstrings
def test_instance_docs(self):
# Issue 19330: ensure context manager instances have good docstrings
cm_docstring = suppress.__doc__
obj = suppress()
self.assertEqual(obj.__doc__, cm_docstring)
def test_no_result_from_enter(self):
with suppress(ValueError) as enter_result:
self.assertIsNone(enter_result)
def test_no_exception(self):
with suppress(ValueError):
self.assertEqual(pow(2, 5), 32)
def test_exact_exception(self):
with suppress(TypeError):
len(5)
def test_exception_hierarchy(self):
with suppress(LookupError):
'Hello'[50]
def test_other_exception(self):
with self.assertRaises(ZeroDivisionError):
with suppress(TypeError):
1/0
def test_no_args(self):
with self.assertRaises(ZeroDivisionError):
with suppress():
1/0
def test_multiple_exception_args(self):
with suppress(ZeroDivisionError, TypeError):
1/0
with suppress(ZeroDivisionError, TypeError):
len(5)
def test_cm_is_reentrant(self):
ignore_exceptions = suppress(Exception)
with ignore_exceptions:
pass
with ignore_exceptions:
len(5)
with ignore_exceptions:
with ignore_exceptions: # Check nested usage
len(5)
outer_continued = True
1/0
self.assertTrue(outer_continued)
if __name__ == "__main__":
unittest.main()
| 31,511 | 992 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_metaclass.py | doctests = """
Basic class construction.
>>> class C:
... def meth(self): print("Hello")
...
>>> C.__class__ is type
True
>>> a = C()
>>> a.__class__ is C
True
>>> a.meth()
Hello
>>>
Use *args notation for the bases.
>>> class A: pass
>>> class B: pass
>>> bases = (A, B)
>>> class C(*bases): pass
>>> C.__bases__ == bases
True
>>>
Use a trivial metaclass.
>>> class M(type):
... pass
...
>>> class C(metaclass=M):
... def meth(self): print("Hello")
...
>>> C.__class__ is M
True
>>> a = C()
>>> a.__class__ is C
True
>>> a.meth()
Hello
>>>
Use **kwds notation for the metaclass keyword.
>>> kwds = {'metaclass': M}
>>> class C(**kwds): pass
...
>>> C.__class__ is M
True
>>> a = C()
>>> a.__class__ is C
True
>>>
Use a metaclass with a __prepare__ static method.
>>> class M(type):
... @staticmethod
... def __prepare__(*args, **kwds):
... print("Prepare called:", args, kwds)
... return dict()
... def __new__(cls, name, bases, namespace, **kwds):
... print("New called:", kwds)
... return type.__new__(cls, name, bases, namespace)
... def __init__(cls, *args, **kwds):
... pass
...
>>> class C(metaclass=M):
... def meth(self): print("Hello")
...
Prepare called: ('C', ()) {}
New called: {}
>>>
Also pass another keyword.
>>> class C(object, metaclass=M, other="haha"):
... pass
...
Prepare called: ('C', (<class 'object'>,)) {'other': 'haha'}
New called: {'other': 'haha'}
>>> C.__class__ is M
True
>>> C.__bases__ == (object,)
True
>>> a = C()
>>> a.__class__ is C
True
>>>
Check that build_class doesn't mutate the kwds dict.
>>> kwds = {'metaclass': type}
>>> class C(**kwds): pass
...
>>> kwds == {'metaclass': type}
True
>>>
Use various combinations of explicit keywords and **kwds.
>>> bases = (object,)
>>> kwds = {'metaclass': M, 'other': 'haha'}
>>> class C(*bases, **kwds): pass
...
Prepare called: ('C', (<class 'object'>,)) {'other': 'haha'}
New called: {'other': 'haha'}
>>> C.__class__ is M
True
>>> C.__bases__ == (object,)
True
>>> class B: pass
>>> kwds = {'other': 'haha'}
>>> class C(B, metaclass=M, *bases, **kwds): pass
...
Prepare called: ('C', (<class 'test.test_metaclass.B'>, <class 'object'>)) {'other': 'haha'}
New called: {'other': 'haha'}
>>> C.__class__ is M
True
>>> C.__bases__ == (B, object)
True
>>>
Check for duplicate keywords.
>>> class C(metaclass=type, metaclass=type): pass
...
Traceback (most recent call last):
[...]
SyntaxError: keyword argument repeated
>>>
Another way.
>>> kwds = {'metaclass': type}
>>> class C(metaclass=type, **kwds): pass
...
Traceback (most recent call last):
[...]
TypeError: __build_class__() got multiple values for keyword argument 'metaclass'
>>>
Use a __prepare__ method that returns an instrumented dict.
>>> class LoggingDict(dict):
... def __setitem__(self, key, value):
... print("d[%r] = %r" % (key, value))
... dict.__setitem__(self, key, value)
...
>>> class Meta(type):
... @staticmethod
... def __prepare__(name, bases):
... return LoggingDict()
...
>>> class C(metaclass=Meta):
... foo = 2+2
... foo = 42
... bar = 123
...
d['__module__'] = 'test.test_metaclass'
d['__qualname__'] = 'C'
d['foo'] = 4
d['foo'] = 42
d['bar'] = 123
>>>
Use a metaclass that doesn't derive from type.
>>> def meta(name, bases, namespace, **kwds):
... print("meta:", name, bases)
... print("ns:", sorted(namespace.items()))
... print("kw:", sorted(kwds.items()))
... return namespace
...
>>> class C(metaclass=meta):
... a = 42
... b = 24
...
meta: C ()
ns: [('__module__', 'test.test_metaclass'), ('__qualname__', 'C'), ('a', 42), ('b', 24)]
kw: []
>>> type(C) is dict
True
>>> print(sorted(C.items()))
[('__module__', 'test.test_metaclass'), ('__qualname__', 'C'), ('a', 42), ('b', 24)]
>>>
And again, with a __prepare__ attribute.
>>> def prepare(name, bases, **kwds):
... print("prepare:", name, bases, sorted(kwds.items()))
... return LoggingDict()
...
>>> meta.__prepare__ = prepare
>>> class C(metaclass=meta, other="booh"):
... a = 1
... a = 2
... b = 3
...
prepare: C () [('other', 'booh')]
d['__module__'] = 'test.test_metaclass'
d['__qualname__'] = 'C'
d['a'] = 1
d['a'] = 2
d['b'] = 3
meta: C ()
ns: [('__module__', 'test.test_metaclass'), ('__qualname__', 'C'), ('a', 2), ('b', 3)]
kw: [('other', 'booh')]
>>>
The default metaclass must define a __prepare__() method.
>>> type.__prepare__()
{}
>>>
Make sure it works with subclassing.
>>> class M(type):
... @classmethod
... def __prepare__(cls, *args, **kwds):
... d = super().__prepare__(*args, **kwds)
... d["hello"] = 42
... return d
...
>>> class C(metaclass=M):
... print(hello)
...
42
>>> print(C.hello)
42
>>>
Test failures in looking up the __prepare__ method work.
>>> class ObscureException(Exception):
... pass
>>> class FailDescr:
... def __get__(self, instance, owner):
... raise ObscureException
>>> class Meta(type):
... __prepare__ = FailDescr()
>>> class X(metaclass=Meta):
... pass
Traceback (most recent call last):
[...]
test.test_metaclass.ObscureException
"""
import sys
# Trace function introduces __locals__ which causes various tests to fail.
if hasattr(sys, 'gettrace') and sys.gettrace():
__test__ = {}
else:
__test__ = {'doctests' : doctests}
def test_main(verbose=False):
from test import support
from test import test_metaclass
support.run_doctest(test_metaclass, verbose)
if __name__ == "__main__":
test_main(verbose=True)
| 6,350 | 266 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_bigmem.py | """Bigmem tests - tests for the 32-bit boundary in containers.
These tests try to exercise the 32-bit boundary that is sometimes, if
rarely, exceeded in practice, but almost never tested. They are really only
meaningful on 64-bit builds on machines with a *lot* of memory, but the
tests are always run, usually with very low memory limits to make sure the
tests themselves don't suffer from bitrot. To run them for real, pass a
high memory limit to regrtest, with the -M option.
"""
from test import support
from test.support import bigmemtest, _1G, _2G, _4G
import unittest
import operator
import sys
from encodings import (
raw_unicode_escape,
utf_7,
utf_32,
latin_1,
raw_unicode_escape,
)
# These tests all use one of the bigmemtest decorators to indicate how much
# memory they use and how much memory they need to be even meaningful. The
# decorators take two arguments: a 'memuse' indicator declaring
# (approximate) bytes per size-unit the test will use (at peak usage), and a
# 'minsize' indicator declaring a minimum *useful* size. A test that
# allocates a bytestring to test various operations near the end will have a
# minsize of at least 2Gb (or it wouldn't reach the 32-bit limit, so the
# test wouldn't be very useful) and a memuse of 1 (one byte per size-unit,
# if it allocates only one big string at a time.)
#
# When run with a memory limit set, both decorators skip tests that need
# more memory than available to be meaningful. The precisionbigmemtest will
# always pass minsize as size, even if there is much more memory available.
# The bigmemtest decorator will scale size upward to fill available memory.
#
# Bigmem testing houserules:
#
# - Try not to allocate too many large objects. It's okay to rely on
# refcounting semantics, and don't forget that 's = create_largestring()'
# doesn't release the old 's' (if it exists) until well after its new
# value has been created. Use 'del s' before the create_largestring call.
#
# - Do *not* compare large objects using assertEqual, assertIn or similar.
# It's a lengthy operation and the errormessage will be utterly useless
# due to its size. To make sure whether a result has the right contents,
# better to use the strip or count methods, or compare meaningful slices.
#
# - Don't forget to test for large indices, offsets and results and such,
# in addition to large sizes. Anything that probes the 32-bit boundary.
#
# - When repeating an object (say, a substring, or a small list) to create
# a large object, make the subobject of a length that is not a power of
# 2. That way, int-wrapping problems are more easily detected.
#
# - Despite the bigmemtest decorator, all tests will actually be called
# with a much smaller number too, in the normal test run (5Kb currently.)
# This is so the tests themselves get frequent testing.
# Consequently, always make all large allocations based on the
# passed-in 'size', and don't rely on the size being very large. Also,
# memuse-per-size should remain sane (less than a few thousand); if your
# test uses more, adjust 'size' upward, instead.
# BEWARE: it seems that one failing test can yield other subsequent tests to
# fail as well. I do not know whether it is due to memory fragmentation
# issues, or other specifics of the platform malloc() routine.
ascii_char_size = 1
ucs2_char_size = 2
ucs4_char_size = 4
class BaseStrTest:
def _test_capitalize(self, size):
_ = self.from_latin1
SUBSTR = self.from_latin1(' abc def ghi')
s = _('-') * size + SUBSTR
caps = s.capitalize()
self.assertEqual(caps[-len(SUBSTR):],
SUBSTR.capitalize())
self.assertEqual(caps.lstrip(_('-')), SUBSTR)
@bigmemtest(size=_2G + 10, memuse=1)
def test_center(self, size):
SUBSTR = self.from_latin1(' abc def ghi')
s = SUBSTR.center(size)
self.assertEqual(len(s), size)
lpadsize = rpadsize = (len(s) - len(SUBSTR)) // 2
if len(s) % 2:
lpadsize += 1
self.assertEqual(s[lpadsize:-rpadsize], SUBSTR)
self.assertEqual(s.strip(), SUBSTR.strip())
@bigmemtest(size=_2G, memuse=2)
def test_count(self, size):
_ = self.from_latin1
SUBSTR = _(' abc def ghi')
s = _('.') * size + SUBSTR
self.assertEqual(s.count(_('.')), size)
s += _('.')
self.assertEqual(s.count(_('.')), size + 1)
self.assertEqual(s.count(_(' ')), 3)
self.assertEqual(s.count(_('i')), 1)
self.assertEqual(s.count(_('j')), 0)
@bigmemtest(size=_2G, memuse=2)
def test_endswith(self, size):
_ = self.from_latin1
SUBSTR = _(' abc def ghi')
s = _('-') * size + SUBSTR
self.assertTrue(s.endswith(SUBSTR))
self.assertTrue(s.endswith(s))
s2 = _('...') + s
self.assertTrue(s2.endswith(s))
self.assertFalse(s.endswith(_('a') + SUBSTR))
self.assertFalse(SUBSTR.endswith(s))
@bigmemtest(size=_2G + 10, memuse=2)
def test_expandtabs(self, size):
_ = self.from_latin1
s = _('-') * size
tabsize = 8
self.assertTrue(s.expandtabs() == s)
del s
slen, remainder = divmod(size, tabsize)
s = _(' \t') * slen
s = s.expandtabs(tabsize)
self.assertEqual(len(s), size - remainder)
self.assertEqual(len(s.strip(_(' '))), 0)
@bigmemtest(size=_2G, memuse=2)
def test_find(self, size):
_ = self.from_latin1
SUBSTR = _(' abc def ghi')
sublen = len(SUBSTR)
s = _('').join([SUBSTR, _('-') * size, SUBSTR])
self.assertEqual(s.find(_(' ')), 0)
self.assertEqual(s.find(SUBSTR), 0)
self.assertEqual(s.find(_(' '), sublen), sublen + size)
self.assertEqual(s.find(SUBSTR, len(SUBSTR)), sublen + size)
self.assertEqual(s.find(_('i')), SUBSTR.find(_('i')))
self.assertEqual(s.find(_('i'), sublen),
sublen + size + SUBSTR.find(_('i')))
self.assertEqual(s.find(_('i'), size),
sublen + size + SUBSTR.find(_('i')))
self.assertEqual(s.find(_('j')), -1)
@bigmemtest(size=_2G, memuse=2)
def test_index(self, size):
_ = self.from_latin1
SUBSTR = _(' abc def ghi')
sublen = len(SUBSTR)
s = _('').join([SUBSTR, _('-') * size, SUBSTR])
self.assertEqual(s.index(_(' ')), 0)
self.assertEqual(s.index(SUBSTR), 0)
self.assertEqual(s.index(_(' '), sublen), sublen + size)
self.assertEqual(s.index(SUBSTR, sublen), sublen + size)
self.assertEqual(s.index(_('i')), SUBSTR.index(_('i')))
self.assertEqual(s.index(_('i'), sublen),
sublen + size + SUBSTR.index(_('i')))
self.assertEqual(s.index(_('i'), size),
sublen + size + SUBSTR.index(_('i')))
self.assertRaises(ValueError, s.index, _('j'))
@bigmemtest(size=_2G, memuse=2)
def test_isalnum(self, size):
_ = self.from_latin1
SUBSTR = _('123456')
s = _('a') * size + SUBSTR
self.assertTrue(s.isalnum())
s += _('.')
self.assertFalse(s.isalnum())
@bigmemtest(size=_2G, memuse=2)
def test_isalpha(self, size):
_ = self.from_latin1
SUBSTR = _('zzzzzzz')
s = _('a') * size + SUBSTR
self.assertTrue(s.isalpha())
s += _('.')
self.assertFalse(s.isalpha())
@bigmemtest(size=_2G, memuse=2)
def test_isdigit(self, size):
_ = self.from_latin1
SUBSTR = _('123456')
s = _('9') * size + SUBSTR
self.assertTrue(s.isdigit())
s += _('z')
self.assertFalse(s.isdigit())
@bigmemtest(size=_2G, memuse=2)
def test_islower(self, size):
_ = self.from_latin1
chars = _(''.join(
chr(c) for c in range(255) if not chr(c).isupper()))
repeats = size // len(chars) + 2
s = chars * repeats
self.assertTrue(s.islower())
s += _('A')
self.assertFalse(s.islower())
@bigmemtest(size=_2G, memuse=2)
def test_isspace(self, size):
_ = self.from_latin1
whitespace = _(' \f\n\r\t\v')
repeats = size // len(whitespace) + 2
s = whitespace * repeats
self.assertTrue(s.isspace())
s += _('j')
self.assertFalse(s.isspace())
@bigmemtest(size=_2G, memuse=2)
def test_istitle(self, size):
_ = self.from_latin1
SUBSTR = _('123456')
s = _('').join([_('A'), _('a') * size, SUBSTR])
self.assertTrue(s.istitle())
s += _('A')
self.assertTrue(s.istitle())
s += _('aA')
self.assertFalse(s.istitle())
@bigmemtest(size=_2G, memuse=2)
def test_isupper(self, size):
_ = self.from_latin1
chars = _(''.join(
chr(c) for c in range(255) if not chr(c).islower()))
repeats = size // len(chars) + 2
s = chars * repeats
self.assertTrue(s.isupper())
s += _('a')
self.assertFalse(s.isupper())
@bigmemtest(size=_2G, memuse=2)
def test_join(self, size):
_ = self.from_latin1
s = _('A') * size
x = s.join([_('aaaaa'), _('bbbbb')])
self.assertEqual(x.count(_('a')), 5)
self.assertEqual(x.count(_('b')), 5)
self.assertTrue(x.startswith(_('aaaaaA')))
self.assertTrue(x.endswith(_('Abbbbb')))
@bigmemtest(size=_2G + 10, memuse=1)
def test_ljust(self, size):
_ = self.from_latin1
SUBSTR = _(' abc def ghi')
s = SUBSTR.ljust(size)
self.assertTrue(s.startswith(SUBSTR + _(' ')))
self.assertEqual(len(s), size)
self.assertEqual(s.strip(), SUBSTR.strip())
@bigmemtest(size=_2G + 10, memuse=2)
def test_lower(self, size):
_ = self.from_latin1
s = _('A') * size
s = s.lower()
self.assertEqual(len(s), size)
self.assertEqual(s.count(_('a')), size)
@bigmemtest(size=_2G + 10, memuse=1)
def test_lstrip(self, size):
_ = self.from_latin1
SUBSTR = _('abc def ghi')
s = SUBSTR.rjust(size)
self.assertEqual(len(s), size)
self.assertEqual(s.lstrip(), SUBSTR.lstrip())
del s
s = SUBSTR.ljust(size)
self.assertEqual(len(s), size)
# Type-specific optimization
if isinstance(s, (str, bytes)):
stripped = s.lstrip()
self.assertTrue(stripped is s)
@bigmemtest(size=_2G + 10, memuse=2)
def test_replace(self, size):
_ = self.from_latin1
replacement = _('a')
s = _(' ') * size
s = s.replace(_(' '), replacement)
self.assertEqual(len(s), size)
self.assertEqual(s.count(replacement), size)
s = s.replace(replacement, _(' '), size - 4)
self.assertEqual(len(s), size)
self.assertEqual(s.count(replacement), 4)
self.assertEqual(s[-10:], _(' aaaa'))
@bigmemtest(size=_2G, memuse=2)
def test_rfind(self, size):
_ = self.from_latin1
SUBSTR = _(' abc def ghi')
sublen = len(SUBSTR)
s = _('').join([SUBSTR, _('-') * size, SUBSTR])
self.assertEqual(s.rfind(_(' ')), sublen + size + SUBSTR.rfind(_(' ')))
self.assertEqual(s.rfind(SUBSTR), sublen + size)
self.assertEqual(s.rfind(_(' '), 0, size), SUBSTR.rfind(_(' ')))
self.assertEqual(s.rfind(SUBSTR, 0, sublen + size), 0)
self.assertEqual(s.rfind(_('i')), sublen + size + SUBSTR.rfind(_('i')))
self.assertEqual(s.rfind(_('i'), 0, sublen), SUBSTR.rfind(_('i')))
self.assertEqual(s.rfind(_('i'), 0, sublen + size),
SUBSTR.rfind(_('i')))
self.assertEqual(s.rfind(_('j')), -1)
@bigmemtest(size=_2G, memuse=2)
def test_rindex(self, size):
_ = self.from_latin1
SUBSTR = _(' abc def ghi')
sublen = len(SUBSTR)
s = _('').join([SUBSTR, _('-') * size, SUBSTR])
self.assertEqual(s.rindex(_(' ')),
sublen + size + SUBSTR.rindex(_(' ')))
self.assertEqual(s.rindex(SUBSTR), sublen + size)
self.assertEqual(s.rindex(_(' '), 0, sublen + size - 1),
SUBSTR.rindex(_(' ')))
self.assertEqual(s.rindex(SUBSTR, 0, sublen + size), 0)
self.assertEqual(s.rindex(_('i')),
sublen + size + SUBSTR.rindex(_('i')))
self.assertEqual(s.rindex(_('i'), 0, sublen), SUBSTR.rindex(_('i')))
self.assertEqual(s.rindex(_('i'), 0, sublen + size),
SUBSTR.rindex(_('i')))
self.assertRaises(ValueError, s.rindex, _('j'))
@bigmemtest(size=_2G + 10, memuse=1)
def test_rjust(self, size):
_ = self.from_latin1
SUBSTR = _(' abc def ghi')
s = SUBSTR.ljust(size)
self.assertTrue(s.startswith(SUBSTR + _(' ')))
self.assertEqual(len(s), size)
self.assertEqual(s.strip(), SUBSTR.strip())
@bigmemtest(size=_2G + 10, memuse=1)
def test_rstrip(self, size):
_ = self.from_latin1
SUBSTR = _(' abc def ghi')
s = SUBSTR.ljust(size)
self.assertEqual(len(s), size)
self.assertEqual(s.rstrip(), SUBSTR.rstrip())
del s
s = SUBSTR.rjust(size)
self.assertEqual(len(s), size)
# Type-specific optimization
if isinstance(s, (str, bytes)):
stripped = s.rstrip()
self.assertTrue(stripped is s)
# The test takes about size bytes to build a string, and then about
# sqrt(size) substrings of sqrt(size) in size and a list to
# hold sqrt(size) items. It's close but just over 2x size.
@bigmemtest(size=_2G, memuse=2.1)
def test_split_small(self, size):
_ = self.from_latin1
# Crudely calculate an estimate so that the result of s.split won't
# take up an inordinate amount of memory
chunksize = int(size ** 0.5 + 2)
SUBSTR = _('a') + _(' ') * chunksize
s = SUBSTR * chunksize
l = s.split()
self.assertEqual(len(l), chunksize)
expected = _('a')
for item in l:
self.assertEqual(item, expected)
del l
l = s.split(_('a'))
self.assertEqual(len(l), chunksize + 1)
expected = _(' ') * chunksize
for item in filter(None, l):
self.assertEqual(item, expected)
# Allocates a string of twice size (and briefly two) and a list of
# size. Because of internal affairs, the s.split() call produces a
# list of size times the same one-character string, so we only
# suffer for the list size. (Otherwise, it'd cost another 48 times
# size in bytes!) Nevertheless, a list of size takes
# 8*size bytes.
@bigmemtest(size=_2G + 5, memuse=2 * ascii_char_size + 8)
def test_split_large(self, size):
_ = self.from_latin1
s = _(' a') * size + _(' ')
l = s.split()
self.assertEqual(len(l), size)
self.assertEqual(set(l), set([_('a')]))
del l
l = s.split(_('a'))
self.assertEqual(len(l), size + 1)
self.assertEqual(set(l), set([_(' ')]))
@bigmemtest(size=_2G, memuse=2.1)
def test_splitlines(self, size):
_ = self.from_latin1
# Crudely calculate an estimate so that the result of s.split won't
# take up an inordinate amount of memory
chunksize = int(size ** 0.5 + 2) // 2
SUBSTR = _(' ') * chunksize + _('\n') + _(' ') * chunksize + _('\r\n')
s = SUBSTR * (chunksize * 2)
l = s.splitlines()
self.assertEqual(len(l), chunksize * 4)
expected = _(' ') * chunksize
for item in l:
self.assertEqual(item, expected)
@bigmemtest(size=_2G, memuse=2)
def test_startswith(self, size):
_ = self.from_latin1
SUBSTR = _(' abc def ghi')
s = _('-') * size + SUBSTR
self.assertTrue(s.startswith(s))
self.assertTrue(s.startswith(_('-') * size))
self.assertFalse(s.startswith(SUBSTR))
@bigmemtest(size=_2G, memuse=1)
def test_strip(self, size):
_ = self.from_latin1
SUBSTR = _(' abc def ghi ')
s = SUBSTR.rjust(size)
self.assertEqual(len(s), size)
self.assertEqual(s.strip(), SUBSTR.strip())
del s
s = SUBSTR.ljust(size)
self.assertEqual(len(s), size)
self.assertEqual(s.strip(), SUBSTR.strip())
def _test_swapcase(self, size):
_ = self.from_latin1
SUBSTR = _("aBcDeFG12.'\xa9\x00")
sublen = len(SUBSTR)
repeats = size // sublen + 2
s = SUBSTR * repeats
s = s.swapcase()
self.assertEqual(len(s), sublen * repeats)
self.assertEqual(s[:sublen * 3], SUBSTR.swapcase() * 3)
self.assertEqual(s[-sublen * 3:], SUBSTR.swapcase() * 3)
def _test_title(self, size):
_ = self.from_latin1
SUBSTR = _('SpaaHAaaAaham')
s = SUBSTR * (size // len(SUBSTR) + 2)
s = s.title()
self.assertTrue(s.startswith((SUBSTR * 3).title()))
self.assertTrue(s.endswith(SUBSTR.lower() * 3))
@bigmemtest(size=_2G, memuse=2)
def test_translate(self, size):
_ = self.from_latin1
SUBSTR = _('aZz.z.Aaz.')
trans = bytes.maketrans(b'.aZ', b'-!$')
sublen = len(SUBSTR)
repeats = size // sublen + 2
s = SUBSTR * repeats
s = s.translate(trans)
self.assertEqual(len(s), repeats * sublen)
self.assertEqual(s[:sublen], SUBSTR.translate(trans))
self.assertEqual(s[-sublen:], SUBSTR.translate(trans))
self.assertEqual(s.count(_('.')), 0)
self.assertEqual(s.count(_('!')), repeats * 2)
self.assertEqual(s.count(_('z')), repeats * 3)
@bigmemtest(size=_2G + 5, memuse=2)
def test_upper(self, size):
_ = self.from_latin1
s = _('a') * size
s = s.upper()
self.assertEqual(len(s), size)
self.assertEqual(s.count(_('A')), size)
@bigmemtest(size=_2G + 20, memuse=1)
def test_zfill(self, size):
_ = self.from_latin1
SUBSTR = _('-568324723598234')
s = SUBSTR.zfill(size)
self.assertTrue(s.endswith(_('0') + SUBSTR[1:]))
self.assertTrue(s.startswith(_('-0')))
self.assertEqual(len(s), size)
self.assertEqual(s.count(_('0')), size - len(SUBSTR))
# This test is meaningful even with size < 2G, as long as the
# doubled string is > 2G (but it tests more if both are > 2G :)
@bigmemtest(size=_1G + 2, memuse=3)
def test_concat(self, size):
_ = self.from_latin1
s = _('.') * size
self.assertEqual(len(s), size)
s = s + s
self.assertEqual(len(s), size * 2)
self.assertEqual(s.count(_('.')), size * 2)
# This test is meaningful even with size < 2G, as long as the
# repeated string is > 2G (but it tests more if both are > 2G :)
@bigmemtest(size=_1G + 2, memuse=3)
def test_repeat(self, size):
_ = self.from_latin1
s = _('.') * size
self.assertEqual(len(s), size)
s = s * 2
self.assertEqual(len(s), size * 2)
self.assertEqual(s.count(_('.')), size * 2)
@bigmemtest(size=_2G + 20, memuse=2)
def test_slice_and_getitem(self, size):
_ = self.from_latin1
SUBSTR = _('0123456789')
sublen = len(SUBSTR)
s = SUBSTR * (size // sublen)
stepsize = len(s) // 100
stepsize = stepsize - (stepsize % sublen)
for i in range(0, len(s) - stepsize, stepsize):
self.assertEqual(s[i], SUBSTR[0])
self.assertEqual(s[i:i + sublen], SUBSTR)
self.assertEqual(s[i:i + sublen:2], SUBSTR[::2])
if i > 0:
self.assertEqual(s[i + sublen - 1:i - 1:-3],
SUBSTR[sublen::-3])
# Make sure we do some slicing and indexing near the end of the
# string, too.
self.assertEqual(s[len(s) - 1], SUBSTR[-1])
self.assertEqual(s[-1], SUBSTR[-1])
self.assertEqual(s[len(s) - 10], SUBSTR[0])
self.assertEqual(s[-sublen], SUBSTR[0])
self.assertEqual(s[len(s):], _(''))
self.assertEqual(s[len(s) - 1:], SUBSTR[-1:])
self.assertEqual(s[-1:], SUBSTR[-1:])
self.assertEqual(s[len(s) - sublen:], SUBSTR)
self.assertEqual(s[-sublen:], SUBSTR)
self.assertEqual(len(s[:]), len(s))
self.assertEqual(len(s[:len(s) - 5]), len(s) - 5)
self.assertEqual(len(s[5:-5]), len(s) - 10)
self.assertRaises(IndexError, operator.getitem, s, len(s))
self.assertRaises(IndexError, operator.getitem, s, len(s) + 1)
self.assertRaises(IndexError, operator.getitem, s, len(s) + 1<<31)
@bigmemtest(size=_2G, memuse=2)
def test_contains(self, size):
_ = self.from_latin1
SUBSTR = _('0123456789')
edge = _('-') * (size // 2)
s = _('').join([edge, SUBSTR, edge])
del edge
self.assertTrue(SUBSTR in s)
self.assertFalse(SUBSTR * 2 in s)
self.assertTrue(_('-') in s)
self.assertFalse(_('a') in s)
s += _('a')
self.assertTrue(_('a') in s)
@bigmemtest(size=_2G + 10, memuse=2)
def test_compare(self, size):
_ = self.from_latin1
s1 = _('-') * size
s2 = _('-') * size
self.assertTrue(s1 == s2)
del s2
s2 = s1 + _('a')
self.assertFalse(s1 == s2)
del s2
s2 = _('.') * size
self.assertFalse(s1 == s2)
@bigmemtest(size=_2G + 10, memuse=1)
def test_hash(self, size):
# Not sure if we can do any meaningful tests here... Even if we
# start relying on the exact algorithm used, the result will be
# different depending on the size of the C 'long int'. Even this
# test is dodgy (there's no *guarantee* that the two things should
# have a different hash, even if they, in the current
# implementation, almost always do.)
_ = self.from_latin1
s = _('\x00') * size
h1 = hash(s)
del s
s = _('\x00') * (size + 1)
self.assertNotEqual(h1, hash(s))
class StrTest(unittest.TestCase, BaseStrTest):
def from_latin1(self, s):
return s
def basic_encode_test(self, size, enc, c='.', expectedsize=None):
if expectedsize is None:
expectedsize = size
try:
s = c * size
self.assertEqual(len(s.encode(enc)), expectedsize)
finally:
s = None
def setUp(self):
# HACK: adjust memory use of tests inherited from BaseStrTest
# according to character size.
self._adjusted = {}
for name in dir(BaseStrTest):
if not name.startswith('test_'):
continue
meth = getattr(type(self), name)
try:
memuse = meth.memuse
except AttributeError:
continue
meth.memuse = ascii_char_size * memuse
self._adjusted[name] = memuse
def tearDown(self):
for name, memuse in self._adjusted.items():
getattr(type(self), name).memuse = memuse
@bigmemtest(size=_2G, memuse=ucs4_char_size * 3)
def test_capitalize(self, size):
self._test_capitalize(size)
@bigmemtest(size=_2G, memuse=ucs4_char_size * 3)
def test_title(self, size):
self._test_title(size)
@bigmemtest(size=_2G, memuse=ucs4_char_size * 3)
def test_swapcase(self, size):
self._test_swapcase(size)
# Many codecs convert to the legacy representation first, explaining
# why we add 'ucs4_char_size' to the 'memuse' below.
@bigmemtest(size=_2G + 2, memuse=ascii_char_size + 1)
def test_encode(self, size):
return self.basic_encode_test(size, 'utf-8')
@bigmemtest(size=_4G // 6 + 2, memuse=ascii_char_size + ucs4_char_size + 1)
def test_encode_raw_unicode_escape(self, size):
return
try:
return self.basic_encode_test(size, 'raw_unicode_escape')
except MemoryError:
pass # acceptable on 32-bit
@bigmemtest(size=_4G // 5 + 70, memuse=ascii_char_size + ucs4_char_size + 1)
def test_encode_utf7(self, size):
return
try:
return self.basic_encode_test(size, 'utf7')
except MemoryError:
pass # acceptable on 32-bit
@bigmemtest(size=_4G // 4 + 5, memuse=ascii_char_size + ucs4_char_size + 4)
def test_encode_utf32(self, size):
try:
return self.basic_encode_test(size, 'utf32', expectedsize=4 * size + 4)
except MemoryError:
pass # acceptable on 32-bit
@bigmemtest(size=_2G - 1, memuse=ascii_char_size + 1)
def test_encode_ascii(self, size):
return self.basic_encode_test(size, 'ascii', c='A')
# str % (...) uses a Py_UCS4 intermediate representation
@bigmemtest(size=_2G + 10, memuse=ascii_char_size * 2 + ucs4_char_size)
def test_format(self, size):
s = '-' * size
sf = '%s' % (s,)
self.assertTrue(s == sf)
del sf
sf = '..%s..' % (s,)
self.assertEqual(len(sf), len(s) + 4)
self.assertTrue(sf.startswith('..-'))
self.assertTrue(sf.endswith('-..'))
del s, sf
size //= 2
edge = '-' * size
s = ''.join([edge, '%s', edge])
del edge
s = s % '...'
self.assertEqual(len(s), size * 2 + 3)
self.assertEqual(s.count('.'), 3)
self.assertEqual(s.count('-'), size * 2)
@bigmemtest(size=_2G + 10, memuse=ascii_char_size * 2)
def test_repr_small(self, size):
s = '-' * size
s = repr(s)
self.assertEqual(len(s), size + 2)
self.assertEqual(s[0], "'")
self.assertEqual(s[-1], "'")
self.assertEqual(s.count('-'), size)
del s
# repr() will create a string four times as large as this 'binary
# string', but we don't want to allocate much more than twice
# size in total. (We do extra testing in test_repr_large())
size = size // 5 * 2
s = '\x00' * size
s = repr(s)
self.assertEqual(len(s), size * 4 + 2)
self.assertEqual(s[0], "'")
self.assertEqual(s[-1], "'")
self.assertEqual(s.count('\\'), size)
self.assertEqual(s.count('0'), size * 2)
@bigmemtest(size=_2G + 10, memuse=ascii_char_size * 5)
def test_repr_large(self, size):
s = '\x00' * size
s = repr(s)
self.assertEqual(len(s), size * 4 + 2)
self.assertEqual(s[0], "'")
self.assertEqual(s[-1], "'")
self.assertEqual(s.count('\\'), size)
self.assertEqual(s.count('0'), size * 2)
# ascii() calls encode('ascii', 'backslashreplace'), which itself
# creates a temporary Py_UNICODE representation in addition to the
# original (Py_UCS2) one
# There's also some overallocation when resizing the ascii() result
# that isn't taken into account here.
@bigmemtest(size=_2G // 5 + 1, memuse=ucs2_char_size +
ucs4_char_size + ascii_char_size * 6)
def test_unicode_repr(self, size):
# Use an assigned, but not printable code point.
# It is in the range of the low surrogates \uDC00-\uDFFF.
char = "\uDCBA"
s = char * size
try:
for f in (repr, ascii):
r = f(s)
self.assertEqual(len(r), 2 + (len(f(char)) - 2) * size)
self.assertTrue(r.endswith(r"\udcba'"), r[-10:])
r = None
finally:
r = s = None
@bigmemtest(size=_2G // 5 + 1, memuse=ucs4_char_size * 2 + ascii_char_size * 10)
def test_unicode_repr_wide(self, size):
char = "\U0001DCBA"
s = char * size
try:
for f in (repr, ascii):
r = f(s)
self.assertEqual(len(r), 2 + (len(f(char)) - 2) * size)
self.assertTrue(r.endswith(r"\U0001dcba'"), r[-12:])
r = None
finally:
r = s = None
# The original test_translate is overridden here, so as to get the
# correct size estimate: str.translate() uses an intermediate Py_UCS4
# representation.
@bigmemtest(size=_2G, memuse=ascii_char_size * 2 + ucs4_char_size)
def test_translate(self, size):
_ = self.from_latin1
SUBSTR = _('aZz.z.Aaz.')
trans = {
ord(_('.')): _('-'),
ord(_('a')): _('!'),
ord(_('Z')): _('$'),
}
sublen = len(SUBSTR)
repeats = size // sublen + 2
s = SUBSTR * repeats
s = s.translate(trans)
self.assertEqual(len(s), repeats * sublen)
self.assertEqual(s[:sublen], SUBSTR.translate(trans))
self.assertEqual(s[-sublen:], SUBSTR.translate(trans))
self.assertEqual(s.count(_('.')), 0)
self.assertEqual(s.count(_('!')), repeats * 2)
self.assertEqual(s.count(_('z')), repeats * 3)
class BytesTest(unittest.TestCase, BaseStrTest):
def from_latin1(self, s):
return s.encode("latin-1")
@bigmemtest(size=_2G + 2, memuse=1 + ascii_char_size)
def test_decode(self, size):
s = self.from_latin1('.') * size
self.assertEqual(len(s.decode('utf-8')), size)
@bigmemtest(size=_2G, memuse=2)
def test_capitalize(self, size):
self._test_capitalize(size)
@bigmemtest(size=_2G, memuse=2)
def test_title(self, size):
self._test_title(size)
@bigmemtest(size=_2G, memuse=2)
def test_swapcase(self, size):
self._test_swapcase(size)
class BytearrayTest(unittest.TestCase, BaseStrTest):
def from_latin1(self, s):
return bytearray(s.encode("latin-1"))
@bigmemtest(size=_2G + 2, memuse=1 + ascii_char_size)
def test_decode(self, size):
s = self.from_latin1('.') * size
self.assertEqual(len(s.decode('utf-8')), size)
@bigmemtest(size=_2G, memuse=2)
def test_capitalize(self, size):
self._test_capitalize(size)
@bigmemtest(size=_2G, memuse=2)
def test_title(self, size):
self._test_title(size)
@bigmemtest(size=_2G, memuse=2)
def test_swapcase(self, size):
self._test_swapcase(size)
test_hash = None
test_split_large = None
class TupleTest(unittest.TestCase):
# Tuples have a small, fixed-sized head and an array of pointers to
# data. Since we're testing 64-bit addressing, we can assume that the
# pointers are 8 bytes, and that thus that the tuples take up 8 bytes
# per size.
# As a side-effect of testing long tuples, these tests happen to test
# having more than 2<<31 references to any given object. Hence the
# use of different types of objects as contents in different tests.
@bigmemtest(size=_2G + 2, memuse=16)
def test_compare(self, size):
t1 = ('',) * size
t2 = ('',) * size
self.assertTrue(t1 == t2)
del t2
t2 = ('',) * (size + 1)
self.assertFalse(t1 == t2)
del t2
t2 = (1,) * size
self.assertFalse(t1 == t2)
# Test concatenating into a single tuple of more than 2G in length,
# and concatenating a tuple of more than 2G in length separately, so
# the smaller test still gets run even if there isn't memory for the
# larger test (but we still let the tester know the larger test is
# skipped, in verbose mode.)
def basic_concat_test(self, size):
t = ((),) * size
self.assertEqual(len(t), size)
t = t + t
self.assertEqual(len(t), size * 2)
@bigmemtest(size=_2G // 2 + 2, memuse=24)
def test_concat_small(self, size):
return self.basic_concat_test(size)
@bigmemtest(size=_2G + 2, memuse=24)
def test_concat_large(self, size):
return self.basic_concat_test(size)
@bigmemtest(size=_2G // 5 + 10, memuse=8 * 5)
def test_contains(self, size):
t = (1, 2, 3, 4, 5) * size
self.assertEqual(len(t), size * 5)
self.assertTrue(5 in t)
self.assertFalse((1, 2, 3, 4, 5) in t)
self.assertFalse(0 in t)
@bigmemtest(size=_2G + 10, memuse=8)
def test_hash(self, size):
t1 = (0,) * size
h1 = hash(t1)
del t1
t2 = (0,) * (size + 1)
self.assertFalse(h1 == hash(t2))
@bigmemtest(size=_2G + 10, memuse=8)
def test_index_and_slice(self, size):
t = (None,) * size
self.assertEqual(len(t), size)
self.assertEqual(t[-1], None)
self.assertEqual(t[5], None)
self.assertEqual(t[size - 1], None)
self.assertRaises(IndexError, operator.getitem, t, size)
self.assertEqual(t[:5], (None,) * 5)
self.assertEqual(t[-5:], (None,) * 5)
self.assertEqual(t[20:25], (None,) * 5)
self.assertEqual(t[-25:-20], (None,) * 5)
self.assertEqual(t[size - 5:], (None,) * 5)
self.assertEqual(t[size - 5:size], (None,) * 5)
self.assertEqual(t[size - 6:size - 2], (None,) * 4)
self.assertEqual(t[size:size], ())
self.assertEqual(t[size:size+5], ())
# Like test_concat, split in two.
def basic_test_repeat(self, size):
t = ('',) * size
self.assertEqual(len(t), size)
t = t * 2
self.assertEqual(len(t), size * 2)
@bigmemtest(size=_2G // 2 + 2, memuse=24)
def test_repeat_small(self, size):
return self.basic_test_repeat(size)
@bigmemtest(size=_2G + 2, memuse=24)
def test_repeat_large(self, size):
return self.basic_test_repeat(size)
@bigmemtest(size=_1G - 1, memuse=12)
def test_repeat_large_2(self, size):
return self.basic_test_repeat(size)
@bigmemtest(size=_1G - 1, memuse=9)
def test_from_2G_generator(self, size):
self.skipTest("test needs much more memory than advertised, see issue5438")
try:
t = tuple(range(size))
except MemoryError:
pass # acceptable on 32-bit
else:
count = 0
for item in t:
self.assertEqual(item, count)
count += 1
self.assertEqual(count, size)
@bigmemtest(size=_1G - 25, memuse=9)
def test_from_almost_2G_generator(self, size):
self.skipTest("test needs much more memory than advertised, see issue5438")
try:
t = tuple(range(size))
count = 0
for item in t:
self.assertEqual(item, count)
count += 1
self.assertEqual(count, size)
except MemoryError:
pass # acceptable, expected on 32-bit
# Like test_concat, split in two.
def basic_test_repr(self, size):
t = (0,) * size
s = repr(t)
# The repr of a tuple of 0's is exactly three times the tuple length.
self.assertEqual(len(s), size * 3)
self.assertEqual(s[:5], '(0, 0')
self.assertEqual(s[-5:], '0, 0)')
self.assertEqual(s.count('0'), size)
@bigmemtest(size=_2G // 3 + 2, memuse=8 + 3 * ascii_char_size)
def test_repr_small(self, size):
return self.basic_test_repr(size)
@bigmemtest(size=_2G + 2, memuse=8 + 3 * ascii_char_size)
def test_repr_large(self, size):
return self.basic_test_repr(size)
class ListTest(unittest.TestCase):
# Like tuples, lists have a small, fixed-sized head and an array of
# pointers to data, so 8 bytes per size. Also like tuples, we make the
# lists hold references to various objects to test their refcount
# limits.
@bigmemtest(size=_2G + 2, memuse=16)
def test_compare(self, size):
l1 = [''] * size
l2 = [''] * size
self.assertTrue(l1 == l2)
del l2
l2 = [''] * (size + 1)
self.assertFalse(l1 == l2)
del l2
l2 = [2] * size
self.assertFalse(l1 == l2)
# Test concatenating into a single list of more than 2G in length,
# and concatenating a list of more than 2G in length separately, so
# the smaller test still gets run even if there isn't memory for the
# larger test (but we still let the tester know the larger test is
# skipped, in verbose mode.)
def basic_test_concat(self, size):
l = [[]] * size
self.assertEqual(len(l), size)
l = l + l
self.assertEqual(len(l), size * 2)
@bigmemtest(size=_2G // 2 + 2, memuse=24)
def test_concat_small(self, size):
return self.basic_test_concat(size)
@bigmemtest(size=_2G + 2, memuse=24)
def test_concat_large(self, size):
return self.basic_test_concat(size)
def basic_test_inplace_concat(self, size):
l = [sys.stdout] * size
l += l
self.assertEqual(len(l), size * 2)
self.assertTrue(l[0] is l[-1])
self.assertTrue(l[size - 1] is l[size + 1])
@bigmemtest(size=_2G // 2 + 2, memuse=24)
def test_inplace_concat_small(self, size):
return self.basic_test_inplace_concat(size)
@bigmemtest(size=_2G + 2, memuse=24)
def test_inplace_concat_large(self, size):
return self.basic_test_inplace_concat(size)
@bigmemtest(size=_2G // 5 + 10, memuse=8 * 5)
def test_contains(self, size):
l = [1, 2, 3, 4, 5] * size
self.assertEqual(len(l), size * 5)
self.assertTrue(5 in l)
self.assertFalse([1, 2, 3, 4, 5] in l)
self.assertFalse(0 in l)
@bigmemtest(size=_2G + 10, memuse=8)
def test_hash(self, size):
l = [0] * size
self.assertRaises(TypeError, hash, l)
@bigmemtest(size=_2G + 10, memuse=8)
def test_index_and_slice(self, size):
l = [None] * size
self.assertEqual(len(l), size)
self.assertEqual(l[-1], None)
self.assertEqual(l[5], None)
self.assertEqual(l[size - 1], None)
self.assertRaises(IndexError, operator.getitem, l, size)
self.assertEqual(l[:5], [None] * 5)
self.assertEqual(l[-5:], [None] * 5)
self.assertEqual(l[20:25], [None] * 5)
self.assertEqual(l[-25:-20], [None] * 5)
self.assertEqual(l[size - 5:], [None] * 5)
self.assertEqual(l[size - 5:size], [None] * 5)
self.assertEqual(l[size - 6:size - 2], [None] * 4)
self.assertEqual(l[size:size], [])
self.assertEqual(l[size:size+5], [])
l[size - 2] = 5
self.assertEqual(len(l), size)
self.assertEqual(l[-3:], [None, 5, None])
self.assertEqual(l.count(5), 1)
self.assertRaises(IndexError, operator.setitem, l, size, 6)
self.assertEqual(len(l), size)
l[size - 7:] = [1, 2, 3, 4, 5]
size -= 2
self.assertEqual(len(l), size)
self.assertEqual(l[-7:], [None, None, 1, 2, 3, 4, 5])
l[:7] = [1, 2, 3, 4, 5]
size -= 2
self.assertEqual(len(l), size)
self.assertEqual(l[:7], [1, 2, 3, 4, 5, None, None])
del l[size - 1]
size -= 1
self.assertEqual(len(l), size)
self.assertEqual(l[-1], 4)
del l[-2:]
size -= 2
self.assertEqual(len(l), size)
self.assertEqual(l[-1], 2)
del l[0]
size -= 1
self.assertEqual(len(l), size)
self.assertEqual(l[0], 2)
del l[:2]
size -= 2
self.assertEqual(len(l), size)
self.assertEqual(l[0], 4)
# Like test_concat, split in two.
def basic_test_repeat(self, size):
l = [] * size
self.assertFalse(l)
l = [''] * size
self.assertEqual(len(l), size)
l = l * 2
self.assertEqual(len(l), size * 2)
@bigmemtest(size=_2G // 2 + 2, memuse=24)
def test_repeat_small(self, size):
return self.basic_test_repeat(size)
@bigmemtest(size=_2G + 2, memuse=24)
def test_repeat_large(self, size):
return self.basic_test_repeat(size)
def basic_test_inplace_repeat(self, size):
l = ['']
l *= size
self.assertEqual(len(l), size)
self.assertTrue(l[0] is l[-1])
del l
l = [''] * size
l *= 2
self.assertEqual(len(l), size * 2)
self.assertTrue(l[size - 1] is l[-1])
@bigmemtest(size=_2G // 2 + 2, memuse=16)
def test_inplace_repeat_small(self, size):
return self.basic_test_inplace_repeat(size)
@bigmemtest(size=_2G + 2, memuse=16)
def test_inplace_repeat_large(self, size):
return self.basic_test_inplace_repeat(size)
def basic_test_repr(self, size):
l = [0] * size
s = repr(l)
# The repr of a list of 0's is exactly three times the list length.
self.assertEqual(len(s), size * 3)
self.assertEqual(s[:5], '[0, 0')
self.assertEqual(s[-5:], '0, 0]')
self.assertEqual(s.count('0'), size)
@bigmemtest(size=_2G // 3 + 2, memuse=8 + 3 * ascii_char_size)
def test_repr_small(self, size):
return self.basic_test_repr(size)
@bigmemtest(size=_2G + 2, memuse=8 + 3 * ascii_char_size)
def test_repr_large(self, size):
return self.basic_test_repr(size)
# list overallocates ~1/8th of the total size (on first expansion) so
# the single list.append call puts memuse at 9 bytes per size.
@bigmemtest(size=_2G, memuse=9)
def test_append(self, size):
l = [object()] * size
l.append(object())
self.assertEqual(len(l), size+1)
self.assertTrue(l[-3] is l[-2])
self.assertFalse(l[-2] is l[-1])
@bigmemtest(size=_2G // 5 + 2, memuse=8 * 5)
def test_count(self, size):
l = [1, 2, 3, 4, 5] * size
self.assertEqual(l.count(1), size)
self.assertEqual(l.count("1"), 0)
def basic_test_extend(self, size):
l = [object] * size
l.extend(l)
self.assertEqual(len(l), size * 2)
self.assertTrue(l[0] is l[-1])
self.assertTrue(l[size - 1] is l[size + 1])
@bigmemtest(size=_2G // 2 + 2, memuse=16)
def test_extend_small(self, size):
return self.basic_test_extend(size)
@bigmemtest(size=_2G + 2, memuse=16)
def test_extend_large(self, size):
return self.basic_test_extend(size)
@bigmemtest(size=_2G // 5 + 2, memuse=8 * 5)
def test_index(self, size):
l = [1, 2, 3, 4, 5] * size
size *= 5
self.assertEqual(l.index(1), 0)
self.assertEqual(l.index(5, size - 5), size - 1)
self.assertEqual(l.index(5, size - 5, size), size - 1)
self.assertRaises(ValueError, l.index, 1, size - 4, size)
self.assertRaises(ValueError, l.index, 6)
# This tests suffers from overallocation, just like test_append.
@bigmemtest(size=_2G + 10, memuse=9)
def test_insert(self, size):
l = [1.0] * size
l.insert(size - 1, "A")
size += 1
self.assertEqual(len(l), size)
self.assertEqual(l[-3:], [1.0, "A", 1.0])
l.insert(size + 1, "B")
size += 1
self.assertEqual(len(l), size)
self.assertEqual(l[-3:], ["A", 1.0, "B"])
l.insert(1, "C")
size += 1
self.assertEqual(len(l), size)
self.assertEqual(l[:3], [1.0, "C", 1.0])
self.assertEqual(l[size - 3:], ["A", 1.0, "B"])
@bigmemtest(size=_2G // 5 + 4, memuse=8 * 5)
def test_pop(self, size):
l = ["a", "b", "c", "d", "e"] * size
size *= 5
self.assertEqual(len(l), size)
item = l.pop()
size -= 1
self.assertEqual(len(l), size)
self.assertEqual(item, "e")
self.assertEqual(l[-2:], ["c", "d"])
item = l.pop(0)
size -= 1
self.assertEqual(len(l), size)
self.assertEqual(item, "a")
self.assertEqual(l[:2], ["b", "c"])
item = l.pop(size - 2)
size -= 1
self.assertEqual(len(l), size)
self.assertEqual(item, "c")
self.assertEqual(l[-2:], ["b", "d"])
@bigmemtest(size=_2G + 10, memuse=8)
def test_remove(self, size):
l = [10] * size
self.assertEqual(len(l), size)
l.remove(10)
size -= 1
self.assertEqual(len(l), size)
# Because of the earlier l.remove(), this append doesn't trigger
# a resize.
l.append(5)
size += 1
self.assertEqual(len(l), size)
self.assertEqual(l[-2:], [10, 5])
l.remove(5)
size -= 1
self.assertEqual(len(l), size)
self.assertEqual(l[-2:], [10, 10])
@bigmemtest(size=_2G // 5 + 2, memuse=8 * 5)
def test_reverse(self, size):
l = [1, 2, 3, 4, 5] * size
l.reverse()
self.assertEqual(len(l), size * 5)
self.assertEqual(l[-5:], [5, 4, 3, 2, 1])
self.assertEqual(l[:5], [5, 4, 3, 2, 1])
@bigmemtest(size=_2G // 5 + 2, memuse=8 * 5)
def test_sort(self, size):
l = [1, 2, 3, 4, 5] * size
l.sort()
self.assertEqual(len(l), size * 5)
self.assertEqual(l.count(1), size)
self.assertEqual(l[:10], [1] * 10)
self.assertEqual(l[-10:], [5] * 10)
def test_main():
support.run_unittest(StrTest, BytesTest, BytearrayTest,
TupleTest, ListTest)
if __name__ == '__main__':
if len(sys.argv) > 1:
arg = sys.argv[1]
if arg not in ('-v', '-vv'):
support.set_memlimit(arg)
elif len(sys.argv) > 2:
support.set_memlimit(sys.argv[2])
test_main()
| 45,503 | 1,271 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_macpath.py | import macpath
from test import test_genericpath
import unittest
class MacPathTestCase(unittest.TestCase):
def test_abspath(self):
self.assertEqual(macpath.abspath("xx:yy"), "xx:yy")
def test_isabs(self):
isabs = macpath.isabs
self.assertTrue(isabs("xx:yy"))
self.assertTrue(isabs("xx:yy:"))
self.assertTrue(isabs("xx:"))
self.assertFalse(isabs("foo"))
self.assertFalse(isabs(":foo"))
self.assertFalse(isabs(":foo:bar"))
self.assertFalse(isabs(":foo:bar:"))
self.assertTrue(isabs(b"xx:yy"))
self.assertTrue(isabs(b"xx:yy:"))
self.assertTrue(isabs(b"xx:"))
self.assertFalse(isabs(b"foo"))
self.assertFalse(isabs(b":foo"))
self.assertFalse(isabs(b":foo:bar"))
self.assertFalse(isabs(b":foo:bar:"))
def test_split(self):
split = macpath.split
self.assertEqual(split("foo:bar"),
('foo:', 'bar'))
self.assertEqual(split("conky:mountpoint:foo:bar"),
('conky:mountpoint:foo', 'bar'))
self.assertEqual(split(":"), ('', ''))
self.assertEqual(split(":conky:mountpoint:"),
(':conky:mountpoint', ''))
self.assertEqual(split(b"foo:bar"),
(b'foo:', b'bar'))
self.assertEqual(split(b"conky:mountpoint:foo:bar"),
(b'conky:mountpoint:foo', b'bar'))
self.assertEqual(split(b":"), (b'', b''))
self.assertEqual(split(b":conky:mountpoint:"),
(b':conky:mountpoint', b''))
def test_join(self):
join = macpath.join
self.assertEqual(join('a', 'b'), ':a:b')
self.assertEqual(join(':a', 'b'), ':a:b')
self.assertEqual(join(':a:', 'b'), ':a:b')
self.assertEqual(join(':a::', 'b'), ':a::b')
self.assertEqual(join(':a', '::b'), ':a::b')
self.assertEqual(join('a', ':'), ':a:')
self.assertEqual(join('a:', ':'), 'a:')
self.assertEqual(join('a', ''), ':a:')
self.assertEqual(join('a:', ''), 'a:')
self.assertEqual(join('', ''), '')
self.assertEqual(join('', 'a:b'), 'a:b')
self.assertEqual(join('', 'a', 'b'), ':a:b')
self.assertEqual(join('a:b', 'c'), 'a:b:c')
self.assertEqual(join('a:b', ':c'), 'a:b:c')
self.assertEqual(join('a', ':b', ':c'), ':a:b:c')
self.assertEqual(join('a', 'b:'), 'b:')
self.assertEqual(join('a:', 'b:'), 'b:')
self.assertEqual(join(b'a', b'b'), b':a:b')
self.assertEqual(join(b':a', b'b'), b':a:b')
self.assertEqual(join(b':a:', b'b'), b':a:b')
self.assertEqual(join(b':a::', b'b'), b':a::b')
self.assertEqual(join(b':a', b'::b'), b':a::b')
self.assertEqual(join(b'a', b':'), b':a:')
self.assertEqual(join(b'a:', b':'), b'a:')
self.assertEqual(join(b'a', b''), b':a:')
self.assertEqual(join(b'a:', b''), b'a:')
self.assertEqual(join(b'', b''), b'')
self.assertEqual(join(b'', b'a:b'), b'a:b')
self.assertEqual(join(b'', b'a', b'b'), b':a:b')
self.assertEqual(join(b'a:b', b'c'), b'a:b:c')
self.assertEqual(join(b'a:b', b':c'), b'a:b:c')
self.assertEqual(join(b'a', b':b', b':c'), b':a:b:c')
self.assertEqual(join(b'a', b'b:'), b'b:')
self.assertEqual(join(b'a:', b'b:'), b'b:')
def test_splitext(self):
splitext = macpath.splitext
self.assertEqual(splitext(":foo.ext"), (':foo', '.ext'))
self.assertEqual(splitext("foo:foo.ext"), ('foo:foo', '.ext'))
self.assertEqual(splitext(".ext"), ('.ext', ''))
self.assertEqual(splitext("foo.ext:foo"), ('foo.ext:foo', ''))
self.assertEqual(splitext(":foo.ext:"), (':foo.ext:', ''))
self.assertEqual(splitext(""), ('', ''))
self.assertEqual(splitext("foo.bar.ext"), ('foo.bar', '.ext'))
self.assertEqual(splitext(b":foo.ext"), (b':foo', b'.ext'))
self.assertEqual(splitext(b"foo:foo.ext"), (b'foo:foo', b'.ext'))
self.assertEqual(splitext(b".ext"), (b'.ext', b''))
self.assertEqual(splitext(b"foo.ext:foo"), (b'foo.ext:foo', b''))
self.assertEqual(splitext(b":foo.ext:"), (b':foo.ext:', b''))
self.assertEqual(splitext(b""), (b'', b''))
self.assertEqual(splitext(b"foo.bar.ext"), (b'foo.bar', b'.ext'))
def test_ismount(self):
ismount = macpath.ismount
self.assertEqual(ismount("a:"), True)
self.assertEqual(ismount("a:b"), False)
self.assertEqual(ismount("a:b:"), True)
self.assertEqual(ismount(""), False)
self.assertEqual(ismount(":"), False)
self.assertEqual(ismount(b"a:"), True)
self.assertEqual(ismount(b"a:b"), False)
self.assertEqual(ismount(b"a:b:"), True)
self.assertEqual(ismount(b""), False)
self.assertEqual(ismount(b":"), False)
def test_normpath(self):
normpath = macpath.normpath
self.assertEqual(normpath("a:b"), "a:b")
self.assertEqual(normpath("a"), ":a")
self.assertEqual(normpath("a:b::c"), "a:c")
self.assertEqual(normpath("a:b:c:::d"), "a:d")
self.assertRaises(macpath.norm_error, normpath, "a::b")
self.assertRaises(macpath.norm_error, normpath, "a:b:::c")
self.assertEqual(normpath(":"), ":")
self.assertEqual(normpath("a:"), "a:")
self.assertEqual(normpath("a:b:"), "a:b")
self.assertEqual(normpath(b"a:b"), b"a:b")
self.assertEqual(normpath(b"a"), b":a")
self.assertEqual(normpath(b"a:b::c"), b"a:c")
self.assertEqual(normpath(b"a:b:c:::d"), b"a:d")
self.assertRaises(macpath.norm_error, normpath, b"a::b")
self.assertRaises(macpath.norm_error, normpath, b"a:b:::c")
self.assertEqual(normpath(b":"), b":")
self.assertEqual(normpath(b"a:"), b"a:")
self.assertEqual(normpath(b"a:b:"), b"a:b")
class MacCommonTest(test_genericpath.CommonTest, unittest.TestCase):
pathmodule = macpath
test_relpath_errors = None
if __name__ == "__main__":
unittest.main()
| 6,172 | 150 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/signalinterproctester.py | import os
import signal
import subprocess
import sys
import time
import unittest
class SIGUSR1Exception(Exception):
pass
class InterProcessSignalTests(unittest.TestCase):
def setUp(self):
self.got_signals = {'SIGHUP': 0, 'SIGUSR1': 0, 'SIGALRM': 0}
def sighup_handler(self, signum, frame):
self.got_signals['SIGHUP'] += 1
def sigusr1_handler(self, signum, frame):
self.got_signals['SIGUSR1'] += 1
raise SIGUSR1Exception
def wait_signal(self, child, signame):
if child is not None:
# This wait should be interrupted by exc_class
# (if set)
child.wait()
timeout = 10.0
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if self.got_signals[signame]:
return
signal.pause()
self.fail('signal %s not received after %s seconds'
% (signame, timeout))
def subprocess_send_signal(self, pid, signame):
code = 'import os, signal; os.kill(%s, signal.%s)' % (pid, signame)
args = [sys.executable, '-I', '-c', code]
return subprocess.Popen(args)
def test_interprocess_signal(self):
# Install handlers. This function runs in a sub-process, so we
# don't worry about re-setting the default handlers.
signal.signal(signal.SIGHUP, self.sighup_handler)
signal.signal(signal.SIGUSR1, self.sigusr1_handler)
signal.signal(signal.SIGUSR2, signal.SIG_IGN)
signal.signal(signal.SIGALRM, signal.default_int_handler)
# Let the sub-processes know who to send signals to.
pid = str(os.getpid())
with self.subprocess_send_signal(pid, "SIGHUP") as child:
self.wait_signal(child, 'SIGHUP')
self.assertEqual(self.got_signals, {'SIGHUP': 1, 'SIGUSR1': 0,
'SIGALRM': 0})
with self.assertRaises(SIGUSR1Exception):
with self.subprocess_send_signal(pid, "SIGUSR1") as child:
self.wait_signal(child, 'SIGUSR1')
self.assertEqual(self.got_signals, {'SIGHUP': 1, 'SIGUSR1': 1,
'SIGALRM': 0})
with self.subprocess_send_signal(pid, "SIGUSR2") as child:
# Nothing should happen: SIGUSR2 is ignored
child.wait()
try:
with self.assertRaises(KeyboardInterrupt):
signal.alarm(1)
self.wait_signal(None, 'SIGALRM')
self.assertEqual(self.got_signals, {'SIGHUP': 1, 'SIGUSR1': 1,
'SIGALRM': 0})
finally:
signal.alarm(0)
if __name__ == "__main__":
unittest.main()
| 2,761 | 84 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/ann_module3.py | """
Correct syntax for variable annotation that should fail at runtime
in a certain manner. More examples are in test_grammar and test_parser.
"""
def f_bad_ann():
__annotations__[1] = 2
class C_OK:
def __init__(self, x: int) -> None:
self.x: no_such_name = x # This one is OK as proposed by Guido
class D_bad_ann:
def __init__(self, x: int) -> None:
sfel.y: int = 0
def g_bad_ann():
no_such_name.attr: int = 0
| 448 | 19 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_memoryview.py | """Unit tests for the memoryview
Some tests are in test_bytes. Many tests that require _testbuffer.ndarray
are in test_buffer.
"""
import unittest
import test.support
import sys
import gc
import weakref
import array
import io
import copy
import pickle
class AbstractMemoryTests:
source_bytes = b"abcdef"
@property
def _source(self):
return self.source_bytes
@property
def _types(self):
return filter(None, [self.ro_type, self.rw_type])
def check_getitem_with_type(self, tp):
b = tp(self._source)
oldrefcount = sys.getrefcount(b)
m = self._view(b)
self.assertEqual(m[0], ord(b"a"))
self.assertIsInstance(m[0], int)
self.assertEqual(m[5], ord(b"f"))
self.assertEqual(m[-1], ord(b"f"))
self.assertEqual(m[-6], ord(b"a"))
# Bounds checking
self.assertRaises(IndexError, lambda: m[6])
self.assertRaises(IndexError, lambda: m[-7])
self.assertRaises(IndexError, lambda: m[sys.maxsize])
self.assertRaises(IndexError, lambda: m[-sys.maxsize])
# Type checking
self.assertRaises(TypeError, lambda: m[None])
self.assertRaises(TypeError, lambda: m[0.0])
self.assertRaises(TypeError, lambda: m["a"])
m = None
self.assertEqual(sys.getrefcount(b), oldrefcount)
def test_getitem(self):
for tp in self._types:
self.check_getitem_with_type(tp)
def test_iter(self):
for tp in self._types:
b = tp(self._source)
m = self._view(b)
self.assertEqual(list(m), [m[i] for i in range(len(m))])
def test_setitem_readonly(self):
if not self.ro_type:
self.skipTest("no read-only type to test")
b = self.ro_type(self._source)
oldrefcount = sys.getrefcount(b)
m = self._view(b)
def setitem(value):
m[0] = value
self.assertRaises(TypeError, setitem, b"a")
self.assertRaises(TypeError, setitem, 65)
self.assertRaises(TypeError, setitem, memoryview(b"a"))
m = None
self.assertEqual(sys.getrefcount(b), oldrefcount)
def test_setitem_writable(self):
if not self.rw_type:
self.skipTest("no writable type to test")
tp = self.rw_type
b = self.rw_type(self._source)
oldrefcount = sys.getrefcount(b)
m = self._view(b)
m[0] = ord(b'1')
self._check_contents(tp, b, b"1bcdef")
m[0:1] = tp(b"0")
self._check_contents(tp, b, b"0bcdef")
m[1:3] = tp(b"12")
self._check_contents(tp, b, b"012def")
m[1:1] = tp(b"")
self._check_contents(tp, b, b"012def")
m[:] = tp(b"abcdef")
self._check_contents(tp, b, b"abcdef")
# Overlapping copies of a view into itself
m[0:3] = m[2:5]
self._check_contents(tp, b, b"cdedef")
m[:] = tp(b"abcdef")
m[2:5] = m[0:3]
self._check_contents(tp, b, b"ababcf")
def setitem(key, value):
m[key] = tp(value)
# Bounds checking
self.assertRaises(IndexError, setitem, 6, b"a")
self.assertRaises(IndexError, setitem, -7, b"a")
self.assertRaises(IndexError, setitem, sys.maxsize, b"a")
self.assertRaises(IndexError, setitem, -sys.maxsize, b"a")
# Wrong index/slice types
self.assertRaises(TypeError, setitem, 0.0, b"a")
self.assertRaises(TypeError, setitem, (0,), b"a")
self.assertRaises(TypeError, setitem, (slice(0,1,1), 0), b"a")
self.assertRaises(TypeError, setitem, (0, slice(0,1,1)), b"a")
self.assertRaises(TypeError, setitem, (0,), b"a")
self.assertRaises(TypeError, setitem, "a", b"a")
# Not implemented: multidimensional slices
slices = (slice(0,1,1), slice(0,1,2))
self.assertRaises(NotImplementedError, setitem, slices, b"a")
# Trying to resize the memory object
exc = ValueError if m.format == 'c' else TypeError
self.assertRaises(exc, setitem, 0, b"")
self.assertRaises(exc, setitem, 0, b"ab")
self.assertRaises(ValueError, setitem, slice(1,1), b"a")
self.assertRaises(ValueError, setitem, slice(0,2), b"a")
m = None
self.assertEqual(sys.getrefcount(b), oldrefcount)
def test_delitem(self):
for tp in self._types:
b = tp(self._source)
m = self._view(b)
with self.assertRaises(TypeError):
del m[1]
with self.assertRaises(TypeError):
del m[1:4]
def test_tobytes(self):
for tp in self._types:
m = self._view(tp(self._source))
b = m.tobytes()
# This calls self.getitem_type() on each separate byte of b"abcdef"
expected = b"".join(
self.getitem_type(bytes([c])) for c in b"abcdef")
self.assertEqual(b, expected)
self.assertIsInstance(b, bytes)
def test_tolist(self):
for tp in self._types:
m = self._view(tp(self._source))
l = m.tolist()
self.assertEqual(l, list(b"abcdef"))
def test_compare(self):
# memoryviews can compare for equality with other objects
# having the buffer interface.
for tp in self._types:
m = self._view(tp(self._source))
for tp_comp in self._types:
self.assertTrue(m == tp_comp(b"abcdef"))
self.assertFalse(m != tp_comp(b"abcdef"))
self.assertFalse(m == tp_comp(b"abcde"))
self.assertTrue(m != tp_comp(b"abcde"))
self.assertFalse(m == tp_comp(b"abcde1"))
self.assertTrue(m != tp_comp(b"abcde1"))
self.assertTrue(m == m)
self.assertTrue(m == m[:])
self.assertTrue(m[0:6] == m[:])
self.assertFalse(m[0:5] == m)
# Comparison with objects which don't support the buffer API
self.assertFalse(m == "abcdef")
self.assertTrue(m != "abcdef")
self.assertFalse("abcdef" == m)
self.assertTrue("abcdef" != m)
# Unordered comparisons
for c in (m, b"abcdef"):
self.assertRaises(TypeError, lambda: m < c)
self.assertRaises(TypeError, lambda: c <= m)
self.assertRaises(TypeError, lambda: m >= c)
self.assertRaises(TypeError, lambda: c > m)
def check_attributes_with_type(self, tp):
m = self._view(tp(self._source))
self.assertEqual(m.format, self.format)
self.assertEqual(m.itemsize, self.itemsize)
self.assertEqual(m.ndim, 1)
self.assertEqual(m.shape, (6,))
self.assertEqual(len(m), 6)
self.assertEqual(m.strides, (self.itemsize,))
self.assertEqual(m.suboffsets, ())
return m
def test_attributes_readonly(self):
if not self.ro_type:
self.skipTest("no read-only type to test")
m = self.check_attributes_with_type(self.ro_type)
self.assertEqual(m.readonly, True)
def test_attributes_writable(self):
if not self.rw_type:
self.skipTest("no writable type to test")
m = self.check_attributes_with_type(self.rw_type)
self.assertEqual(m.readonly, False)
def test_getbuffer(self):
# Test PyObject_GetBuffer() on a memoryview object.
for tp in self._types:
b = tp(self._source)
oldrefcount = sys.getrefcount(b)
m = self._view(b)
oldviewrefcount = sys.getrefcount(m)
s = str(m, "utf-8")
self._check_contents(tp, b, s.encode("utf-8"))
self.assertEqual(sys.getrefcount(m), oldviewrefcount)
m = None
self.assertEqual(sys.getrefcount(b), oldrefcount)
def test_gc(self):
for tp in self._types:
if not isinstance(tp, type):
# If tp is a factory rather than a plain type, skip
continue
class MyView():
def __init__(self, base):
self.m = memoryview(base)
class MySource(tp):
pass
class MyObject:
pass
# Create a reference cycle through a memoryview object.
# This exercises mbuf_clear().
b = MySource(tp(b'abc'))
m = self._view(b)
o = MyObject()
b.m = m
b.o = o
wr = weakref.ref(o)
b = m = o = None
# The cycle must be broken
gc.collect()
self.assertTrue(wr() is None, wr())
# This exercises memory_clear().
m = MyView(tp(b'abc'))
o = MyObject()
m.x = m
m.o = o
wr = weakref.ref(o)
m = o = None
# The cycle must be broken
gc.collect()
self.assertTrue(wr() is None, wr())
def _check_released(self, m, tp):
check = self.assertRaisesRegex(ValueError, "released")
with check: bytes(m)
with check: m.tobytes()
with check: m.tolist()
with check: m[0]
with check: m[0] = b'x'
with check: len(m)
with check: m.format
with check: m.itemsize
with check: m.ndim
with check: m.readonly
with check: m.shape
with check: m.strides
with check:
with m:
pass
# str() and repr() still function
self.assertIn("released memory", str(m))
self.assertIn("released memory", repr(m))
self.assertEqual(m, m)
self.assertNotEqual(m, memoryview(tp(self._source)))
self.assertNotEqual(m, tp(self._source))
def test_contextmanager(self):
for tp in self._types:
b = tp(self._source)
m = self._view(b)
with m as cm:
self.assertIs(cm, m)
self._check_released(m, tp)
m = self._view(b)
# Can release explicitly inside the context manager
with m:
m.release()
def test_release(self):
for tp in self._types:
b = tp(self._source)
m = self._view(b)
m.release()
self._check_released(m, tp)
# Can be called a second time (it's a no-op)
m.release()
self._check_released(m, tp)
def test_writable_readonly(self):
# Issue #10451: memoryview incorrectly exposes a readonly
# buffer as writable causing a segfault if using mmap
tp = self.ro_type
if tp is None:
self.skipTest("no read-only type to test")
b = tp(self._source)
m = self._view(b)
i = io.BytesIO(b'ZZZZ')
self.assertRaises(TypeError, i.readinto, m)
def test_getbuf_fail(self):
self.assertRaises(TypeError, self._view, {})
def test_hash(self):
# Memoryviews of readonly (hashable) types are hashable, and they
# hash as hash(obj.tobytes()).
tp = self.ro_type
if tp is None:
self.skipTest("no read-only type to test")
b = tp(self._source)
m = self._view(b)
self.assertEqual(hash(m), hash(b"abcdef"))
# Releasing the memoryview keeps the stored hash value (as with weakrefs)
m.release()
self.assertEqual(hash(m), hash(b"abcdef"))
# Hashing a memoryview for the first time after it is released
# results in an error (as with weakrefs).
m = self._view(b)
m.release()
self.assertRaises(ValueError, hash, m)
def test_hash_writable(self):
# Memoryviews of writable types are unhashable
tp = self.rw_type
if tp is None:
self.skipTest("no writable type to test")
b = tp(self._source)
m = self._view(b)
self.assertRaises(ValueError, hash, m)
def test_weakref(self):
# Check memoryviews are weakrefable
for tp in self._types:
b = tp(self._source)
m = self._view(b)
L = []
def callback(wr, b=b):
L.append(b)
wr = weakref.ref(m, callback)
self.assertIs(wr(), m)
del m
test.support.gc_collect()
self.assertIs(wr(), None)
self.assertIs(L[0], b)
def test_reversed(self):
for tp in self._types:
b = tp(self._source)
m = self._view(b)
aslist = list(reversed(m.tolist()))
self.assertEqual(list(reversed(m)), aslist)
self.assertEqual(list(reversed(m)), list(m[::-1]))
def test_issue22668(self):
a = array.array('H', [256, 256, 256, 256])
x = memoryview(a)
m = x.cast('B')
b = m.cast('H')
c = b[0:2]
d = memoryview(b)
del b
self.assertEqual(c[0], 256)
self.assertEqual(d[0], 256)
self.assertEqual(c.format, "H")
self.assertEqual(d.format, "H")
_ = m.cast('I')
self.assertEqual(c[0], 256)
self.assertEqual(d[0], 256)
self.assertEqual(c.format, "H")
self.assertEqual(d.format, "H")
# Variations on source objects for the buffer: bytes-like objects, then arrays
# with itemsize > 1.
# NOTE: support for multi-dimensional objects is unimplemented.
class BaseBytesMemoryTests(AbstractMemoryTests):
ro_type = bytes
rw_type = bytearray
getitem_type = bytes
itemsize = 1
format = 'B'
class BaseArrayMemoryTests(AbstractMemoryTests):
ro_type = None
rw_type = lambda self, b: array.array('i', list(b))
getitem_type = lambda self, b: array.array('i', list(b)).tobytes()
itemsize = array.array('i').itemsize
format = 'i'
@unittest.skip('XXX test should be adapted for non-byte buffers')
def test_getbuffer(self):
pass
@unittest.skip('XXX NotImplementedError: tolist() only supports byte views')
def test_tolist(self):
pass
# Variations on indirection levels: memoryview, slice of memoryview,
# slice of slice of memoryview.
# This is important to test allocation subtleties.
class BaseMemoryviewTests:
def _view(self, obj):
return memoryview(obj)
def _check_contents(self, tp, obj, contents):
self.assertEqual(obj, tp(contents))
class BaseMemorySliceTests:
source_bytes = b"XabcdefY"
def _view(self, obj):
m = memoryview(obj)
return m[1:7]
def _check_contents(self, tp, obj, contents):
self.assertEqual(obj[1:7], tp(contents))
def test_refs(self):
for tp in self._types:
m = memoryview(tp(self._source))
oldrefcount = sys.getrefcount(m)
m[1:2]
self.assertEqual(sys.getrefcount(m), oldrefcount)
class BaseMemorySliceSliceTests:
source_bytes = b"XabcdefY"
def _view(self, obj):
m = memoryview(obj)
return m[:7][1:]
def _check_contents(self, tp, obj, contents):
self.assertEqual(obj[1:7], tp(contents))
# Concrete test classes
class BytesMemoryviewTest(unittest.TestCase,
BaseMemoryviewTests, BaseBytesMemoryTests):
def test_constructor(self):
for tp in self._types:
ob = tp(self._source)
self.assertTrue(memoryview(ob))
self.assertTrue(memoryview(object=ob))
self.assertRaises(TypeError, memoryview)
self.assertRaises(TypeError, memoryview, ob, ob)
self.assertRaises(TypeError, memoryview, argument=ob)
self.assertRaises(TypeError, memoryview, ob, argument=True)
class ArrayMemoryviewTest(unittest.TestCase,
BaseMemoryviewTests, BaseArrayMemoryTests):
def test_array_assign(self):
# Issue #4569: segfault when mutating a memoryview with itemsize != 1
a = array.array('i', range(10))
m = memoryview(a)
new_a = array.array('i', range(9, -1, -1))
m[:] = new_a
self.assertEqual(a, new_a)
class BytesMemorySliceTest(unittest.TestCase,
BaseMemorySliceTests, BaseBytesMemoryTests):
pass
class ArrayMemorySliceTest(unittest.TestCase,
BaseMemorySliceTests, BaseArrayMemoryTests):
pass
class BytesMemorySliceSliceTest(unittest.TestCase,
BaseMemorySliceSliceTests, BaseBytesMemoryTests):
pass
class ArrayMemorySliceSliceTest(unittest.TestCase,
BaseMemorySliceSliceTests, BaseArrayMemoryTests):
pass
class OtherTest(unittest.TestCase):
def test_ctypes_cast(self):
# Issue 15944: Allow all source formats when casting to bytes.
ctypes = test.support.import_module("ctypes")
p6 = bytes(ctypes.c_double(0.6))
d = ctypes.c_double()
m = memoryview(d).cast("B")
m[:2] = p6[:2]
m[2:] = p6[2:]
self.assertEqual(d.value, 0.6)
for format in "Bbc":
with self.subTest(format):
d = ctypes.c_double()
m = memoryview(d).cast(format)
m[:2] = memoryview(p6).cast(format)[:2]
m[2:] = memoryview(p6).cast(format)[2:]
self.assertEqual(d.value, 0.6)
def test_memoryview_hex(self):
# Issue #9951: memoryview.hex() segfaults with non-contiguous buffers.
x = b'0' * 200000
m1 = memoryview(x)
m2 = m1[::-1]
self.assertEqual(m2.hex(), '30' * 200000)
def test_copy(self):
m = memoryview(b'abc')
with self.assertRaises(TypeError):
copy.copy(m)
def test_pickle(self):
m = memoryview(b'abc')
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
with self.assertRaises(TypeError):
pickle.dumps(m, proto)
if __name__ == "__main__":
unittest.main()
| 17,856 | 538 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_dummy_threading.py | from test import support
import unittest
import dummy_threading as _threading
import time
class DummyThreadingTestCase(unittest.TestCase):
class TestThread(_threading.Thread):
def run(self):
global running
global sema
global mutex
# Uncomment if testing another module, such as the real 'threading'
# module.
#delay = random.random() * 2
delay = 0
if support.verbose:
print('task', self.name, 'will run for', delay, 'sec')
sema.acquire()
mutex.acquire()
running += 1
if support.verbose:
print(running, 'tasks are running')
mutex.release()
time.sleep(delay)
if support.verbose:
print('task', self.name, 'done')
mutex.acquire()
running -= 1
if support.verbose:
print(self.name, 'is finished.', running, 'tasks are running')
mutex.release()
sema.release()
def setUp(self):
self.numtasks = 10
global sema
sema = _threading.BoundedSemaphore(value=3)
global mutex
mutex = _threading.RLock()
global running
running = 0
self.threads = []
def test_tasks(self):
for i in range(self.numtasks):
t = self.TestThread(name="<thread %d>"%i)
self.threads.append(t)
t.start()
if support.verbose:
print('waiting for all tasks to complete')
for t in self.threads:
t.join()
if support.verbose:
print('all tasks done')
if __name__ == '__main__':
unittest.main()
| 1,743 | 61 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_py_compile.py | import importlib.util
import os
import py_compile
import shutil
import stat
import sys
import tempfile
import unittest
from test import support
class PyCompileTests(unittest.TestCase):
def setUp(self):
self.directory = tempfile.mkdtemp(dir=os.getcwd())
self.source_path = os.path.join(self.directory, '_test.py')
self.pyc_path = self.source_path + 'c'
self.cache_path = importlib.util.cache_from_source(self.source_path)
self.cwd_drive = os.path.splitdrive(os.getcwd())[0]
# In these tests we compute relative paths. When using Windows, the
# current working directory path and the 'self.source_path' might be
# on different drives. Therefore we need to switch to the drive where
# the temporary source file lives.
drive = os.path.splitdrive(self.source_path)[0]
if drive:
os.chdir(drive)
with open(self.source_path, 'w') as file:
file.write('x = 123\n')
def tearDown(self):
shutil.rmtree(self.directory)
if self.cwd_drive:
os.chdir(self.cwd_drive)
def test_absolute_path(self):
py_compile.compile(self.source_path, self.pyc_path)
self.assertTrue(os.path.exists(self.pyc_path))
self.assertFalse(os.path.exists(self.cache_path))
def test_do_not_overwrite_symlinks(self):
# In the face of a cfile argument being a symlink, bail out.
# Issue #17222
try:
os.symlink(self.pyc_path + '.actual', self.pyc_path)
except (NotImplementedError, OSError):
self.skipTest('need to be able to create a symlink for a file')
else:
assert os.path.islink(self.pyc_path)
with self.assertRaises(FileExistsError):
py_compile.compile(self.source_path, self.pyc_path)
@unittest.skipIf(not os.path.exists(os.devnull) or os.path.isfile(os.devnull),
'requires os.devnull and for it to be a non-regular file')
def test_do_not_overwrite_nonregular_files(self):
# In the face of a cfile argument being a non-regular file, bail out.
# Issue #17222
with self.assertRaises(FileExistsError):
py_compile.compile(self.source_path, os.devnull)
def test_cache_path(self):
py_compile.compile(self.source_path)
self.assertTrue(os.path.exists(self.cache_path))
def test_cwd(self):
with support.change_cwd(self.directory):
py_compile.compile(os.path.basename(self.source_path),
os.path.basename(self.pyc_path))
self.assertTrue(os.path.exists(self.pyc_path))
self.assertFalse(os.path.exists(self.cache_path))
def test_relative_path(self):
py_compile.compile(os.path.relpath(self.source_path),
os.path.relpath(self.pyc_path))
self.assertTrue(os.path.exists(self.pyc_path))
self.assertFalse(os.path.exists(self.cache_path))
@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
'non-root user required')
@unittest.skipIf(os.name == 'nt',
'cannot control directory permissions on Windows')
def test_exceptions_propagate(self):
# Make sure that exceptions raised thanks to issues with writing
# bytecode.
# http://bugs.python.org/issue17244
mode = os.stat(self.directory)
os.chmod(self.directory, stat.S_IREAD)
try:
with self.assertRaises(IOError):
py_compile.compile(self.source_path, self.pyc_path)
finally:
os.chmod(self.directory, mode.st_mode)
def test_bad_coding(self):
bad_coding = os.path.join(os.path.dirname(__file__), 'bad_coding2.py')
with support.captured_stderr():
self.assertIsNone(py_compile.compile(bad_coding, doraise=False))
self.assertFalse(os.path.exists(
importlib.util.cache_from_source(bad_coding)))
@unittest.skipIf(sys.flags.optimize > 0, 'test does not work with -O')
def test_double_dot_no_clobber(self):
# http://bugs.python.org/issue22966
# py_compile foo.bar.py -> __pycache__/foo.cpython-34.pyc
weird_path = os.path.join(self.directory, 'foo.bar.py')
cache_path = importlib.util.cache_from_source(weird_path)
pyc_path = weird_path + 'c'
head, tail = os.path.split(cache_path)
penultimate_tail = os.path.basename(head)
self.assertEqual(
os.path.join(penultimate_tail, tail),
os.path.join(
'__pycache__',
'foo.bar.{}.pyc'.format(sys.implementation.cache_tag)))
with open(weird_path, 'w') as file:
file.write('x = 123\n')
py_compile.compile(weird_path)
self.assertTrue(os.path.exists(cache_path))
self.assertFalse(os.path.exists(pyc_path))
def test_optimization_path(self):
# Specifying optimized bytecode should lead to a path reflecting that.
self.assertIn('opt-2', py_compile.compile(self.source_path, optimize=2))
if __name__ == "__main__":
unittest.main()
| 5,171 | 128 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/future_test2.py | """This is a test"""
from __future__ import nested_scopes; import site
def f(x):
def g(y):
return x + y
return g
result = f(2)(4)
| 149 | 11 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_doctest3.txt |
Here we check that `__file__` is provided:
>>> type(__file__)
<class 'str'>
| 82 | 6 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_string_literals.py | r"""Test correct treatment of various string literals by the parser.
There are four types of string literals:
'abc' -- normal str
r'abc' -- raw str
b'xyz' -- normal bytes
br'xyz' | rb'xyz' -- raw bytes
The difference between normal and raw strings is of course that in a
raw string, \ escapes (while still used to determine the end of the
literal) are not interpreted, so that r'\x00' contains four
characters: a backslash, an x, and two zeros; while '\x00' contains a
single character (code point zero).
The tricky thing is what should happen when non-ASCII bytes are used
inside literals. For bytes literals, this is considered illegal. But
for str literals, those bytes are supposed to be decoded using the
encoding declared for the file (UTF-8 by default).
We have to test this with various file encodings. We also test it with
exec()/eval(), which uses a different code path.
This file is really about correct treatment of encodings and
backslashes. It doesn't concern itself with issues like single
vs. double quotes or singly- vs. triply-quoted strings: that's dealt
with elsewhere (I assume).
"""
import os
import sys
import shutil
import tempfile
import warnings
import unittest
TEMPLATE = r"""# coding: %s
a = 'x'
assert ord(a) == 120
b = '\x01'
assert ord(b) == 1
c = r'\x01'
assert list(map(ord, c)) == [92, 120, 48, 49]
d = '\x81'
assert ord(d) == 0x81
e = r'\x81'
assert list(map(ord, e)) == [92, 120, 56, 49]
f = '\u1881'
assert ord(f) == 0x1881
g = r'\u1881'
assert list(map(ord, g)) == [92, 117, 49, 56, 56, 49]
h = '\U0001d120'
assert ord(h) == 0x1d120
i = r'\U0001d120'
assert list(map(ord, i)) == [92, 85, 48, 48, 48, 49, 100, 49, 50, 48]
"""
def byte(i):
return bytes([i])
class TestLiterals(unittest.TestCase):
def setUp(self):
self.save_path = sys.path[:]
self.tmpdir = tempfile.mkdtemp()
sys.path.insert(0, self.tmpdir)
def tearDown(self):
sys.path[:] = self.save_path
shutil.rmtree(self.tmpdir, ignore_errors=True)
def test_template(self):
# Check that the template doesn't contain any non-printables
# except for \n.
for c in TEMPLATE:
assert c == '\n' or ' ' <= c <= '~', repr(c)
def test_eval_str_normal(self):
self.assertEqual(eval(""" 'x' """), 'x')
self.assertEqual(eval(r""" '\x01' """), chr(1))
self.assertEqual(eval(""" '\x01' """), chr(1))
self.assertEqual(eval(r""" '\x81' """), chr(0x81))
self.assertEqual(eval(""" '\x81' """), chr(0x81))
self.assertEqual(eval(r""" '\u1881' """), chr(0x1881))
self.assertEqual(eval(""" '\u1881' """), chr(0x1881))
self.assertEqual(eval(r""" '\U0001d120' """), chr(0x1d120))
self.assertEqual(eval(""" '\U0001d120' """), chr(0x1d120))
def test_eval_str_incomplete(self):
self.assertRaises(SyntaxError, eval, r""" '\x' """)
self.assertRaises(SyntaxError, eval, r""" '\x0' """)
self.assertRaises(SyntaxError, eval, r""" '\u' """)
self.assertRaises(SyntaxError, eval, r""" '\u0' """)
self.assertRaises(SyntaxError, eval, r""" '\u00' """)
self.assertRaises(SyntaxError, eval, r""" '\u000' """)
self.assertRaises(SyntaxError, eval, r""" '\U' """)
self.assertRaises(SyntaxError, eval, r""" '\U0' """)
self.assertRaises(SyntaxError, eval, r""" '\U00' """)
self.assertRaises(SyntaxError, eval, r""" '\U000' """)
self.assertRaises(SyntaxError, eval, r""" '\U0000' """)
self.assertRaises(SyntaxError, eval, r""" '\U00000' """)
self.assertRaises(SyntaxError, eval, r""" '\U000000' """)
self.assertRaises(SyntaxError, eval, r""" '\U0000000' """)
def test_eval_str_invalid_escape(self):
for b in range(1, 128):
if b in b"""\n\r"'01234567NU\\abefnrtuvx""":
continue
with self.assertWarns(DeprecationWarning):
self.assertEqual(eval(r"'\%c'" % b), '\\' + chr(b))
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always', category=DeprecationWarning)
eval("'''\n\\z'''")
self.assertEqual(len(w), 1)
self.assertEqual(w[0].filename, '<string>')
self.assertEqual(w[0].lineno, 2)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('error', category=DeprecationWarning)
with self.assertRaises(SyntaxError) as cm:
eval("'''\n\\z'''")
exc = cm.exception
self.assertEqual(w, [])
self.assertEqual(exc.filename, '<string>')
self.assertEqual(exc.lineno, 2)
def test_eval_str_raw(self):
self.assertEqual(eval(""" r'x' """), 'x')
self.assertEqual(eval(r""" r'\x01' """), '\\' + 'x01')
self.assertEqual(eval(""" r'\x01' """), chr(1))
self.assertEqual(eval(r""" r'\x81' """), '\\' + 'x81')
self.assertEqual(eval(""" r'\x81' """), chr(0x81))
self.assertEqual(eval(r""" r'\u1881' """), '\\' + 'u1881')
self.assertEqual(eval(""" r'\u1881' """), chr(0x1881))
self.assertEqual(eval(r""" r'\U0001d120' """), '\\' + 'U0001d120')
self.assertEqual(eval(""" r'\U0001d120' """), chr(0x1d120))
def test_eval_bytes_normal(self):
self.assertEqual(eval(""" b'x' """), b'x')
self.assertEqual(eval(r""" b'\x01' """), byte(1))
self.assertEqual(eval(""" b'\x01' """), byte(1))
self.assertEqual(eval(r""" b'\x81' """), byte(0x81))
self.assertRaises(SyntaxError, eval, """ b'\x81' """)
self.assertEqual(eval(r""" br'\u1881' """), b'\\' + b'u1881')
self.assertRaises(SyntaxError, eval, """ b'\u1881' """)
self.assertEqual(eval(r""" br'\U0001d120' """), b'\\' + b'U0001d120')
self.assertRaises(SyntaxError, eval, """ b'\U0001d120' """)
def test_eval_bytes_incomplete(self):
self.assertRaises(SyntaxError, eval, r""" b'\x' """)
self.assertRaises(SyntaxError, eval, r""" b'\x0' """)
def test_eval_bytes_invalid_escape(self):
for b in range(1, 128):
if b in b"""\n\r"'01234567\\abefnrtvx""":
continue
with self.assertWarns(DeprecationWarning):
self.assertEqual(eval(r"b'\%c'" % b), b'\\' + bytes([b]))
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always', category=DeprecationWarning)
eval("b'''\n\\z'''")
self.assertEqual(len(w), 1)
self.assertEqual(w[0].filename, '<string>')
self.assertEqual(w[0].lineno, 2)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('error', category=DeprecationWarning)
with self.assertRaises(SyntaxError) as cm:
eval("b'''\n\\z'''")
exc = cm.exception
self.assertEqual(w, [])
self.assertEqual(exc.filename, '<string>')
self.assertEqual(exc.lineno, 2)
def test_eval_bytes_raw(self):
self.assertEqual(eval(""" br'x' """), b'x')
self.assertEqual(eval(""" rb'x' """), b'x')
self.assertEqual(eval(r""" br'\x01' """), b'\\' + b'x01')
self.assertEqual(eval(r""" rb'\x01' """), b'\\' + b'x01')
self.assertEqual(eval(""" br'\x01' """), byte(1))
self.assertEqual(eval(""" rb'\x01' """), byte(1))
self.assertEqual(eval(r""" br'\x81' """), b"\\" + b"x81")
self.assertEqual(eval(r""" rb'\x81' """), b"\\" + b"x81")
self.assertRaises(SyntaxError, eval, """ br'\x81' """)
self.assertRaises(SyntaxError, eval, """ rb'\x81' """)
self.assertEqual(eval(r""" br'\u1881' """), b"\\" + b"u1881")
self.assertEqual(eval(r""" rb'\u1881' """), b"\\" + b"u1881")
self.assertRaises(SyntaxError, eval, """ br'\u1881' """)
self.assertRaises(SyntaxError, eval, """ rb'\u1881' """)
self.assertEqual(eval(r""" br'\U0001d120' """), b"\\" + b"U0001d120")
self.assertEqual(eval(r""" rb'\U0001d120' """), b"\\" + b"U0001d120")
self.assertRaises(SyntaxError, eval, """ br'\U0001d120' """)
self.assertRaises(SyntaxError, eval, """ rb'\U0001d120' """)
self.assertRaises(SyntaxError, eval, """ bb'' """)
self.assertRaises(SyntaxError, eval, """ rr'' """)
self.assertRaises(SyntaxError, eval, """ brr'' """)
self.assertRaises(SyntaxError, eval, """ bbr'' """)
self.assertRaises(SyntaxError, eval, """ rrb'' """)
self.assertRaises(SyntaxError, eval, """ rbb'' """)
def test_eval_str_u(self):
self.assertEqual(eval(""" u'x' """), 'x')
self.assertEqual(eval(""" U'\u00e4' """), 'ä')
self.assertEqual(eval(""" u'\N{LATIN SMALL LETTER A WITH DIAERESIS}' """), 'ä')
self.assertRaises(SyntaxError, eval, """ ur'' """)
self.assertRaises(SyntaxError, eval, """ ru'' """)
self.assertRaises(SyntaxError, eval, """ bu'' """)
self.assertRaises(SyntaxError, eval, """ ub'' """)
def check_encoding(self, encoding, extra=""):
modname = "xx_" + encoding.replace("-", "_")
fn = os.path.join(self.tmpdir, modname + ".py")
f = open(fn, "w", encoding=encoding)
try:
f.write(TEMPLATE % encoding)
f.write(extra)
finally:
f.close()
__import__(modname)
del sys.modules[modname]
def test_file_utf_8(self):
extra = "z = '\u1234'; assert ord(z) == 0x1234\n"
self.check_encoding("utf-8", extra)
def test_file_utf_8_error(self):
extra = "b'\x80'\n"
self.assertRaises(SyntaxError, self.check_encoding, "utf-8", extra)
def test_file_utf8(self):
self.check_encoding("utf-8")
def test_file_iso_8859_1(self):
self.check_encoding("iso-8859-1")
def test_file_latin_1(self):
self.check_encoding("latin-1")
def test_file_latin9(self):
return
self.check_encoding("latin9")
if __name__ == "__main__":
unittest.main()
| 10,080 | 251 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_webbrowser.py | import webbrowser
import unittest
import subprocess
from unittest import mock
from test import support
URL = 'http://www.example.com'
CMD_NAME = 'test'
class PopenMock(mock.MagicMock):
def poll(self):
return 0
def wait(self, seconds=None):
return 0
class CommandTestMixin:
def _test(self, meth, *, args=[URL], kw={}, options, arguments):
"""Given a web browser instance method name along with arguments and
keywords for same (which defaults to the single argument URL), creates
a browser instance from the class pointed to by self.browser, calls the
indicated instance method with the indicated arguments, and compares
the resulting options and arguments passed to Popen by the browser
instance against the 'options' and 'args' lists. Options are compared
in a position independent fashion, and the arguments are compared in
sequence order to whatever is left over after removing the options.
"""
popen = PopenMock()
support.patch(self, subprocess, 'Popen', popen)
browser = self.browser_class(name=CMD_NAME)
getattr(browser, meth)(*args, **kw)
popen_args = subprocess.Popen.call_args[0][0]
self.assertEqual(popen_args[0], CMD_NAME)
popen_args.pop(0)
for option in options:
self.assertIn(option, popen_args)
popen_args.pop(popen_args.index(option))
self.assertEqual(popen_args, arguments)
class GenericBrowserCommandTest(CommandTestMixin, unittest.TestCase):
browser_class = webbrowser.GenericBrowser
def test_open(self):
self._test('open',
options=[],
arguments=[URL])
class BackgroundBrowserCommandTest(CommandTestMixin, unittest.TestCase):
browser_class = webbrowser.BackgroundBrowser
def test_open(self):
self._test('open',
options=[],
arguments=[URL])
class ChromeCommandTest(CommandTestMixin, unittest.TestCase):
browser_class = webbrowser.Chrome
def test_open(self):
self._test('open',
options=[],
arguments=[URL])
def test_open_with_autoraise_false(self):
self._test('open', kw=dict(autoraise=False),
options=[],
arguments=[URL])
def test_open_new(self):
self._test('open_new',
options=['--new-window'],
arguments=[URL])
def test_open_new_tab(self):
self._test('open_new_tab',
options=[],
arguments=[URL])
class MozillaCommandTest(CommandTestMixin, unittest.TestCase):
browser_class = webbrowser.Mozilla
def test_open(self):
self._test('open',
options=[],
arguments=[URL])
def test_open_with_autoraise_false(self):
self._test('open', kw=dict(autoraise=False),
options=[],
arguments=[URL])
def test_open_new(self):
self._test('open_new',
options=[],
arguments=['-new-window', URL])
def test_open_new_tab(self):
self._test('open_new_tab',
options=[],
arguments=['-new-tab', URL])
class NetscapeCommandTest(CommandTestMixin, unittest.TestCase):
browser_class = webbrowser.Netscape
def test_open(self):
self._test('open',
options=['-raise', '-remote'],
arguments=['openURL({})'.format(URL)])
def test_open_with_autoraise_false(self):
self._test('open', kw=dict(autoraise=False),
options=['-noraise', '-remote'],
arguments=['openURL({})'.format(URL)])
def test_open_new(self):
self._test('open_new',
options=['-raise', '-remote'],
arguments=['openURL({},new-window)'.format(URL)])
def test_open_new_tab(self):
self._test('open_new_tab',
options=['-raise', '-remote'],
arguments=['openURL({},new-tab)'.format(URL)])
class GaleonCommandTest(CommandTestMixin, unittest.TestCase):
browser_class = webbrowser.Galeon
def test_open(self):
self._test('open',
options=['-n'],
arguments=[URL])
def test_open_with_autoraise_false(self):
self._test('open', kw=dict(autoraise=False),
options=['-noraise', '-n'],
arguments=[URL])
def test_open_new(self):
self._test('open_new',
options=['-w'],
arguments=[URL])
def test_open_new_tab(self):
self._test('open_new_tab',
options=['-w'],
arguments=[URL])
class OperaCommandTest(CommandTestMixin, unittest.TestCase):
browser_class = webbrowser.Opera
def test_open(self):
self._test('open',
options=[],
arguments=[URL])
def test_open_with_autoraise_false(self):
self._test('open', kw=dict(autoraise=False),
options=[],
arguments=[URL])
def test_open_new(self):
self._test('open_new',
options=['--new-window'],
arguments=[URL])
def test_open_new_tab(self):
self._test('open_new_tab',
options=[],
arguments=[URL])
class ELinksCommandTest(CommandTestMixin, unittest.TestCase):
browser_class = webbrowser.Elinks
def test_open(self):
self._test('open', options=['-remote'],
arguments=['openURL({})'.format(URL)])
def test_open_with_autoraise_false(self):
self._test('open',
options=['-remote'],
arguments=['openURL({})'.format(URL)])
def test_open_new(self):
self._test('open_new',
options=['-remote'],
arguments=['openURL({},new-window)'.format(URL)])
def test_open_new_tab(self):
self._test('open_new_tab',
options=['-remote'],
arguments=['openURL({},new-tab)'.format(URL)])
if __name__=='__main__':
unittest.main()
| 6,329 | 218 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_list.py | import sys
from test import list_tests
import pickle
import unittest
class ListTest(list_tests.CommonTest):
type2test = list
def test_basic(self):
self.assertEqual(list([]), [])
l0_3 = [0, 1, 2, 3]
l0_3_bis = list(l0_3)
self.assertEqual(l0_3, l0_3_bis)
self.assertTrue(l0_3 is not l0_3_bis)
self.assertEqual(list(()), [])
self.assertEqual(list((0, 1, 2, 3)), [0, 1, 2, 3])
self.assertEqual(list(''), [])
self.assertEqual(list('spam'), ['s', 'p', 'a', 'm'])
if sys.maxsize == 0x7fffffff:
# This test can currently only work on 32-bit machines.
# XXX If/when PySequence_Length() returns a ssize_t, it should be
# XXX re-enabled.
# Verify clearing of bug #556025.
# This assumes that the max data size (sys.maxint) == max
# address size this also assumes that the address size is at
# least 4 bytes with 8 byte addresses, the bug is not well
# tested
#
# Note: This test is expected to SEGV under Cygwin 1.3.12 or
# earlier due to a newlib bug. See the following mailing list
# thread for the details:
# http://sources.redhat.com/ml/newlib/2002/msg00369.html
self.assertRaises(MemoryError, list, range(sys.maxsize // 2))
# This code used to segfault in Py2.4a3
x = []
x.extend(-y for y in x)
self.assertEqual(x, [])
def test_truth(self):
super().test_truth()
self.assertTrue(not [])
self.assertTrue([42])
def test_identity(self):
self.assertTrue([] is not [])
def test_len(self):
super().test_len()
self.assertEqual(len([]), 0)
self.assertEqual(len([0]), 1)
self.assertEqual(len([0, 1, 2]), 3)
def test_overflow(self):
lst = [4, 5, 6, 7]
n = int((sys.maxsize*2+2) // len(lst))
def mul(a, b): return a * b
def imul(a, b): a *= b
self.assertRaises((MemoryError, OverflowError), mul, lst, n)
self.assertRaises((MemoryError, OverflowError), imul, lst, n)
def test_repr_large(self):
# Check the repr of large list objects
def check(n):
l = [0] * n
s = repr(l)
self.assertEqual(s,
'[' + ', '.join(['0'] * n) + ']')
check(10) # check our checking code
check(1000000)
def test_iterator_pickle(self):
orig = self.type2test([4, 5, 6, 7])
data = [10, 11, 12, 13, 14, 15]
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
# initial iterator
itorig = iter(orig)
d = pickle.dumps((itorig, orig), proto)
it, a = pickle.loads(d)
a[:] = data
self.assertEqual(type(it), type(itorig))
self.assertEqual(list(it), data)
# running iterator
next(itorig)
d = pickle.dumps((itorig, orig), proto)
it, a = pickle.loads(d)
a[:] = data
self.assertEqual(type(it), type(itorig))
self.assertEqual(list(it), data[1:])
# empty iterator
for i in range(1, len(orig)):
next(itorig)
d = pickle.dumps((itorig, orig), proto)
it, a = pickle.loads(d)
a[:] = data
self.assertEqual(type(it), type(itorig))
self.assertEqual(list(it), data[len(orig):])
# exhausted iterator
self.assertRaises(StopIteration, next, itorig)
d = pickle.dumps((itorig, orig), proto)
it, a = pickle.loads(d)
a[:] = data
self.assertEqual(list(it), [])
def test_reversed_pickle(self):
orig = self.type2test([4, 5, 6, 7])
data = [10, 11, 12, 13, 14, 15]
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
# initial iterator
itorig = reversed(orig)
d = pickle.dumps((itorig, orig), proto)
it, a = pickle.loads(d)
a[:] = data
self.assertEqual(type(it), type(itorig))
self.assertEqual(list(it), data[len(orig)-1::-1])
# running iterator
next(itorig)
d = pickle.dumps((itorig, orig), proto)
it, a = pickle.loads(d)
a[:] = data
self.assertEqual(type(it), type(itorig))
self.assertEqual(list(it), data[len(orig)-2::-1])
# empty iterator
for i in range(1, len(orig)):
next(itorig)
d = pickle.dumps((itorig, orig), proto)
it, a = pickle.loads(d)
a[:] = data
self.assertEqual(type(it), type(itorig))
self.assertEqual(list(it), [])
# exhausted iterator
self.assertRaises(StopIteration, next, itorig)
d = pickle.dumps((itorig, orig), proto)
it, a = pickle.loads(d)
a[:] = data
self.assertEqual(list(it), [])
def test_no_comdat_folding(self):
# Issue 8847: In the PGO build, the MSVC linker's COMDAT folding
# optimization causes failures in code that relies on distinct
# function addresses.
class L(list): pass
with self.assertRaises(TypeError):
(3,) + L([1,2])
if __name__ == "__main__":
unittest.main()
| 5,448 | 156 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_fstring.py | import ast
import types
import decimal
import unittest
a_global = 'global variable'
# You could argue that I'm too strict in looking for specific error
# values with assertRaisesRegex, but without it it's way too easy to
# make a syntax error in the test strings. Especially with all of the
# triple quotes, raw strings, backslashes, etc. I think it's a
# worthwhile tradeoff. When I switched to this method, I found many
# examples where I wasn't testing what I thought I was.
class TestCase(unittest.TestCase):
def assertAllRaise(self, exception_type, regex, error_strings):
for str in error_strings:
with self.subTest(str=str):
with self.assertRaisesRegex(exception_type, regex):
eval(str)
def test__format__lookup(self):
# Make sure __format__ is looked up on the type, not the instance.
class X:
def __format__(self, spec):
return 'class'
x = X()
# Add a bound __format__ method to the 'y' instance, but not
# the 'x' instance.
y = X()
y.__format__ = types.MethodType(lambda self, spec: 'instance', y)
self.assertEqual(f'{y}', format(y))
self.assertEqual(f'{y}', 'class')
self.assertEqual(format(x), format(y))
# __format__ is not called this way, but still make sure it
# returns what we expect (so we can make sure we're bypassing
# it).
self.assertEqual(x.__format__(''), 'class')
self.assertEqual(y.__format__(''), 'instance')
# This is how __format__ is actually called.
self.assertEqual(type(x).__format__(x, ''), 'class')
self.assertEqual(type(y).__format__(y, ''), 'class')
def test_ast(self):
# Inspired by http://bugs.python.org/issue24975
class X:
def __init__(self):
self.called = False
def __call__(self):
self.called = True
return 4
x = X()
expr = """
a = 10
f'{a * x()}'"""
t = ast.parse(expr)
c = compile(t, '', 'exec')
# Make sure x was not called.
self.assertFalse(x.called)
# Actually run the code.
exec(c)
# Make sure x was called.
self.assertTrue(x.called)
def test_ast_line_numbers(self):
expr = """
a = 10
f'{a * x()}'"""
t = ast.parse(expr)
self.assertEqual(type(t), ast.Module)
self.assertEqual(len(t.body), 2)
# check `a = 10`
self.assertEqual(type(t.body[0]), ast.Assign)
self.assertEqual(t.body[0].lineno, 2)
# check `f'...'`
self.assertEqual(type(t.body[1]), ast.Expr)
self.assertEqual(type(t.body[1].value), ast.JoinedStr)
self.assertEqual(len(t.body[1].value.values), 1)
self.assertEqual(type(t.body[1].value.values[0]), ast.FormattedValue)
self.assertEqual(t.body[1].lineno, 3)
self.assertEqual(t.body[1].value.lineno, 3)
self.assertEqual(t.body[1].value.values[0].lineno, 3)
# check the binop location
binop = t.body[1].value.values[0].value
self.assertEqual(type(binop), ast.BinOp)
self.assertEqual(type(binop.left), ast.Name)
self.assertEqual(type(binop.op), ast.Mult)
self.assertEqual(type(binop.right), ast.Call)
self.assertEqual(binop.lineno, 3)
self.assertEqual(binop.left.lineno, 3)
self.assertEqual(binop.right.lineno, 3)
self.assertEqual(binop.col_offset, 3)
self.assertEqual(binop.left.col_offset, 3)
self.assertEqual(binop.right.col_offset, 7)
def test_ast_line_numbers_multiple_formattedvalues(self):
expr = """
f'no formatted values'
f'eggs {a * x()} spam {b + y()}'"""
t = ast.parse(expr)
self.assertEqual(type(t), ast.Module)
self.assertEqual(len(t.body), 2)
# check `f'no formatted value'`
self.assertEqual(type(t.body[0]), ast.Expr)
self.assertEqual(type(t.body[0].value), ast.JoinedStr)
self.assertEqual(t.body[0].lineno, 2)
# check `f'...'`
self.assertEqual(type(t.body[1]), ast.Expr)
self.assertEqual(type(t.body[1].value), ast.JoinedStr)
self.assertEqual(len(t.body[1].value.values), 4)
self.assertEqual(type(t.body[1].value.values[0]), ast.Str)
self.assertEqual(type(t.body[1].value.values[1]), ast.FormattedValue)
self.assertEqual(type(t.body[1].value.values[2]), ast.Str)
self.assertEqual(type(t.body[1].value.values[3]), ast.FormattedValue)
self.assertEqual(t.body[1].lineno, 3)
self.assertEqual(t.body[1].value.lineno, 3)
self.assertEqual(t.body[1].value.values[0].lineno, 3)
self.assertEqual(t.body[1].value.values[1].lineno, 3)
self.assertEqual(t.body[1].value.values[2].lineno, 3)
self.assertEqual(t.body[1].value.values[3].lineno, 3)
# check the first binop location
binop1 = t.body[1].value.values[1].value
self.assertEqual(type(binop1), ast.BinOp)
self.assertEqual(type(binop1.left), ast.Name)
self.assertEqual(type(binop1.op), ast.Mult)
self.assertEqual(type(binop1.right), ast.Call)
self.assertEqual(binop1.lineno, 3)
self.assertEqual(binop1.left.lineno, 3)
self.assertEqual(binop1.right.lineno, 3)
self.assertEqual(binop1.col_offset, 8)
self.assertEqual(binop1.left.col_offset, 8)
self.assertEqual(binop1.right.col_offset, 12)
# check the second binop location
binop2 = t.body[1].value.values[3].value
self.assertEqual(type(binop2), ast.BinOp)
self.assertEqual(type(binop2.left), ast.Name)
self.assertEqual(type(binop2.op), ast.Add)
self.assertEqual(type(binop2.right), ast.Call)
self.assertEqual(binop2.lineno, 3)
self.assertEqual(binop2.left.lineno, 3)
self.assertEqual(binop2.right.lineno, 3)
self.assertEqual(binop2.col_offset, 23)
self.assertEqual(binop2.left.col_offset, 23)
self.assertEqual(binop2.right.col_offset, 27)
def test_ast_line_numbers_nested(self):
expr = """
a = 10
f'{a * f"-{x()}-"}'"""
t = ast.parse(expr)
self.assertEqual(type(t), ast.Module)
self.assertEqual(len(t.body), 2)
# check `a = 10`
self.assertEqual(type(t.body[0]), ast.Assign)
self.assertEqual(t.body[0].lineno, 2)
# check `f'...'`
self.assertEqual(type(t.body[1]), ast.Expr)
self.assertEqual(type(t.body[1].value), ast.JoinedStr)
self.assertEqual(len(t.body[1].value.values), 1)
self.assertEqual(type(t.body[1].value.values[0]), ast.FormattedValue)
self.assertEqual(t.body[1].lineno, 3)
self.assertEqual(t.body[1].value.lineno, 3)
self.assertEqual(t.body[1].value.values[0].lineno, 3)
# check the binop location
binop = t.body[1].value.values[0].value
self.assertEqual(type(binop), ast.BinOp)
self.assertEqual(type(binop.left), ast.Name)
self.assertEqual(type(binop.op), ast.Mult)
self.assertEqual(type(binop.right), ast.JoinedStr)
self.assertEqual(binop.lineno, 3)
self.assertEqual(binop.left.lineno, 3)
self.assertEqual(binop.right.lineno, 3)
self.assertEqual(binop.col_offset, 3)
self.assertEqual(binop.left.col_offset, 3)
self.assertEqual(binop.right.col_offset, 7)
# check the nested call location
self.assertEqual(len(binop.right.values), 3)
self.assertEqual(type(binop.right.values[0]), ast.Str)
self.assertEqual(type(binop.right.values[1]), ast.FormattedValue)
self.assertEqual(type(binop.right.values[2]), ast.Str)
self.assertEqual(binop.right.values[0].lineno, 3)
self.assertEqual(binop.right.values[1].lineno, 3)
self.assertEqual(binop.right.values[2].lineno, 3)
call = binop.right.values[1].value
self.assertEqual(type(call), ast.Call)
self.assertEqual(call.lineno, 3)
self.assertEqual(call.col_offset, 11)
def test_ast_line_numbers_duplicate_expression(self):
"""Duplicate expression
NOTE: this is currently broken, always sets location of the first
expression.
"""
expr = """
a = 10
f'{a * x()} {a * x()} {a * x()}'
"""
t = ast.parse(expr)
self.assertEqual(type(t), ast.Module)
self.assertEqual(len(t.body), 2)
# check `a = 10`
self.assertEqual(type(t.body[0]), ast.Assign)
self.assertEqual(t.body[0].lineno, 2)
# check `f'...'`
self.assertEqual(type(t.body[1]), ast.Expr)
self.assertEqual(type(t.body[1].value), ast.JoinedStr)
self.assertEqual(len(t.body[1].value.values), 5)
self.assertEqual(type(t.body[1].value.values[0]), ast.FormattedValue)
self.assertEqual(type(t.body[1].value.values[1]), ast.Str)
self.assertEqual(type(t.body[1].value.values[2]), ast.FormattedValue)
self.assertEqual(type(t.body[1].value.values[3]), ast.Str)
self.assertEqual(type(t.body[1].value.values[4]), ast.FormattedValue)
self.assertEqual(t.body[1].lineno, 3)
self.assertEqual(t.body[1].value.lineno, 3)
self.assertEqual(t.body[1].value.values[0].lineno, 3)
self.assertEqual(t.body[1].value.values[1].lineno, 3)
self.assertEqual(t.body[1].value.values[2].lineno, 3)
self.assertEqual(t.body[1].value.values[3].lineno, 3)
self.assertEqual(t.body[1].value.values[4].lineno, 3)
# check the first binop location
binop = t.body[1].value.values[0].value
self.assertEqual(type(binop), ast.BinOp)
self.assertEqual(type(binop.left), ast.Name)
self.assertEqual(type(binop.op), ast.Mult)
self.assertEqual(type(binop.right), ast.Call)
self.assertEqual(binop.lineno, 3)
self.assertEqual(binop.left.lineno, 3)
self.assertEqual(binop.right.lineno, 3)
self.assertEqual(binop.col_offset, 3)
self.assertEqual(binop.left.col_offset, 3)
self.assertEqual(binop.right.col_offset, 7)
# check the second binop location
binop = t.body[1].value.values[2].value
self.assertEqual(type(binop), ast.BinOp)
self.assertEqual(type(binop.left), ast.Name)
self.assertEqual(type(binop.op), ast.Mult)
self.assertEqual(type(binop.right), ast.Call)
self.assertEqual(binop.lineno, 3)
self.assertEqual(binop.left.lineno, 3)
self.assertEqual(binop.right.lineno, 3)
self.assertEqual(binop.col_offset, 3) # FIXME: this is wrong
self.assertEqual(binop.left.col_offset, 3) # FIXME: this is wrong
self.assertEqual(binop.right.col_offset, 7) # FIXME: this is wrong
# check the third binop location
binop = t.body[1].value.values[4].value
self.assertEqual(type(binop), ast.BinOp)
self.assertEqual(type(binop.left), ast.Name)
self.assertEqual(type(binop.op), ast.Mult)
self.assertEqual(type(binop.right), ast.Call)
self.assertEqual(binop.lineno, 3)
self.assertEqual(binop.left.lineno, 3)
self.assertEqual(binop.right.lineno, 3)
self.assertEqual(binop.col_offset, 3) # FIXME: this is wrong
self.assertEqual(binop.left.col_offset, 3) # FIXME: this is wrong
self.assertEqual(binop.right.col_offset, 7) # FIXME: this is wrong
def test_ast_line_numbers_multiline_fstring(self):
# FIXME: This test demonstrates invalid behavior due to JoinedStr's
# immediate child nodes containing the wrong lineno. The enclosed
# expressions have valid line information and column offsets.
# See bpo-16806 and bpo-30465 for details.
expr = """
a = 10
f'''
{a
*
x()}
non-important content
'''
"""
t = ast.parse(expr)
self.assertEqual(type(t), ast.Module)
self.assertEqual(len(t.body), 2)
# check `a = 10`
self.assertEqual(type(t.body[0]), ast.Assign)
self.assertEqual(t.body[0].lineno, 2)
# check `f'...'`
self.assertEqual(type(t.body[1]), ast.Expr)
self.assertEqual(type(t.body[1].value), ast.JoinedStr)
self.assertEqual(len(t.body[1].value.values), 3)
self.assertEqual(type(t.body[1].value.values[0]), ast.Str)
self.assertEqual(type(t.body[1].value.values[1]), ast.FormattedValue)
self.assertEqual(type(t.body[1].value.values[2]), ast.Str)
# NOTE: the following invalid behavior is described in bpo-16806.
# - line number should be the *first* line (3), not the *last* (8)
# - column offset should not be -1
self.assertEqual(t.body[1].lineno, 8)
self.assertEqual(t.body[1].value.lineno, 8)
self.assertEqual(t.body[1].value.values[0].lineno, 8)
self.assertEqual(t.body[1].value.values[1].lineno, 8)
self.assertEqual(t.body[1].value.values[2].lineno, 8)
self.assertEqual(t.body[1].col_offset, -1)
self.assertEqual(t.body[1].value.col_offset, -1)
self.assertEqual(t.body[1].value.values[0].col_offset, -1)
self.assertEqual(t.body[1].value.values[1].col_offset, -1)
self.assertEqual(t.body[1].value.values[2].col_offset, -1)
# NOTE: the following lineno information and col_offset is correct for
# expressions within FormattedValues.
binop = t.body[1].value.values[1].value
self.assertEqual(type(binop), ast.BinOp)
self.assertEqual(type(binop.left), ast.Name)
self.assertEqual(type(binop.op), ast.Mult)
self.assertEqual(type(binop.right), ast.Call)
self.assertEqual(binop.lineno, 4)
self.assertEqual(binop.left.lineno, 4)
self.assertEqual(binop.right.lineno, 6)
self.assertEqual(binop.col_offset, 3)
self.assertEqual(binop.left.col_offset, 3)
self.assertEqual(binop.right.col_offset, 7)
def test_docstring(self):
def f():
f'''Not a docstring'''
self.assertIsNone(f.__doc__)
def g():
'''Not a docstring''' \
f''
self.assertIsNone(g.__doc__)
def test_literal_eval(self):
with self.assertRaisesRegex(ValueError, 'malformed node or string'):
ast.literal_eval("f'x'")
def test_ast_compile_time_concat(self):
x = ['']
expr = """x[0] = 'foo' f'{3}'"""
t = ast.parse(expr)
c = compile(t, '', 'exec')
exec(c)
self.assertEqual(x[0], 'foo3')
def test_compile_time_concat_errors(self):
self.assertAllRaise(SyntaxError,
'cannot mix bytes and nonbytes literals',
[r"""f'' b''""",
r"""b'' f''""",
])
def test_literal(self):
self.assertEqual(f'', '')
self.assertEqual(f'a', 'a')
self.assertEqual(f' ', ' ')
def test_unterminated_string(self):
self.assertAllRaise(SyntaxError, 'f-string: unterminated string',
[r"""f'{"x'""",
r"""f'{"x}'""",
r"""f'{("x'""",
r"""f'{("x}'""",
])
def test_mismatched_parens(self):
self.assertAllRaise(SyntaxError, 'f-string: mismatched',
["f'{((}'",
])
def test_double_braces(self):
self.assertEqual(f'{{', '{')
self.assertEqual(f'a{{', 'a{')
self.assertEqual(f'{{b', '{b')
self.assertEqual(f'a{{b', 'a{b')
self.assertEqual(f'}}', '}')
self.assertEqual(f'a}}', 'a}')
self.assertEqual(f'}}b', '}b')
self.assertEqual(f'a}}b', 'a}b')
self.assertEqual(f'{{}}', '{}')
self.assertEqual(f'a{{}}', 'a{}')
self.assertEqual(f'{{b}}', '{b}')
self.assertEqual(f'{{}}c', '{}c')
self.assertEqual(f'a{{b}}', 'a{b}')
self.assertEqual(f'a{{}}c', 'a{}c')
self.assertEqual(f'{{b}}c', '{b}c')
self.assertEqual(f'a{{b}}c', 'a{b}c')
self.assertEqual(f'{{{10}', '{10')
self.assertEqual(f'}}{10}', '}10')
self.assertEqual(f'}}{{{10}', '}{10')
self.assertEqual(f'}}a{{{10}', '}a{10')
self.assertEqual(f'{10}{{', '10{')
self.assertEqual(f'{10}}}', '10}')
self.assertEqual(f'{10}}}{{', '10}{')
self.assertEqual(f'{10}}}a{{' '}', '10}a{}')
# Inside of strings, don't interpret doubled brackets.
self.assertEqual(f'{"{{}}"}', '{{}}')
self.assertAllRaise(TypeError, 'unhashable type',
["f'{ {{}} }'", # dict in a set
])
def test_compile_time_concat(self):
x = 'def'
self.assertEqual('abc' f'## {x}ghi', 'abc## defghi')
self.assertEqual('abc' f'{x}' 'ghi', 'abcdefghi')
self.assertEqual('abc' f'{x}' 'gh' f'i{x:4}', 'abcdefghidef ')
self.assertEqual('{x}' f'{x}', '{x}def')
self.assertEqual('{x' f'{x}', '{xdef')
self.assertEqual('{x}' f'{x}', '{x}def')
self.assertEqual('{{x}}' f'{x}', '{{x}}def')
self.assertEqual('{{x' f'{x}', '{{xdef')
self.assertEqual('x}}' f'{x}', 'x}}def')
self.assertEqual(f'{x}' 'x}}', 'defx}}')
self.assertEqual(f'{x}' '', 'def')
self.assertEqual('' f'{x}' '', 'def')
self.assertEqual('' f'{x}', 'def')
self.assertEqual(f'{x}' '2', 'def2')
self.assertEqual('1' f'{x}' '2', '1def2')
self.assertEqual('1' f'{x}', '1def')
self.assertEqual(f'{x}' f'-{x}', 'def-def')
self.assertEqual('' f'', '')
self.assertEqual('' f'' '', '')
self.assertEqual('' f'' '' f'', '')
self.assertEqual(f'', '')
self.assertEqual(f'' '', '')
self.assertEqual(f'' '' f'', '')
self.assertEqual(f'' '' f'' '', '')
self.assertAllRaise(SyntaxError, "f-string: expecting '}'",
["f'{3' f'}'", # can't concat to get a valid f-string
])
def test_comments(self):
# These aren't comments, since they're in strings.
d = {'#': 'hash'}
self.assertEqual(f'{"#"}', '#')
self.assertEqual(f'{d["#"]}', 'hash')
self.assertAllRaise(SyntaxError, "f-string expression part cannot include '#'",
["f'{1#}'", # error because the expression becomes "(1#)"
"f'{3(#)}'",
"f'{#}'",
"f'{)#}'", # When wrapped in parens, this becomes
# '()#)'. Make sure that doesn't compile.
])
def test_many_expressions(self):
# Create a string with many expressions in it. Note that
# because we have a space in here as a literal, we're actually
# going to use twice as many ast nodes: one for each literal
# plus one for each expression.
def build_fstr(n, extra=''):
return "f'" + ('{x} ' * n) + extra + "'"
x = 'X'
width = 1
# Test around 256.
for i in range(250, 260):
self.assertEqual(eval(build_fstr(i)), (x+' ')*i)
# Test concatenating 2 largs fstrings.
self.assertEqual(eval(build_fstr(255)*256), (x+' ')*(255*256))
s = build_fstr(253, '{x:{width}} ')
self.assertEqual(eval(s), (x+' ')*254)
# Test lots of expressions and constants, concatenated.
s = "f'{1}' 'x' 'y'" * 1024
self.assertEqual(eval(s), '1xy' * 1024)
def test_format_specifier_expressions(self):
width = 10
precision = 4
value = decimal.Decimal('12.34567')
self.assertEqual(f'result: {value:{width}.{precision}}', 'result: 12.35')
self.assertEqual(f'result: {value:{width!r}.{precision}}', 'result: 12.35')
self.assertEqual(f'result: {value:{width:0}.{precision:1}}', 'result: 12.35')
self.assertEqual(f'result: {value:{1}{0:0}.{precision:1}}', 'result: 12.35')
self.assertEqual(f'result: {value:{ 1}{ 0:0}.{ precision:1}}', 'result: 12.35')
self.assertEqual(f'{10:#{1}0x}', ' 0xa')
self.assertEqual(f'{10:{"#"}1{0}{"x"}}', ' 0xa')
self.assertEqual(f'{-10:-{"#"}1{0}x}', ' -0xa')
self.assertEqual(f'{-10:{"-"}#{1}0{"x"}}', ' -0xa')
self.assertEqual(f'{10:#{3 != {4:5} and width}x}', ' 0xa')
self.assertAllRaise(SyntaxError, "f-string: expecting '}'",
["""f'{"s"!r{":10"}}'""",
# This looks like a nested format spec.
])
self.assertAllRaise(SyntaxError, "invalid syntax",
[# Invalid syntax inside a nested spec.
"f'{4:{/5}}'",
])
self.assertAllRaise(SyntaxError, "f-string: expressions nested too deeply",
[# Can't nest format specifiers.
"f'result: {value:{width:{0}}.{precision:1}}'",
])
self.assertAllRaise(SyntaxError, 'f-string: invalid conversion character',
[# No expansion inside conversion or for
# the : or ! itself.
"""f'{"s"!{"r"}}'""",
])
def test_side_effect_order(self):
class X:
def __init__(self):
self.i = 0
def __format__(self, spec):
self.i += 1
return str(self.i)
x = X()
self.assertEqual(f'{x} {x}', '1 2')
def test_missing_expression(self):
self.assertAllRaise(SyntaxError, 'f-string: empty expression not allowed',
["f'{}'",
"f'{ }'"
"f' {} '",
"f'{!r}'",
"f'{ !r}'",
"f'{10:{ }}'",
"f' { } '",
# The Python parser ignores also the following
# whitespace characters in additional to a space.
"f'''{\t\f\r\n}'''",
# Catch the empty expression before the
# invalid conversion.
"f'{!x}'",
"f'{ !xr}'",
"f'{!x:}'",
"f'{!x:a}'",
"f'{ !xr:}'",
"f'{ !xr:a}'",
"f'{!}'",
"f'{:}'",
# We find the empty expression before the
# missing closing brace.
"f'{!'",
"f'{!s:'",
"f'{:'",
"f'{:x'",
])
# Different error message is raised for other whitespace characters.
self.assertAllRaise(SyntaxError, 'invalid character in identifier',
["f'''{\xa0}'''",
"\xa0",
])
def test_parens_in_expressions(self):
self.assertEqual(f'{3,}', '(3,)')
# Add these because when an expression is evaluated, parens
# are added around it. But we shouldn't go from an invalid
# expression to a valid one. The added parens are just
# supposed to allow whitespace (including newlines).
self.assertAllRaise(SyntaxError, 'invalid syntax',
["f'{,}'",
"f'{,}'", # this is (,), which is an error
])
self.assertAllRaise(SyntaxError, "f-string: expecting '}'",
["f'{3)+(4}'",
])
self.assertAllRaise(SyntaxError, 'EOL while scanning string literal',
["f'{\n}'",
])
def test_backslashes_in_string_part(self):
self.assertEqual(f'\t', '\t')
self.assertEqual(r'\t', '\\t')
self.assertEqual(rf'\t', '\\t')
self.assertEqual(f'{2}\t', '2\t')
self.assertEqual(f'{2}\t{3}', '2\t3')
self.assertEqual(f'\t{3}', '\t3')
self.assertEqual(f'\u0394', '\u0394')
self.assertEqual(r'\u0394', '\\u0394')
self.assertEqual(rf'\u0394', '\\u0394')
self.assertEqual(f'{2}\u0394', '2\u0394')
self.assertEqual(f'{2}\u0394{3}', '2\u03943')
self.assertEqual(f'\u0394{3}', '\u03943')
self.assertEqual(f'\U00000394', '\u0394')
self.assertEqual(r'\U00000394', '\\U00000394')
self.assertEqual(rf'\U00000394', '\\U00000394')
self.assertEqual(f'{2}\U00000394', '2\u0394')
self.assertEqual(f'{2}\U00000394{3}', '2\u03943')
self.assertEqual(f'\U00000394{3}', '\u03943')
self.assertEqual(f'\N{GREEK CAPITAL LETTER DELTA}', '\u0394')
self.assertEqual(f'{2}\N{GREEK CAPITAL LETTER DELTA}', '2\u0394')
self.assertEqual(f'{2}\N{GREEK CAPITAL LETTER DELTA}{3}', '2\u03943')
self.assertEqual(f'\N{GREEK CAPITAL LETTER DELTA}{3}', '\u03943')
self.assertEqual(f'2\N{GREEK CAPITAL LETTER DELTA}', '2\u0394')
self.assertEqual(f'2\N{GREEK CAPITAL LETTER DELTA}3', '2\u03943')
self.assertEqual(f'\N{GREEK CAPITAL LETTER DELTA}3', '\u03943')
self.assertEqual(f'\x20', ' ')
self.assertEqual(r'\x20', '\\x20')
self.assertEqual(rf'\x20', '\\x20')
self.assertEqual(f'{2}\x20', '2 ')
self.assertEqual(f'{2}\x20{3}', '2 3')
self.assertEqual(f'\x20{3}', ' 3')
self.assertEqual(f'2\x20', '2 ')
self.assertEqual(f'2\x203', '2 3')
self.assertEqual(f'\x203', ' 3')
with self.assertWarns(DeprecationWarning): # invalid escape sequence
value = eval(r"f'\{6*7}'")
self.assertEqual(value, '\\42')
self.assertEqual(f'\\{6*7}', '\\42')
self.assertEqual(fr'\{6*7}', '\\42')
AMPERSAND = 'spam'
# Get the right unicode character (&), or pick up local variable
# depending on the number of backslashes.
self.assertEqual(f'\N{AMPERSAND}', '&')
self.assertEqual(f'\\N{AMPERSAND}', '\\Nspam')
self.assertEqual(fr'\N{AMPERSAND}', '\\Nspam')
self.assertEqual(f'\\\N{AMPERSAND}', '\\&')
def test_misformed_unicode_character_name(self):
# These test are needed because unicode names are parsed
# differently inside f-strings.
self.assertAllRaise(SyntaxError, r"\(unicode error\) 'unicodeescape' codec can't decode bytes in position .*: malformed \\N character escape",
[r"f'\N'",
r"f'\N{'",
r"f'\N{GREEK CAPITAL LETTER DELTA'",
# Here are the non-f-string versions,
# which should give the same errors.
r"'\N'",
r"'\N{'",
r"'\N{GREEK CAPITAL LETTER DELTA'",
])
def test_no_backslashes_in_expression_part(self):
self.assertAllRaise(SyntaxError, 'f-string expression part cannot include a backslash',
[r"f'{\'a\'}'",
r"f'{\t3}'",
r"f'{\}'",
r"rf'{\'a\'}'",
r"rf'{\t3}'",
r"rf'{\}'",
r"""rf'{"\N{LEFT CURLY BRACKET}"}'""",
r"f'{\n}'",
])
def test_no_escapes_for_braces(self):
"""
Only literal curly braces begin an expression.
"""
# \x7b is '{'.
self.assertEqual(f'\x7b1+1}}', '{1+1}')
self.assertEqual(f'\x7b1+1', '{1+1')
self.assertEqual(f'\u007b1+1', '{1+1')
self.assertEqual(f'\N{LEFT CURLY BRACKET}1+1\N{RIGHT CURLY BRACKET}', '{1+1}')
def test_newlines_in_expressions(self):
self.assertEqual(f'{0}', '0')
self.assertEqual(rf'''{3+
4}''', '7')
def test_lambda(self):
x = 5
self.assertEqual(f'{(lambda y:x*y)("8")!r}', "'88888'")
self.assertEqual(f'{(lambda y:x*y)("8")!r:10}', "'88888' ")
self.assertEqual(f'{(lambda y:x*y)("8"):10}', "88888 ")
# lambda doesn't work without parens, because the colon
# makes the parser think it's a format_spec
self.assertAllRaise(SyntaxError, 'unexpected EOF while parsing',
["f'{lambda x:x}'",
])
def test_yield(self):
# Not terribly useful, but make sure the yield turns
# a function into a generator
def fn(y):
f'y:{yield y*2}'
g = fn(4)
self.assertEqual(next(g), 8)
def test_yield_send(self):
def fn(x):
yield f'x:{yield (lambda i: x * i)}'
g = fn(10)
the_lambda = next(g)
self.assertEqual(the_lambda(4), 40)
self.assertEqual(g.send('string'), 'x:string')
def test_expressions_with_triple_quoted_strings(self):
self.assertEqual(f"{'''x'''}", 'x')
self.assertEqual(f"{'''eric's'''}", "eric's")
# Test concatenation within an expression
self.assertEqual(f'{"x" """eric"s""" "y"}', 'xeric"sy')
self.assertEqual(f'{"x" """eric"s"""}', 'xeric"s')
self.assertEqual(f'{"""eric"s""" "y"}', 'eric"sy')
self.assertEqual(f'{"""x""" """eric"s""" "y"}', 'xeric"sy')
self.assertEqual(f'{"""x""" """eric"s""" """y"""}', 'xeric"sy')
self.assertEqual(f'{r"""x""" """eric"s""" """y"""}', 'xeric"sy')
def test_multiple_vars(self):
x = 98
y = 'abc'
self.assertEqual(f'{x}{y}', '98abc')
self.assertEqual(f'X{x}{y}', 'X98abc')
self.assertEqual(f'{x}X{y}', '98Xabc')
self.assertEqual(f'{x}{y}X', '98abcX')
self.assertEqual(f'X{x}Y{y}', 'X98Yabc')
self.assertEqual(f'X{x}{y}Y', 'X98abcY')
self.assertEqual(f'{x}X{y}Y', '98XabcY')
self.assertEqual(f'X{x}Y{y}Z', 'X98YabcZ')
def test_closure(self):
def outer(x):
def inner():
return f'x:{x}'
return inner
self.assertEqual(outer('987')(), 'x:987')
self.assertEqual(outer(7)(), 'x:7')
def test_arguments(self):
y = 2
def f(x, width):
return f'x={x*y:{width}}'
self.assertEqual(f('foo', 10), 'x=foofoo ')
x = 'bar'
self.assertEqual(f(10, 10), 'x= 20')
def test_locals(self):
value = 123
self.assertEqual(f'v:{value}', 'v:123')
def test_missing_variable(self):
with self.assertRaises(NameError):
f'v:{value}'
def test_missing_format_spec(self):
class O:
def __format__(self, spec):
if not spec:
return '*'
return spec
self.assertEqual(f'{O():x}', 'x')
self.assertEqual(f'{O()}', '*')
self.assertEqual(f'{O():}', '*')
self.assertEqual(f'{3:}', '3')
self.assertEqual(f'{3!s:}', '3')
def test_global(self):
self.assertEqual(f'g:{a_global}', 'g:global variable')
self.assertEqual(f'g:{a_global!r}', "g:'global variable'")
a_local = 'local variable'
self.assertEqual(f'g:{a_global} l:{a_local}',
'g:global variable l:local variable')
self.assertEqual(f'g:{a_global!r}',
"g:'global variable'")
self.assertEqual(f'g:{a_global} l:{a_local!r}',
"g:global variable l:'local variable'")
self.assertIn("module 'unittest' from", f'{unittest}')
def test_shadowed_global(self):
a_global = 'really a local'
self.assertEqual(f'g:{a_global}', 'g:really a local')
self.assertEqual(f'g:{a_global!r}', "g:'really a local'")
a_local = 'local variable'
self.assertEqual(f'g:{a_global} l:{a_local}',
'g:really a local l:local variable')
self.assertEqual(f'g:{a_global!r}',
"g:'really a local'")
self.assertEqual(f'g:{a_global} l:{a_local!r}',
"g:really a local l:'local variable'")
def test_call(self):
def foo(x):
return 'x=' + str(x)
self.assertEqual(f'{foo(10)}', 'x=10')
def test_nested_fstrings(self):
y = 5
self.assertEqual(f'{f"{0}"*3}', '000')
self.assertEqual(f'{f"{y}"*3}', '555')
def test_invalid_string_prefixes(self):
self.assertAllRaise(SyntaxError, 'unexpected EOF while parsing',
["fu''",
"uf''",
"Fu''",
"fU''",
"Uf''",
"uF''",
"ufr''",
"urf''",
"fur''",
"fru''",
"rfu''",
"ruf''",
"FUR''",
"Fur''",
"fb''",
"fB''",
"Fb''",
"FB''",
"bf''",
"bF''",
"Bf''",
"BF''",
])
def test_leading_trailing_spaces(self):
self.assertEqual(f'{ 3}', '3')
self.assertEqual(f'{ 3}', '3')
self.assertEqual(f'{3 }', '3')
self.assertEqual(f'{3 }', '3')
self.assertEqual(f'expr={ {x: y for x, y in [(1, 2), ]}}',
'expr={1: 2}')
self.assertEqual(f'expr={ {x: y for x, y in [(1, 2), ]} }',
'expr={1: 2}')
def test_not_equal(self):
# There's a special test for this because there's a special
# case in the f-string parser to look for != as not ending an
# expression. Normally it would, while looking for !s or !r.
self.assertEqual(f'{3!=4}', 'True')
self.assertEqual(f'{3!=4:}', 'True')
self.assertEqual(f'{3!=4!s}', 'True')
self.assertEqual(f'{3!=4!s:.3}', 'Tru')
def test_conversions(self):
self.assertEqual(f'{3.14:10.10}', ' 3.14')
self.assertEqual(f'{3.14!s:10.10}', '3.14 ')
self.assertEqual(f'{3.14!r:10.10}', '3.14 ')
self.assertEqual(f'{3.14!a:10.10}', '3.14 ')
self.assertEqual(f'{"a"}', 'a')
self.assertEqual(f'{"a"!r}', "'a'")
self.assertEqual(f'{"a"!a}', "'a'")
# Not a conversion.
self.assertEqual(f'{"a!r"}', "a!r")
# Not a conversion, but show that ! is allowed in a format spec.
self.assertEqual(f'{3.14:!<10.10}', '3.14!!!!!!')
self.assertAllRaise(SyntaxError, 'f-string: invalid conversion character',
["f'{3!g}'",
"f'{3!A}'",
"f'{3!3}'",
"f'{3!G}'",
"f'{3!!}'",
"f'{3!:}'",
"f'{3! s}'", # no space before conversion char
])
self.assertAllRaise(SyntaxError, "f-string: expecting '}'",
["f'{x!s{y}}'",
"f'{3!ss}'",
"f'{3!ss:}'",
"f'{3!ss:s}'",
])
def test_assignment(self):
self.assertAllRaise(SyntaxError, 'invalid syntax',
["f'' = 3",
"f'{0}' = x",
"f'{x}' = x",
])
def test_del(self):
self.assertAllRaise(SyntaxError, 'invalid syntax',
["del f''",
"del '' f''",
])
def test_mismatched_braces(self):
self.assertAllRaise(SyntaxError, "f-string: single '}' is not allowed",
["f'{{}'",
"f'{{}}}'",
"f'}'",
"f'x}'",
"f'x}x'",
r"f'\u007b}'",
# Can't have { or } in a format spec.
"f'{3:}>10}'",
"f'{3:}}>10}'",
])
self.assertAllRaise(SyntaxError, "f-string: expecting '}'",
["f'{3:{{>10}'",
"f'{3'",
"f'{3!'",
"f'{3:'",
"f'{3!s'",
"f'{3!s:'",
"f'{3!s:3'",
"f'x{'",
"f'x{x'",
"f'{x'",
"f'{3:s'",
"f'{{{'",
"f'{{}}{'",
"f'{'",
])
# But these are just normal strings.
self.assertEqual(f'{"{"}', '{')
self.assertEqual(f'{"}"}', '}')
self.assertEqual(f'{3:{"}"}>10}', '}}}}}}}}}3')
self.assertEqual(f'{2:{"{"}>10}', '{{{{{{{{{2')
def test_if_conditional(self):
# There's special logic in compile.c to test if the
# conditional for an if (and while) are constants. Exercise
# that code.
def test_fstring(x, expected):
flag = 0
if f'{x}':
flag = 1
else:
flag = 2
self.assertEqual(flag, expected)
def test_concat_empty(x, expected):
flag = 0
if '' f'{x}':
flag = 1
else:
flag = 2
self.assertEqual(flag, expected)
def test_concat_non_empty(x, expected):
flag = 0
if ' ' f'{x}':
flag = 1
else:
flag = 2
self.assertEqual(flag, expected)
test_fstring('', 2)
test_fstring(' ', 1)
test_concat_empty('', 2)
test_concat_empty(' ', 1)
test_concat_non_empty('', 1)
test_concat_non_empty(' ', 1)
def test_empty_format_specifier(self):
x = 'test'
self.assertEqual(f'{x}', 'test')
self.assertEqual(f'{x:}', 'test')
self.assertEqual(f'{x!s:}', 'test')
self.assertEqual(f'{x!r:}', "'test'")
def test_str_format_differences(self):
d = {'a': 'string',
0: 'integer',
}
a = 0
self.assertEqual(f'{d[0]}', 'integer')
self.assertEqual(f'{d["a"]}', 'string')
self.assertEqual(f'{d[a]}', 'integer')
self.assertEqual('{d[a]}'.format(d=d), 'string')
self.assertEqual('{d[0]}'.format(d=d), 'integer')
def test_invalid_expressions(self):
self.assertAllRaise(SyntaxError, 'invalid syntax',
[r"f'{a[4)}'",
r"f'{a(4]}'",
])
def test_errors(self):
# see issue 26287
self.assertAllRaise(TypeError, 'unsupported',
[r"f'{(lambda: 0):x}'",
r"f'{(0,):x}'",
])
self.assertAllRaise(ValueError, 'Unknown format code',
[r"f'{1000:j}'",
r"f'{1000:j}'",
])
def test_loop(self):
for i in range(1000):
self.assertEqual(f'i:{i}', 'i:' + str(i))
def test_dict(self):
d = {'"': 'dquote',
"'": 'squote',
'foo': 'bar',
}
self.assertEqual(f'''{d["'"]}''', 'squote')
self.assertEqual(f"""{d['"']}""", 'dquote')
self.assertEqual(f'{d["foo"]}', 'bar')
self.assertEqual(f"{d['foo']}", 'bar')
def test_backslash_char(self):
# Check eval of a backslash followed by a control char.
# See bpo-30682: this used to raise an assert in pydebug mode.
self.assertEqual(eval('f"\\\n"'), '')
self.assertEqual(eval('f"\\\r"'), '')
if __name__ == '__main__':
unittest.main()
| 41,197 | 1,038 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_eintr.py | import os
import signal
import subprocess
import sys
import unittest
from test import support
from test.support import script_helper
@unittest.skipUnless(os.name == "posix", "only supported on Unix")
class EINTRTests(unittest.TestCase):
@unittest.skipUnless(hasattr(signal, "setitimer"), "requires setitimer()")
def test_all(self):
# Run the tester in a sub-process, to make sure there is only one
# thread (for reliable signal delivery).
tester = support.findfile("eintr_tester.py", subdir="eintrdata")
# use -u to try to get the full output if the test hangs or crash
args = ["-u", tester, "-v"]
if support.verbose:
print()
print("--- run eintr_tester.py ---", flush=True)
# In verbose mode, the child process inherit stdout and stdout,
# to see output in realtime and reduce the risk of loosing output.
args = [sys.executable, "-E", "-X", "faulthandler", *args]
proc = subprocess.run(args)
print(f"--- eintr_tester.py completed: "
f"exit code {proc.returncode} ---", flush=True)
if proc.returncode:
self.fail("eintr_tester.py failed")
else:
script_helper.assert_python_ok("-u", tester, "-v")
if __name__ == "__main__":
unittest.main()
| 1,354 | 38 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_subclassinit.py | import sys
import types
import unittest
class Test(unittest.TestCase):
def test_init_subclass(self):
class A:
initialized = False
def __init_subclass__(cls):
super().__init_subclass__()
cls.initialized = True
class B(A):
pass
self.assertFalse(A.initialized)
self.assertTrue(B.initialized)
def test_init_subclass_dict(self):
class A(dict):
initialized = False
def __init_subclass__(cls):
super().__init_subclass__()
cls.initialized = True
class B(A):
pass
self.assertFalse(A.initialized)
self.assertTrue(B.initialized)
def test_init_subclass_kwargs(self):
class A:
def __init_subclass__(cls, **kwargs):
cls.kwargs = kwargs
class B(A, x=3):
pass
self.assertEqual(B.kwargs, dict(x=3))
def test_init_subclass_error(self):
class A:
def __init_subclass__(cls):
raise RuntimeError
with self.assertRaises(RuntimeError):
class B(A):
pass
def test_init_subclass_wrong(self):
class A:
def __init_subclass__(cls, whatever):
pass
with self.assertRaises(TypeError):
class B(A):
pass
def test_init_subclass_skipped(self):
class BaseWithInit:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.initialized = cls
class BaseWithoutInit(BaseWithInit):
pass
class A(BaseWithoutInit):
pass
self.assertIs(A.initialized, A)
self.assertIs(BaseWithoutInit.initialized, BaseWithoutInit)
def test_init_subclass_diamond(self):
class Base:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.calls = []
class Left(Base):
pass
class Middle:
def __init_subclass__(cls, middle, **kwargs):
super().__init_subclass__(**kwargs)
cls.calls += [middle]
class Right(Base):
def __init_subclass__(cls, right="right", **kwargs):
super().__init_subclass__(**kwargs)
cls.calls += [right]
class A(Left, Middle, Right, middle="middle"):
pass
self.assertEqual(A.calls, ["right", "middle"])
self.assertEqual(Left.calls, [])
self.assertEqual(Right.calls, [])
def test_set_name(self):
class Descriptor:
def __set_name__(self, owner, name):
self.owner = owner
self.name = name
class A:
d = Descriptor()
self.assertEqual(A.d.name, "d")
self.assertIs(A.d.owner, A)
def test_set_name_metaclass(self):
class Meta(type):
def __new__(cls, name, bases, ns):
ret = super().__new__(cls, name, bases, ns)
self.assertEqual(ret.d.name, "d")
self.assertIs(ret.d.owner, ret)
return 0
class Descriptor:
def __set_name__(self, owner, name):
self.owner = owner
self.name = name
class A(metaclass=Meta):
d = Descriptor()
self.assertEqual(A, 0)
def test_set_name_error(self):
class Descriptor:
def __set_name__(self, owner, name):
1/0
with self.assertRaises(RuntimeError) as cm:
class NotGoingToWork:
attr = Descriptor()
exc = cm.exception
self.assertRegex(str(exc), r'\bNotGoingToWork\b')
self.assertRegex(str(exc), r'\battr\b')
self.assertRegex(str(exc), r'\bDescriptor\b')
self.assertIsInstance(exc.__cause__, ZeroDivisionError)
def test_set_name_wrong(self):
class Descriptor:
def __set_name__(self):
pass
with self.assertRaises(RuntimeError) as cm:
class NotGoingToWork:
attr = Descriptor()
exc = cm.exception
self.assertRegex(str(exc), r'\bNotGoingToWork\b')
self.assertRegex(str(exc), r'\battr\b')
self.assertRegex(str(exc), r'\bDescriptor\b')
self.assertIsInstance(exc.__cause__, TypeError)
def test_set_name_lookup(self):
resolved = []
class NonDescriptor:
def __getattr__(self, name):
resolved.append(name)
class A:
d = NonDescriptor()
self.assertNotIn('__set_name__', resolved,
'__set_name__ is looked up in instance dict')
def test_set_name_init_subclass(self):
class Descriptor:
def __set_name__(self, owner, name):
self.owner = owner
self.name = name
class Meta(type):
def __new__(cls, name, bases, ns):
self = super().__new__(cls, name, bases, ns)
self.meta_owner = self.owner
self.meta_name = self.name
return self
class A:
def __init_subclass__(cls):
cls.owner = cls.d.owner
cls.name = cls.d.name
class B(A, metaclass=Meta):
d = Descriptor()
self.assertIs(B.owner, B)
self.assertEqual(B.name, 'd')
self.assertIs(B.meta_owner, B)
self.assertEqual(B.name, 'd')
def test_set_name_modifying_dict(self):
notified = []
class Descriptor:
def __set_name__(self, owner, name):
setattr(owner, name + 'x', None)
notified.append(name)
class A:
a = Descriptor()
b = Descriptor()
c = Descriptor()
d = Descriptor()
e = Descriptor()
self.assertCountEqual(notified, ['a', 'b', 'c', 'd', 'e'])
def test_errors(self):
class MyMeta(type):
pass
with self.assertRaises(TypeError):
class MyClass(metaclass=MyMeta, otherarg=1):
pass
with self.assertRaises(TypeError):
types.new_class("MyClass", (object,),
dict(metaclass=MyMeta, otherarg=1))
types.prepare_class("MyClass", (object,),
dict(metaclass=MyMeta, otherarg=1))
class MyMeta(type):
def __init__(self, name, bases, namespace, otherarg):
super().__init__(name, bases, namespace)
with self.assertRaises(TypeError):
class MyClass(metaclass=MyMeta, otherarg=1):
pass
class MyMeta(type):
def __new__(cls, name, bases, namespace, otherarg):
return super().__new__(cls, name, bases, namespace)
def __init__(self, name, bases, namespace, otherarg):
super().__init__(name, bases, namespace)
self.otherarg = otherarg
class MyClass(metaclass=MyMeta, otherarg=1):
pass
self.assertEqual(MyClass.otherarg, 1)
def test_errors_changed_pep487(self):
# These tests failed before Python 3.6, PEP 487
class MyMeta(type):
def __new__(cls, name, bases, namespace):
return super().__new__(cls, name=name, bases=bases,
dict=namespace)
with self.assertRaises(TypeError):
class MyClass(metaclass=MyMeta):
pass
class MyMeta(type):
def __new__(cls, name, bases, namespace, otherarg):
self = super().__new__(cls, name, bases, namespace)
self.otherarg = otherarg
return self
class MyClass(metaclass=MyMeta, otherarg=1):
pass
self.assertEqual(MyClass.otherarg, 1)
def test_type(self):
t = type('NewClass', (object,), {})
self.assertIsInstance(t, type)
self.assertEqual(t.__name__, 'NewClass')
with self.assertRaises(TypeError):
type(name='NewClass', bases=(object,), dict={})
if __name__ == "__main__":
unittest.main()
| 8,324 | 285 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_functools.py | import abc
import cosmo
import builtins
import collections
import copy
from itertools import permutations
import pickle
from random import choice
import sys
from test import support
import time
import unittest
from weakref import proxy
import contextlib
try:
import _thread
import threading
except ImportError:
threading = None
import functools
if __name__ == 'PYOBJ.COM':
import decimal
py_functools = support.import_fresh_module('functools', blocked=['_functools'])
c_functools = support.import_fresh_module('functools', fresh=['_functools'])
decimal = support.import_fresh_module('decimal', fresh=['_decimal'])
@contextlib.contextmanager
def replaced_module(name, replacement):
original_module = sys.modules[name]
sys.modules[name] = replacement
try:
yield
finally:
sys.modules[name] = original_module
def capture(*args, **kw):
"""capture all positional and keyword arguments"""
return args, kw
def signature(part):
""" return the signature of a partial object """
return (part.func, part.args, part.keywords, part.__dict__)
class MyTuple(tuple):
pass
class BadTuple(tuple):
def __add__(self, other):
return list(self) + list(other)
class MyDict(dict):
pass
class TestPartial:
def test_basic_examples(self):
p = self.partial(capture, 1, 2, a=10, b=20)
self.assertTrue(callable(p))
self.assertEqual(p(3, 4, b=30, c=40),
((1, 2, 3, 4), dict(a=10, b=30, c=40)))
p = self.partial(map, lambda x: x*10)
self.assertEqual(list(p([1,2,3,4])), [10, 20, 30, 40])
def test_attributes(self):
p = self.partial(capture, 1, 2, a=10, b=20)
# attributes should be readable
self.assertEqual(p.func, capture)
self.assertEqual(p.args, (1, 2))
self.assertEqual(p.keywords, dict(a=10, b=20))
def test_argument_checking(self):
self.assertRaises(TypeError, self.partial) # need at least a func arg
try:
self.partial(2)()
except TypeError:
pass
else:
self.fail('First arg not checked for callability')
def test_protection_of_callers_dict_argument(self):
# a caller's dictionary should not be altered by partial
def func(a=10, b=20):
return a
d = {'a':3}
p = self.partial(func, a=5)
self.assertEqual(p(**d), 3)
self.assertEqual(d, {'a':3})
p(b=7)
self.assertEqual(d, {'a':3})
def test_kwargs_copy(self):
# Issue #29532: Altering a kwarg dictionary passed to a constructor
# should not affect a partial object after creation
d = {'a': 3}
p = self.partial(capture, **d)
self.assertEqual(p(), ((), {'a': 3}))
d['a'] = 5
self.assertEqual(p(), ((), {'a': 3}))
def test_arg_combinations(self):
# exercise special code paths for zero args in either partial
# object or the caller
p = self.partial(capture)
self.assertEqual(p(), ((), {}))
self.assertEqual(p(1,2), ((1,2), {}))
p = self.partial(capture, 1, 2)
self.assertEqual(p(), ((1,2), {}))
self.assertEqual(p(3,4), ((1,2,3,4), {}))
def test_kw_combinations(self):
# exercise special code paths for no keyword args in
# either the partial object or the caller
p = self.partial(capture)
self.assertEqual(p.keywords, {})
self.assertEqual(p(), ((), {}))
self.assertEqual(p(a=1), ((), {'a':1}))
p = self.partial(capture, a=1)
self.assertEqual(p.keywords, {'a':1})
self.assertEqual(p(), ((), {'a':1}))
self.assertEqual(p(b=2), ((), {'a':1, 'b':2}))
# keyword args in the call override those in the partial object
self.assertEqual(p(a=3, b=2), ((), {'a':3, 'b':2}))
def test_positional(self):
# make sure positional arguments are captured correctly
for args in [(), (0,), (0,1), (0,1,2), (0,1,2,3)]:
p = self.partial(capture, *args)
expected = args + ('x',)
got, empty = p('x')
self.assertTrue(expected == got and empty == {})
def test_keyword(self):
# make sure keyword arguments are captured correctly
for a in ['a', 0, None, 3.5]:
p = self.partial(capture, a=a)
expected = {'a':a,'x':None}
empty, got = p(x=None)
self.assertTrue(expected == got and empty == ())
def test_no_side_effects(self):
# make sure there are no side effects that affect subsequent calls
p = self.partial(capture, 0, a=1)
args1, kw1 = p(1, b=2)
self.assertTrue(args1 == (0,1) and kw1 == {'a':1,'b':2})
args2, kw2 = p()
self.assertTrue(args2 == (0,) and kw2 == {'a':1})
def test_error_propagation(self):
def f(x, y):
x / y
self.assertRaises(ZeroDivisionError, self.partial(f, 1, 0))
self.assertRaises(ZeroDivisionError, self.partial(f, 1), 0)
self.assertRaises(ZeroDivisionError, self.partial(f), 1, 0)
self.assertRaises(ZeroDivisionError, self.partial(f, y=0), 1)
def test_weakref(self):
f = self.partial(int, base=16)
p = proxy(f)
self.assertEqual(f.func, p.func)
f = None
self.assertRaises(ReferenceError, getattr, p, 'func')
def test_with_bound_and_unbound_methods(self):
data = list(map(str, range(10)))
join = self.partial(str.join, '')
self.assertEqual(join(data), '0123456789')
join = self.partial(''.join)
self.assertEqual(join(data), '0123456789')
def test_nested_optimization(self):
partial = self.partial
inner = partial(signature, 'asdf')
nested = partial(inner, bar=True)
flat = partial(signature, 'asdf', bar=True)
self.assertEqual(signature(nested), signature(flat))
def test_nested_partial_with_attribute(self):
# see issue 25137
partial = self.partial
def foo(bar):
return bar
p = partial(foo, 'first')
p2 = partial(p, 'second')
p2.new_attr = 'spam'
self.assertEqual(p2.new_attr, 'spam')
def test_repr(self):
args = (object(), object())
args_repr = ', '.join(repr(a) for a in args)
kwargs = {'a': object(), 'b': object()}
kwargs_reprs = ['a={a!r}, b={b!r}'.format_map(kwargs),
'b={b!r}, a={a!r}'.format_map(kwargs)]
if self.partial in (c_functools.partial, py_functools.partial):
name = 'functools.partial'
else:
name = self.partial.__name__
f = self.partial(capture)
self.assertEqual(f'{name}({capture!r})', repr(f))
f = self.partial(capture, *args)
self.assertEqual(f'{name}({capture!r}, {args_repr})', repr(f))
f = self.partial(capture, **kwargs)
self.assertIn(repr(f),
[f'{name}({capture!r}, {kwargs_repr})'
for kwargs_repr in kwargs_reprs])
f = self.partial(capture, *args, **kwargs)
self.assertIn(repr(f),
[f'{name}({capture!r}, {args_repr}, {kwargs_repr})'
for kwargs_repr in kwargs_reprs])
def test_recursive_repr(self):
if self.partial in (c_functools.partial, py_functools.partial):
name = 'functools.partial'
else:
name = self.partial.__name__
f = self.partial(capture)
f.__setstate__((f, (), {}, {}))
try:
self.assertEqual(repr(f), '%s(...)' % (name,))
finally:
f.__setstate__((capture, (), {}, {}))
f = self.partial(capture)
f.__setstate__((capture, (f,), {}, {}))
try:
self.assertEqual(repr(f), '%s(%r, ...)' % (name, capture,))
finally:
f.__setstate__((capture, (), {}, {}))
f = self.partial(capture)
f.__setstate__((capture, (), {'a': f}, {}))
try:
self.assertEqual(repr(f), '%s(%r, a=...)' % (name, capture,))
finally:
f.__setstate__((capture, (), {}, {}))
def test_pickle(self):
with self.AllowPickle():
f = self.partial(signature, ['asdf'], bar=[True])
f.attr = []
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
f_copy = pickle.loads(pickle.dumps(f, proto))
self.assertEqual(signature(f_copy), signature(f))
def test_copy(self):
f = self.partial(signature, ['asdf'], bar=[True])
f.attr = []
f_copy = copy.copy(f)
self.assertEqual(signature(f_copy), signature(f))
self.assertIs(f_copy.attr, f.attr)
self.assertIs(f_copy.args, f.args)
self.assertIs(f_copy.keywords, f.keywords)
def test_deepcopy(self):
f = self.partial(signature, ['asdf'], bar=[True])
f.attr = []
f_copy = copy.deepcopy(f)
self.assertEqual(signature(f_copy), signature(f))
self.assertIsNot(f_copy.attr, f.attr)
self.assertIsNot(f_copy.args, f.args)
self.assertIsNot(f_copy.args[0], f.args[0])
self.assertIsNot(f_copy.keywords, f.keywords)
self.assertIsNot(f_copy.keywords['bar'], f.keywords['bar'])
def test_setstate(self):
f = self.partial(signature)
f.__setstate__((capture, (1,), dict(a=10), dict(attr=[])))
self.assertEqual(signature(f),
(capture, (1,), dict(a=10), dict(attr=[])))
self.assertEqual(f(2, b=20), ((1, 2), {'a': 10, 'b': 20}))
f.__setstate__((capture, (1,), dict(a=10), None))
self.assertEqual(signature(f), (capture, (1,), dict(a=10), {}))
self.assertEqual(f(2, b=20), ((1, 2), {'a': 10, 'b': 20}))
f.__setstate__((capture, (1,), None, None))
#self.assertEqual(signature(f), (capture, (1,), {}, {}))
self.assertEqual(f(2, b=20), ((1, 2), {'b': 20}))
self.assertEqual(f(2), ((1, 2), {}))
self.assertEqual(f(), ((1,), {}))
f.__setstate__((capture, (), {}, None))
self.assertEqual(signature(f), (capture, (), {}, {}))
self.assertEqual(f(2, b=20), ((2,), {'b': 20}))
self.assertEqual(f(2), ((2,), {}))
self.assertEqual(f(), ((), {}))
def test_setstate_errors(self):
f = self.partial(signature)
self.assertRaises(TypeError, f.__setstate__, (capture, (), {}))
self.assertRaises(TypeError, f.__setstate__, (capture, (), {}, {}, None))
self.assertRaises(TypeError, f.__setstate__, [capture, (), {}, None])
self.assertRaises(TypeError, f.__setstate__, (None, (), {}, None))
self.assertRaises(TypeError, f.__setstate__, (capture, None, {}, None))
self.assertRaises(TypeError, f.__setstate__, (capture, [], {}, None))
self.assertRaises(TypeError, f.__setstate__, (capture, (), [], None))
def test_setstate_subclasses(self):
f = self.partial(signature)
f.__setstate__((capture, MyTuple((1,)), MyDict(a=10), None))
s = signature(f)
self.assertEqual(s, (capture, (1,), dict(a=10), {}))
self.assertIs(type(s[1]), tuple)
self.assertIs(type(s[2]), dict)
r = f()
self.assertEqual(r, ((1,), {'a': 10}))
self.assertIs(type(r[0]), tuple)
self.assertIs(type(r[1]), dict)
f.__setstate__((capture, BadTuple((1,)), {}, None))
s = signature(f)
self.assertEqual(s, (capture, (1,), {}, {}))
self.assertIs(type(s[1]), tuple)
r = f(2)
self.assertEqual(r, ((1, 2), {}))
self.assertIs(type(r[0]), tuple)
def test_recursive_pickle(self):
with self.AllowPickle():
if cosmo.MODE == "dbg":
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:
def __len__(self):
return 4
def __getitem__(self, key):
if key == 0:
return max
elif key == 1:
return tuple(range(1000000))
elif key in (2, 3):
return {}
raise IndexError
f = self.partial(object)
self.assertRaises(TypeError, f.__setstate__, BadSequence())
@unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestPartialC(TestPartial, unittest.TestCase):
if c_functools:
partial = c_functools.partial
class AllowPickle:
def __enter__(self):
return self
def __exit__(self, type, value, tb):
return False
def test_attributes_unwritable(self):
# attributes should not be writable
p = self.partial(capture, 1, 2, a=10, b=20)
self.assertRaises(AttributeError, setattr, p, 'func', map)
self.assertRaises(AttributeError, setattr, p, 'args', (1, 2))
self.assertRaises(AttributeError, setattr, p, 'keywords', dict(a=1, b=2))
p = self.partial(hex)
try:
del p.__dict__
except TypeError:
pass
else:
self.fail('partial object allowed __dict__ to be deleted')
def test_manually_adding_non_string_keyword(self):
p = self.partial(capture)
# Adding a non-string/unicode keyword to partial kwargs
p.keywords[1234] = 'value'
r = repr(p)
self.assertIn('1234', r)
self.assertIn("'value'", r)
with self.assertRaises(TypeError):
p()
def test_keystr_replaces_value(self):
p = self.partial(capture)
class MutatesYourDict(object):
def __str__(self):
p.keywords[self] = ['sth2']
return 'astr'
# Replacing the value during key formatting should keep the original
# value alive (at least long enough).
p.keywords[MutatesYourDict()] = ['sth']
r = repr(p)
self.assertIn('astr', r)
self.assertIn("['sth']", r)
@unittest.skipIf(c_functools, "skip pure-python test if C impl is present")
class TestPartialPy(TestPartial, unittest.TestCase):
partial = py_functools.partial
class AllowPickle:
def __init__(self):
self._cm = replaced_module("functools", py_functools)
def __enter__(self):
return self._cm.__enter__()
def __exit__(self, type, value, tb):
return self._cm.__exit__(type, value, tb)
if c_functools:
class CPartialSubclass(c_functools.partial):
pass
class PyPartialSubclass(py_functools.partial):
pass
@unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestPartialCSubclass(TestPartialC):
if c_functools:
partial = CPartialSubclass
# partial subclasses are not optimized for nested calls
test_nested_optimization = None
@unittest.skipIf(c_functools, "skip pure-python test if C impl is present")
class TestPartialPySubclass(TestPartialPy):
partial = PyPartialSubclass
class TestPartialMethod(unittest.TestCase):
class A(object):
nothing = functools.partialmethod(capture)
positional = functools.partialmethod(capture, 1)
keywords = functools.partialmethod(capture, a=2)
both = functools.partialmethod(capture, 3, b=4)
nested = functools.partialmethod(positional, 5)
over_partial = functools.partialmethod(functools.partial(capture, c=6), 7)
static = functools.partialmethod(staticmethod(capture), 8)
cls = functools.partialmethod(classmethod(capture), d=9)
a = A()
def test_arg_combinations(self):
self.assertEqual(self.a.nothing(), ((self.a,), {}))
self.assertEqual(self.a.nothing(5), ((self.a, 5), {}))
self.assertEqual(self.a.nothing(c=6), ((self.a,), {'c': 6}))
self.assertEqual(self.a.nothing(5, c=6), ((self.a, 5), {'c': 6}))
self.assertEqual(self.a.positional(), ((self.a, 1), {}))
self.assertEqual(self.a.positional(5), ((self.a, 1, 5), {}))
self.assertEqual(self.a.positional(c=6), ((self.a, 1), {'c': 6}))
self.assertEqual(self.a.positional(5, c=6), ((self.a, 1, 5), {'c': 6}))
self.assertEqual(self.a.keywords(), ((self.a,), {'a': 2}))
self.assertEqual(self.a.keywords(5), ((self.a, 5), {'a': 2}))
self.assertEqual(self.a.keywords(c=6), ((self.a,), {'a': 2, 'c': 6}))
self.assertEqual(self.a.keywords(5, c=6), ((self.a, 5), {'a': 2, 'c': 6}))
self.assertEqual(self.a.both(), ((self.a, 3), {'b': 4}))
self.assertEqual(self.a.both(5), ((self.a, 3, 5), {'b': 4}))
self.assertEqual(self.a.both(c=6), ((self.a, 3), {'b': 4, 'c': 6}))
self.assertEqual(self.a.both(5, c=6), ((self.a, 3, 5), {'b': 4, 'c': 6}))
self.assertEqual(self.A.both(self.a, 5, c=6), ((self.a, 3, 5), {'b': 4, 'c': 6}))
def test_nested(self):
self.assertEqual(self.a.nested(), ((self.a, 1, 5), {}))
self.assertEqual(self.a.nested(6), ((self.a, 1, 5, 6), {}))
self.assertEqual(self.a.nested(d=7), ((self.a, 1, 5), {'d': 7}))
self.assertEqual(self.a.nested(6, d=7), ((self.a, 1, 5, 6), {'d': 7}))
self.assertEqual(self.A.nested(self.a, 6, d=7), ((self.a, 1, 5, 6), {'d': 7}))
def test_over_partial(self):
self.assertEqual(self.a.over_partial(), ((self.a, 7), {'c': 6}))
self.assertEqual(self.a.over_partial(5), ((self.a, 7, 5), {'c': 6}))
self.assertEqual(self.a.over_partial(d=8), ((self.a, 7), {'c': 6, 'd': 8}))
self.assertEqual(self.a.over_partial(5, d=8), ((self.a, 7, 5), {'c': 6, 'd': 8}))
self.assertEqual(self.A.over_partial(self.a, 5, d=8), ((self.a, 7, 5), {'c': 6, 'd': 8}))
def test_bound_method_introspection(self):
obj = self.a
self.assertIs(obj.both.__self__, obj)
self.assertIs(obj.nested.__self__, obj)
self.assertIs(obj.over_partial.__self__, obj)
self.assertIs(obj.cls.__self__, self.A)
self.assertIs(self.A.cls.__self__, self.A)
def test_unbound_method_retrieval(self):
obj = self.A
self.assertFalse(hasattr(obj.both, "__self__"))
self.assertFalse(hasattr(obj.nested, "__self__"))
self.assertFalse(hasattr(obj.over_partial, "__self__"))
self.assertFalse(hasattr(obj.static, "__self__"))
self.assertFalse(hasattr(self.a.static, "__self__"))
def test_descriptors(self):
for obj in [self.A, self.a]:
with self.subTest(obj=obj):
self.assertEqual(obj.static(), ((8,), {}))
self.assertEqual(obj.static(5), ((8, 5), {}))
self.assertEqual(obj.static(d=8), ((8,), {'d': 8}))
self.assertEqual(obj.static(5, d=8), ((8, 5), {'d': 8}))
self.assertEqual(obj.cls(), ((self.A,), {'d': 9}))
self.assertEqual(obj.cls(5), ((self.A, 5), {'d': 9}))
self.assertEqual(obj.cls(c=8), ((self.A,), {'c': 8, 'd': 9}))
self.assertEqual(obj.cls(5, c=8), ((self.A, 5), {'c': 8, 'd': 9}))
def test_overriding_keywords(self):
self.assertEqual(self.a.keywords(a=3), ((self.a,), {'a': 3}))
self.assertEqual(self.A.keywords(self.a, a=3), ((self.a,), {'a': 3}))
def test_invalid_args(self):
with self.assertRaises(TypeError):
class B(object):
method = functools.partialmethod(None, 1)
def test_repr(self):
self.assertEqual(repr(vars(self.A)['both']),
'functools.partialmethod({}, 3, b=4)'.format(capture))
def test_abstract(self):
class Abstract(abc.ABCMeta):
@abc.abstractmethod
def add(self, x, y):
pass
add5 = functools.partialmethod(add, 5)
self.assertTrue(Abstract.add.__isabstractmethod__)
self.assertTrue(Abstract.add5.__isabstractmethod__)
for func in [self.A.static, self.A.cls, self.A.over_partial, self.A.nested, self.A.both]:
self.assertFalse(getattr(func, '__isabstractmethod__', False))
class TestUpdateWrapper(unittest.TestCase):
def check_wrapper(self, wrapper, wrapped,
assigned=functools.WRAPPER_ASSIGNMENTS,
updated=functools.WRAPPER_UPDATES):
# Check attributes were assigned
for name in assigned:
self.assertIs(getattr(wrapper, name), getattr(wrapped, name))
# Check attributes were updated
for name in updated:
wrapper_attr = getattr(wrapper, name)
wrapped_attr = getattr(wrapped, name)
for key in wrapped_attr:
if name == "__dict__" and key == "__wrapped__":
# __wrapped__ is overwritten by the update code
continue
self.assertIs(wrapped_attr[key], wrapper_attr[key])
# Check __wrapped__
self.assertIs(wrapper.__wrapped__, wrapped)
def _default_update(self):
def f(a:'This is a new annotation'):
"""This is a test"""
pass
f.attr = 'This is also a test'
f.__wrapped__ = "This is a bald faced lie"
def wrapper(b:'This is the prior annotation'):
pass
functools.update_wrapper(wrapper, f)
return wrapper, f
def test_default_update(self):
wrapper, f = self._default_update()
self.check_wrapper(wrapper, f)
self.assertIs(wrapper.__wrapped__, f)
self.assertEqual(wrapper.__name__, 'f')
self.assertEqual(wrapper.__qualname__, f.__qualname__)
self.assertEqual(wrapper.attr, 'This is also a test')
self.assertEqual(wrapper.__annotations__['a'], 'This is a new annotation')
self.assertNotIn('b', wrapper.__annotations__)
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
@unittest.skipIf(cosmo.MODE.startswith("tiny"),
"No .py files available in Cosmo MODE=tiny")
def test_default_update_doc(self):
wrapper, f = self._default_update()
self.assertEqual(wrapper.__doc__, 'This is a test')
def test_no_update(self):
def f():
"""This is a test"""
pass
f.attr = 'This is also a test'
def wrapper():
pass
functools.update_wrapper(wrapper, f, (), ())
self.check_wrapper(wrapper, f, (), ())
self.assertEqual(wrapper.__name__, 'wrapper')
self.assertNotEqual(wrapper.__qualname__, f.__qualname__)
self.assertEqual(wrapper.__doc__, None)
self.assertEqual(wrapper.__annotations__, {})
self.assertFalse(hasattr(wrapper, 'attr'))
def test_selective_update(self):
def f():
pass
f.attr = 'This is a different test'
f.dict_attr = dict(a=1, b=2, c=3)
def wrapper():
pass
wrapper.dict_attr = {}
assign = ('attr',)
update = ('dict_attr',)
functools.update_wrapper(wrapper, f, assign, update)
self.check_wrapper(wrapper, f, assign, update)
self.assertEqual(wrapper.__name__, 'wrapper')
self.assertNotEqual(wrapper.__qualname__, f.__qualname__)
self.assertEqual(wrapper.__doc__, None)
self.assertEqual(wrapper.attr, 'This is a different test')
self.assertEqual(wrapper.dict_attr, f.dict_attr)
def test_missing_attributes(self):
def f():
pass
def wrapper():
pass
wrapper.dict_attr = {}
assign = ('attr',)
update = ('dict_attr',)
# Missing attributes on wrapped object are ignored
functools.update_wrapper(wrapper, f, assign, update)
self.assertNotIn('attr', wrapper.__dict__)
self.assertEqual(wrapper.dict_attr, {})
# Wrapper must have expected attributes for updating
del wrapper.dict_attr
with self.assertRaises(AttributeError):
functools.update_wrapper(wrapper, f, assign, update)
wrapper.dict_attr = 1
with self.assertRaises(AttributeError):
functools.update_wrapper(wrapper, f, assign, update)
@support.requires_docstrings
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
@unittest.skipIf(cosmo.MODE .startswith("tiny"),
"No .py files available in Cosmo MODE=tiny")
def test_builtin_update(self):
# Test for bug #1576241
def wrapper():
pass
functools.update_wrapper(wrapper, max)
self.assertEqual(wrapper.__name__, 'max')
self.assertTrue(wrapper.__doc__.startswith('max('))
self.assertEqual(wrapper.__annotations__, {})
class TestWraps(TestUpdateWrapper):
def _default_update(self):
def f():
"""This is a test"""
pass
f.attr = 'This is also a test'
f.__wrapped__ = "This is still a bald faced lie"
@functools.wraps(f)
def wrapper():
pass
return wrapper, f
def test_default_update(self):
wrapper, f = self._default_update()
self.check_wrapper(wrapper, f)
self.assertEqual(wrapper.__name__, 'f')
self.assertEqual(wrapper.__qualname__, f.__qualname__)
self.assertEqual(wrapper.attr, 'This is also a test')
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
@unittest.skipIf(cosmo.MODE .startswith("tiny"),
"No .py files available in Cosmo MODE=tiny")
def test_default_update_doc(self):
wrapper, _ = self._default_update()
self.assertEqual(wrapper.__doc__, 'This is a test')
def test_no_update(self):
def f():
"""This is a test"""
pass
f.attr = 'This is also a test'
@functools.wraps(f, (), ())
def wrapper():
pass
self.check_wrapper(wrapper, f, (), ())
self.assertEqual(wrapper.__name__, 'wrapper')
self.assertNotEqual(wrapper.__qualname__, f.__qualname__)
self.assertEqual(wrapper.__doc__, None)
self.assertFalse(hasattr(wrapper, 'attr'))
def test_selective_update(self):
def f():
pass
f.attr = 'This is a different test'
f.dict_attr = dict(a=1, b=2, c=3)
def add_dict_attr(f):
f.dict_attr = {}
return f
assign = ('attr',)
update = ('dict_attr',)
@functools.wraps(f, assign, update)
@add_dict_attr
def wrapper():
pass
self.check_wrapper(wrapper, f, assign, update)
self.assertEqual(wrapper.__name__, 'wrapper')
self.assertNotEqual(wrapper.__qualname__, f.__qualname__)
self.assertEqual(wrapper.__doc__, None)
self.assertEqual(wrapper.attr, 'This is a different test')
self.assertEqual(wrapper.dict_attr, f.dict_attr)
@unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestReduce(unittest.TestCase):
if c_functools:
func = c_functools.reduce
def test_reduce(self):
class Squares:
def __init__(self, max):
self.max = max
self.sofar = []
def __len__(self):
return len(self.sofar)
def __getitem__(self, i):
if not 0 <= i < self.max: raise IndexError
n = len(self.sofar)
while n <= i:
self.sofar.append(n*n)
n += 1
return self.sofar[i]
def add(x, y):
return x + y
self.assertEqual(self.func(add, ['a', 'b', 'c'], ''), 'abc')
self.assertEqual(
self.func(add, [['a', 'c'], [], ['d', 'w']], []),
['a','c','d','w']
)
self.assertEqual(self.func(lambda x, y: x*y, range(2,8), 1), 5040)
self.assertEqual(
self.func(lambda x, y: x*y, range(2,21), 1),
2432902008176640000
)
self.assertEqual(self.func(add, Squares(10)), 285)
self.assertEqual(self.func(add, Squares(10), 0), 285)
self.assertEqual(self.func(add, Squares(0), 0), 0)
self.assertRaises(TypeError, self.func)
self.assertRaises(TypeError, self.func, 42, 42)
self.assertRaises(TypeError, self.func, 42, 42, 42)
self.assertEqual(self.func(42, "1"), "1") # func is never called with one item
self.assertEqual(self.func(42, "", "1"), "1") # func is never called with one item
self.assertRaises(TypeError, self.func, 42, (42, 42))
self.assertRaises(TypeError, self.func, add, []) # arg 2 must not be empty sequence with no initial value
self.assertRaises(TypeError, self.func, add, "")
self.assertRaises(TypeError, self.func, add, ())
self.assertRaises(TypeError, self.func, add, object())
class TestFailingIter:
def __iter__(self):
raise RuntimeError
self.assertRaises(RuntimeError, self.func, add, TestFailingIter())
self.assertEqual(self.func(add, [], None), None)
self.assertEqual(self.func(add, [], 42), 42)
class BadSeq:
def __getitem__(self, index):
raise ValueError
self.assertRaises(ValueError, self.func, 42, BadSeq())
# Test reduce()'s use of iterators.
def test_iterator_usage(self):
class SequenceClass:
def __init__(self, n):
self.n = n
def __getitem__(self, i):
if 0 <= i < self.n:
return i
else:
raise IndexError
from operator import add
self.assertEqual(self.func(add, SequenceClass(5)), 10)
self.assertEqual(self.func(add, SequenceClass(5), 42), 52)
self.assertRaises(TypeError, self.func, add, SequenceClass(0))
self.assertEqual(self.func(add, SequenceClass(0), 42), 42)
self.assertEqual(self.func(add, SequenceClass(1)), 0)
self.assertEqual(self.func(add, SequenceClass(1), 42), 42)
d = {"one": 1, "two": 2, "three": 3}
self.assertEqual(self.func(add, d), "".join(d.keys()))
class TestCmpToKey:
def test_cmp_to_key(self):
def cmp1(x, y):
return (x > y) - (x < y)
key = self.cmp_to_key(cmp1)
self.assertEqual(key(3), key(3))
self.assertGreater(key(3), key(1))
self.assertGreaterEqual(key(3), key(3))
def cmp2(x, y):
return int(x) - int(y)
key = self.cmp_to_key(cmp2)
self.assertEqual(key(4.0), key('4'))
self.assertLess(key(2), key('35'))
self.assertLessEqual(key(2), key('35'))
self.assertNotEqual(key(2), key('35'))
def test_cmp_to_key_arguments(self):
def cmp1(x, y):
return (x > y) - (x < y)
key = self.cmp_to_key(mycmp=cmp1)
self.assertEqual(key(obj=3), key(obj=3))
self.assertGreater(key(obj=3), key(obj=1))
with self.assertRaises((TypeError, AttributeError)):
key(3) > 1 # rhs is not a K object
with self.assertRaises((TypeError, AttributeError)):
1 < key(3) # lhs is not a K object
with self.assertRaises(TypeError):
key = self.cmp_to_key() # too few args
with self.assertRaises(TypeError):
key = self.cmp_to_key(cmp1, None) # too many args
key = self.cmp_to_key(cmp1)
with self.assertRaises(TypeError):
key() # too few args
with self.assertRaises(TypeError):
key(None, None) # too many args
def test_bad_cmp(self):
def cmp1(x, y):
raise ZeroDivisionError
key = self.cmp_to_key(cmp1)
with self.assertRaises(ZeroDivisionError):
key(3) > key(1)
class BadCmp:
def __lt__(self, other):
raise ZeroDivisionError
def cmp1(x, y):
return BadCmp()
with self.assertRaises(ZeroDivisionError):
key(3) > key(1)
def test_obj_field(self):
def cmp1(x, y):
return (x > y) - (x < y)
key = self.cmp_to_key(mycmp=cmp1)
self.assertEqual(key(50).obj, 50)
def test_sort_int(self):
def mycmp(x, y):
return y - x
self.assertEqual(sorted(range(5), key=self.cmp_to_key(mycmp)),
[4, 3, 2, 1, 0])
def test_sort_int_str(self):
def mycmp(x, y):
x, y = int(x), int(y)
return (x > y) - (x < y)
values = [5, '3', 7, 2, '0', '1', 4, '10', 1]
values = sorted(values, key=self.cmp_to_key(mycmp))
self.assertEqual([int(value) for value in values],
[0, 1, 1, 2, 3, 4, 5, 7, 10])
def test_hash(self):
def mycmp(x, y):
return y - x
key = self.cmp_to_key(mycmp)
k = key(10)
self.assertRaises(TypeError, hash, k)
self.assertNotIsInstance(k, collections.Hashable)
@unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestCmpToKeyC(TestCmpToKey, unittest.TestCase):
if c_functools:
cmp_to_key = c_functools.cmp_to_key
@unittest.skipIf(c_functools, "skip pure-python test if C impl is present")
class TestCmpToKeyPy(TestCmpToKey, unittest.TestCase):
cmp_to_key = staticmethod(py_functools.cmp_to_key)
class TestTotalOrdering(unittest.TestCase):
def test_total_ordering_lt(self):
@functools.total_ordering
class A:
def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value < other.value
def __eq__(self, other):
return self.value == other.value
self.assertTrue(A(1) < A(2))
self.assertTrue(A(2) > A(1))
self.assertTrue(A(1) <= A(2))
self.assertTrue(A(2) >= A(1))
self.assertTrue(A(2) <= A(2))
self.assertTrue(A(2) >= A(2))
self.assertFalse(A(1) > A(2))
def test_total_ordering_le(self):
@functools.total_ordering
class A:
def __init__(self, value):
self.value = value
def __le__(self, other):
return self.value <= other.value
def __eq__(self, other):
return self.value == other.value
self.assertTrue(A(1) < A(2))
self.assertTrue(A(2) > A(1))
self.assertTrue(A(1) <= A(2))
self.assertTrue(A(2) >= A(1))
self.assertTrue(A(2) <= A(2))
self.assertTrue(A(2) >= A(2))
self.assertFalse(A(1) >= A(2))
def test_total_ordering_gt(self):
@functools.total_ordering
class A:
def __init__(self, value):
self.value = value
def __gt__(self, other):
return self.value > other.value
def __eq__(self, other):
return self.value == other.value
self.assertTrue(A(1) < A(2))
self.assertTrue(A(2) > A(1))
self.assertTrue(A(1) <= A(2))
self.assertTrue(A(2) >= A(1))
self.assertTrue(A(2) <= A(2))
self.assertTrue(A(2) >= A(2))
self.assertFalse(A(2) < A(1))
def test_total_ordering_ge(self):
@functools.total_ordering
class A:
def __init__(self, value):
self.value = value
def __ge__(self, other):
return self.value >= other.value
def __eq__(self, other):
return self.value == other.value
self.assertTrue(A(1) < A(2))
self.assertTrue(A(2) > A(1))
self.assertTrue(A(1) <= A(2))
self.assertTrue(A(2) >= A(1))
self.assertTrue(A(2) <= A(2))
self.assertTrue(A(2) >= A(2))
self.assertFalse(A(2) <= A(1))
def test_total_ordering_no_overwrite(self):
# new methods should not overwrite existing
@functools.total_ordering
class A(int):
pass
self.assertTrue(A(1) < A(2))
self.assertTrue(A(2) > A(1))
self.assertTrue(A(1) <= A(2))
self.assertTrue(A(2) >= A(1))
self.assertTrue(A(2) <= A(2))
self.assertTrue(A(2) >= A(2))
def test_no_operations_defined(self):
with self.assertRaises(ValueError):
@functools.total_ordering
class A:
pass
def test_type_error_when_not_implemented(self):
# bug 10042; ensure stack overflow does not occur
# when decorated types return NotImplemented
@functools.total_ordering
class ImplementsLessThan:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, ImplementsLessThan):
return self.value == other.value
return False
def __lt__(self, other):
if isinstance(other, ImplementsLessThan):
return self.value < other.value
return NotImplemented
@functools.total_ordering
class ImplementsGreaterThan:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, ImplementsGreaterThan):
return self.value == other.value
return False
def __gt__(self, other):
if isinstance(other, ImplementsGreaterThan):
return self.value > other.value
return NotImplemented
@functools.total_ordering
class ImplementsLessThanEqualTo:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, ImplementsLessThanEqualTo):
return self.value == other.value
return False
def __le__(self, other):
if isinstance(other, ImplementsLessThanEqualTo):
return self.value <= other.value
return NotImplemented
@functools.total_ordering
class ImplementsGreaterThanEqualTo:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, ImplementsGreaterThanEqualTo):
return self.value == other.value
return False
def __ge__(self, other):
if isinstance(other, ImplementsGreaterThanEqualTo):
return self.value >= other.value
return NotImplemented
@functools.total_ordering
class ComparatorNotImplemented:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, ComparatorNotImplemented):
return self.value == other.value
return False
def __lt__(self, other):
return NotImplemented
with self.subTest("LT < 1"), self.assertRaises(TypeError):
ImplementsLessThan(-1) < 1
with self.subTest("LT < LE"), self.assertRaises(TypeError):
ImplementsLessThan(0) < ImplementsLessThanEqualTo(0)
with self.subTest("LT < GT"), self.assertRaises(TypeError):
ImplementsLessThan(1) < ImplementsGreaterThan(1)
with self.subTest("LE <= LT"), self.assertRaises(TypeError):
ImplementsLessThanEqualTo(2) <= ImplementsLessThan(2)
with self.subTest("LE <= GE"), self.assertRaises(TypeError):
ImplementsLessThanEqualTo(3) <= ImplementsGreaterThanEqualTo(3)
with self.subTest("GT > GE"), self.assertRaises(TypeError):
ImplementsGreaterThan(4) > ImplementsGreaterThanEqualTo(4)
with self.subTest("GT > LT"), self.assertRaises(TypeError):
ImplementsGreaterThan(5) > ImplementsLessThan(5)
with self.subTest("GE >= GT"), self.assertRaises(TypeError):
ImplementsGreaterThanEqualTo(6) >= ImplementsGreaterThan(6)
with self.subTest("GE >= LE"), self.assertRaises(TypeError):
ImplementsGreaterThanEqualTo(7) >= ImplementsLessThanEqualTo(7)
with self.subTest("GE when equal"):
a = ComparatorNotImplemented(8)
b = ComparatorNotImplemented(8)
self.assertEqual(a, b)
with self.assertRaises(TypeError):
a >= b
with self.subTest("LE when equal"):
a = ComparatorNotImplemented(9)
b = ComparatorNotImplemented(9)
self.assertEqual(a, b)
with self.assertRaises(TypeError):
a <= b
def test_pickle(self):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
for name in '__lt__', '__gt__', '__le__', '__ge__':
with self.subTest(method=name, proto=proto):
method = getattr(Orderable_LT, name)
method_copy = pickle.loads(pickle.dumps(method, proto))
self.assertIs(method_copy, method)
@functools.total_ordering
class Orderable_LT:
def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value < other.value
def __eq__(self, other):
return self.value == other.value
class TestLRU:
def test_lru(self):
def orig(x, y):
return 3 * x + y
f = self.module.lru_cache(maxsize=20)(orig)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(maxsize, 20)
self.assertEqual(currsize, 0)
self.assertEqual(hits, 0)
self.assertEqual(misses, 0)
domain = range(5)
for i in range(1000):
x, y = choice(domain), choice(domain)
actual = f(x, y)
expected = orig(x, y)
self.assertEqual(actual, expected)
hits, misses, maxsize, currsize = f.cache_info()
self.assertTrue(hits > misses)
self.assertEqual(hits + misses, 1000)
self.assertEqual(currsize, 20)
f.cache_clear() # test clearing
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(hits, 0)
self.assertEqual(misses, 0)
self.assertEqual(currsize, 0)
f(x, y)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(hits, 0)
self.assertEqual(misses, 1)
self.assertEqual(currsize, 1)
# Test bypassing the cache
self.assertIs(f.__wrapped__, orig)
f.__wrapped__(x, y)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(hits, 0)
self.assertEqual(misses, 1)
self.assertEqual(currsize, 1)
# test size zero (which means "never-cache")
@self.module.lru_cache(0)
def f():
nonlocal f_cnt
f_cnt += 1
return 20
self.assertEqual(f.cache_info().maxsize, 0)
f_cnt = 0
for i in range(5):
self.assertEqual(f(), 20)
self.assertEqual(f_cnt, 5)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(hits, 0)
self.assertEqual(misses, 5)
self.assertEqual(currsize, 0)
# test size one
@self.module.lru_cache(1)
def f():
nonlocal f_cnt
f_cnt += 1
return 20
self.assertEqual(f.cache_info().maxsize, 1)
f_cnt = 0
for i in range(5):
self.assertEqual(f(), 20)
self.assertEqual(f_cnt, 1)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(hits, 4)
self.assertEqual(misses, 1)
self.assertEqual(currsize, 1)
# test size two
@self.module.lru_cache(2)
def f(x):
nonlocal f_cnt
f_cnt += 1
return x*10
self.assertEqual(f.cache_info().maxsize, 2)
f_cnt = 0
for x in 7, 9, 7, 9, 7, 9, 8, 8, 8, 9, 9, 9, 8, 8, 8, 7:
# * * * *
self.assertEqual(f(x), x*10)
self.assertEqual(f_cnt, 4)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(hits, 12)
self.assertEqual(misses, 4)
self.assertEqual(currsize, 2)
def test_lru_reentrancy_with_len(self):
# Test to make sure the LRU cache code isn't thrown-off by
# caching the built-in len() function. Since len() can be
# cached, we shouldn't use it inside the lru code itself.
old_len = builtins.len
try:
builtins.len = self.module.lru_cache(4)(len)
for i in [0, 0, 1, 2, 3, 3, 4, 5, 6, 1, 7, 2, 1]:
self.assertEqual(len('abcdefghijklmn'[:i]), i)
finally:
builtins.len = old_len
def test_lru_type_error(self):
# Regression test for issue #28653.
# lru_cache was leaking when one of the arguments
# wasn't cacheable.
@functools.lru_cache(maxsize=None)
def infinite_cache(o):
pass
@functools.lru_cache(maxsize=10)
def limited_cache(o):
pass
with self.assertRaises(TypeError):
infinite_cache([])
with self.assertRaises(TypeError):
limited_cache([])
def test_lru_with_maxsize_none(self):
@self.module.lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
self.assertEqual([fib(n) for n in range(16)],
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610])
self.assertEqual(fib.cache_info(),
self.module._CacheInfo(hits=28, misses=16, maxsize=None, currsize=16))
fib.cache_clear()
self.assertEqual(fib.cache_info(),
self.module._CacheInfo(hits=0, misses=0, maxsize=None, currsize=0))
def test_lru_with_maxsize_negative(self):
@self.module.lru_cache(maxsize=-10)
def eq(n):
return n
for i in (0, 1):
self.assertEqual([eq(n) for n in range(150)], list(range(150)))
self.assertEqual(eq.cache_info(),
self.module._CacheInfo(hits=0, misses=300, maxsize=-10, currsize=1))
def test_lru_with_exceptions(self):
# Verify that user_function exceptions get passed through without
# creating a hard-to-read chained exception.
# http://bugs.python.org/issue13177
for maxsize in (None, 128):
@self.module.lru_cache(maxsize)
def func(i):
return 'abc'[i]
self.assertEqual(func(0), 'a')
with self.assertRaises(IndexError) as cm:
func(15)
self.assertIsNone(cm.exception.__context__)
# Verify that the previous exception did not result in a cached entry
with self.assertRaises(IndexError):
func(15)
def test_lru_with_types(self):
for maxsize in (None, 128):
@self.module.lru_cache(maxsize=maxsize, typed=True)
def square(x):
return x * x
self.assertEqual(square(3), 9)
self.assertEqual(type(square(3)), type(9))
self.assertEqual(square(3.0), 9.0)
self.assertEqual(type(square(3.0)), type(9.0))
self.assertEqual(square(x=3), 9)
self.assertEqual(type(square(x=3)), type(9))
self.assertEqual(square(x=3.0), 9.0)
self.assertEqual(type(square(x=3.0)), type(9.0))
self.assertEqual(square.cache_info().hits, 4)
self.assertEqual(square.cache_info().misses, 4)
def test_lru_with_keyword_args(self):
@self.module.lru_cache()
def fib(n):
if n < 2:
return n
return fib(n=n-1) + fib(n=n-2)
self.assertEqual(
[fib(n=number) for number in range(16)],
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
)
self.assertEqual(fib.cache_info(),
self.module._CacheInfo(hits=28, misses=16, maxsize=128, currsize=16))
fib.cache_clear()
self.assertEqual(fib.cache_info(),
self.module._CacheInfo(hits=0, misses=0, maxsize=128, currsize=0))
def test_lru_with_keyword_args_maxsize_none(self):
@self.module.lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n=n-1) + fib(n=n-2)
self.assertEqual([fib(n=number) for number in range(16)],
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610])
self.assertEqual(fib.cache_info(),
self.module._CacheInfo(hits=28, misses=16, maxsize=None, currsize=16))
fib.cache_clear()
self.assertEqual(fib.cache_info(),
self.module._CacheInfo(hits=0, misses=0, maxsize=None, currsize=0))
def test_kwargs_order(self):
# PEP 468: Preserving Keyword Argument Order
@self.module.lru_cache(maxsize=10)
def f(**kwargs):
return list(kwargs.items())
self.assertEqual(f(a=1, b=2), [('a', 1), ('b', 2)])
self.assertEqual(f(b=2, a=1), [('b', 2), ('a', 1)])
self.assertEqual(f.cache_info(),
self.module._CacheInfo(hits=0, misses=2, maxsize=10, currsize=2))
def test_lru_cache_decoration(self):
def f(zomg: 'zomg_annotation'):
"""f doc string"""
return 42
g = self.module.lru_cache()(f)
for attr in self.module.WRAPPER_ASSIGNMENTS:
self.assertEqual(getattr(g, attr), getattr(f, attr))
@unittest.skipUnless(threading, 'This test requires threading.')
def test_lru_cache_threaded(self):
n, m = 5, 11
def orig(x, y):
return 3 * x + y
f = self.module.lru_cache(maxsize=n*m)(orig)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(currsize, 0)
start = threading.Event()
def full(k):
start.wait(10)
for _ in range(m):
self.assertEqual(f(k, 0), orig(k, 0))
def clear():
start.wait(10)
for _ in range(2*m):
f.cache_clear()
orig_si = sys.getswitchinterval()
support.setswitchinterval(1e-6)
try:
# create n threads in order to fill cache
threads = [threading.Thread(target=full, args=[k])
for k in range(n)]
with support.start_threads(threads):
start.set()
hits, misses, maxsize, currsize = f.cache_info()
if self.module is py_functools:
# XXX: Why can be not equal?
self.assertLessEqual(misses, n)
self.assertLessEqual(hits, m*n - misses)
else:
self.assertEqual(misses, n)
self.assertEqual(hits, m*n - misses)
self.assertEqual(currsize, n)
# create n threads in order to fill cache and 1 to clear it
threads = [threading.Thread(target=clear)]
threads += [threading.Thread(target=full, args=[k])
for k in range(n)]
start.clear()
with support.start_threads(threads):
start.set()
finally:
sys.setswitchinterval(orig_si)
@unittest.skipUnless(threading, 'This test requires threading.')
def test_lru_cache_threaded2(self):
# Simultaneous call with the same arguments
n, m = 5, 7
start = threading.Barrier(n+1)
pause = threading.Barrier(n+1)
stop = threading.Barrier(n+1)
@self.module.lru_cache(maxsize=m*n)
def f(x):
pause.wait(10)
return 3 * x
self.assertEqual(f.cache_info(), (0, 0, m*n, 0))
def test():
for i in range(m):
start.wait(10)
self.assertEqual(f(i), 3 * i)
stop.wait(10)
threads = [threading.Thread(target=test) for k in range(n)]
with support.start_threads(threads):
for i in range(m):
start.wait(10)
stop.reset()
pause.wait(10)
start.reset()
stop.wait(10)
pause.reset()
self.assertEqual(f.cache_info(), (0, (i+1)*n, m*n, i+1))
@unittest.skipUnless(threading, 'This test requires threading.')
def test_lru_cache_threaded3(self):
@self.module.lru_cache(maxsize=2)
def f(x):
time.sleep(.01)
return 3 * x
def test(i, x):
with self.subTest(thread=i):
self.assertEqual(f(x), 3 * x, i)
threads = [threading.Thread(target=test, args=(i, v))
for i, v in enumerate([1, 2, 2, 3, 2])]
with support.start_threads(threads):
pass
def test_need_for_rlock(self):
# This will deadlock on an LRU cache that uses a regular lock
@self.module.lru_cache(maxsize=10)
def test_func(x):
'Used to demonstrate a reentrant lru_cache call within a single thread'
return x
class DoubleEq:
'Demonstrate a reentrant lru_cache call within a single thread'
def __init__(self, x):
self.x = x
def __hash__(self):
return self.x
def __eq__(self, other):
if self.x == 2:
test_func(DoubleEq(1))
return self.x == other.x
test_func(DoubleEq(1)) # Load the cache
test_func(DoubleEq(2)) # Load the cache
self.assertEqual(test_func(DoubleEq(2)), # Trigger a re-entrant __eq__ call
DoubleEq(2)) # Verify the correct return value
def test_early_detection_of_bad_call(self):
# Issue #22184
with self.assertRaises(TypeError):
@functools.lru_cache
def f():
pass
def test_lru_method(self):
class X(int):
f_cnt = 0
@self.module.lru_cache(2)
def f(self, x):
self.f_cnt += 1
return x*10+self
a = X(5)
b = X(5)
c = X(7)
self.assertEqual(X.f.cache_info(), (0, 0, 2, 0))
for x in 1, 2, 2, 3, 1, 1, 1, 2, 3, 3:
self.assertEqual(a.f(x), x*10 + 5)
self.assertEqual((a.f_cnt, b.f_cnt, c.f_cnt), (6, 0, 0))
self.assertEqual(X.f.cache_info(), (4, 6, 2, 2))
for x in 1, 2, 1, 1, 1, 1, 3, 2, 2, 2:
self.assertEqual(b.f(x), x*10 + 5)
self.assertEqual((a.f_cnt, b.f_cnt, c.f_cnt), (6, 4, 0))
self.assertEqual(X.f.cache_info(), (10, 10, 2, 2))
for x in 2, 1, 1, 1, 1, 2, 1, 3, 2, 1:
self.assertEqual(c.f(x), x*10 + 7)
self.assertEqual((a.f_cnt, b.f_cnt, c.f_cnt), (6, 4, 5))
self.assertEqual(X.f.cache_info(), (15, 15, 2, 2))
self.assertEqual(a.f.cache_info(), X.f.cache_info())
self.assertEqual(b.f.cache_info(), X.f.cache_info())
self.assertEqual(c.f.cache_info(), X.f.cache_info())
def test_pickle(self):
cls = self.__class__
for f in cls.cached_func[0], cls.cached_meth, cls.cached_staticmeth:
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
with self.subTest(proto=proto, func=f):
f_copy = pickle.loads(pickle.dumps(f, proto))
self.assertIs(f_copy, f)
def test_copy(self):
cls = self.__class__
def orig(x, y):
return 3 * x + y
part = self.module.partial(orig, 2)
funcs = (cls.cached_func[0], cls.cached_meth, cls.cached_staticmeth,
self.module.lru_cache(2)(part))
for f in funcs:
with self.subTest(func=f):
f_copy = copy.copy(f)
self.assertIs(f_copy, f)
def test_deepcopy(self):
cls = self.__class__
def orig(x, y):
return 3 * x + y
part = self.module.partial(orig, 2)
funcs = (cls.cached_func[0], cls.cached_meth, cls.cached_staticmeth,
self.module.lru_cache(2)(part))
for f in funcs:
with self.subTest(func=f):
f_copy = copy.deepcopy(f)
self.assertIs(f_copy, f)
@py_functools.lru_cache()
def py_cached_func(x, y):
return 3 * x + y
@c_functools.lru_cache()
def c_cached_func(x, y):
return 3 * x + y
@unittest.skipIf(c_functools, "skip pure-python test if C impl is present")
class TestLRUPy(TestLRU, unittest.TestCase):
module = py_functools
cached_func = py_cached_func,
@module.lru_cache()
def cached_meth(self, x, y):
return 3 * x + y
@staticmethod
@module.lru_cache()
def cached_staticmeth(x, y):
return 3 * x + y
class TestLRUC(TestLRU, unittest.TestCase):
module = c_functools
cached_func = c_cached_func,
@module.lru_cache()
def cached_meth(self, x, y):
return 3 * x + y
@staticmethod
@module.lru_cache()
def cached_staticmeth(x, y):
return 3 * x + y
class TestSingleDispatch(unittest.TestCase):
def test_simple_overloads(self):
@functools.singledispatch
def g(obj):
return "base"
def g_int(i):
return "integer"
g.register(int, g_int)
self.assertEqual(g("str"), "base")
self.assertEqual(g(1), "integer")
self.assertEqual(g([1,2,3]), "base")
def test_mro(self):
@functools.singledispatch
def g(obj):
return "base"
class A:
pass
class C(A):
pass
class B(A):
pass
class D(C, B):
pass
def g_A(a):
return "A"
def g_B(b):
return "B"
g.register(A, g_A)
g.register(B, g_B)
self.assertEqual(g(A()), "A")
self.assertEqual(g(B()), "B")
self.assertEqual(g(C()), "A")
self.assertEqual(g(D()), "B")
def test_register_decorator(self):
@functools.singledispatch
def g(obj):
return "base"
@g.register(int)
def g_int(i):
return "int %s" % (i,)
self.assertEqual(g(""), "base")
self.assertEqual(g(12), "int 12")
self.assertIs(g.dispatch(int), g_int)
self.assertIs(g.dispatch(object), g.dispatch(str))
# Note: in the assert above this is not g.
# @singledispatch returns the wrapper.
@unittest.skipIf(cosmo.MODE in ('tiny', 'rel'),
"no pydocs in rel mode")
def test_wrapping_attributes(self):
@functools.singledispatch
def g(obj):
"Simple test"
return "Test"
self.assertEqual(g.__name__, "g")
if sys.flags.optimize < 2:
self.assertEqual(g.__doc__, "Simple test")
@unittest.skipUnless(decimal, 'requires _decimal')
@support.cpython_only
def test_c_classes(self):
@functools.singledispatch
def g(obj):
return "base"
@g.register(decimal.DecimalException)
def _(obj):
return obj.args
subn = decimal.Subnormal("Exponent < Emin")
rnd = decimal.Rounded("Number got rounded")
self.assertEqual(g(subn), ("Exponent < Emin",))
self.assertEqual(g(rnd), ("Number got rounded",))
@g.register(decimal.Subnormal)
def _(obj):
return "Too small to care."
self.assertEqual(g(subn), "Too small to care.")
self.assertEqual(g(rnd), ("Number got rounded",))
def test_compose_mro(self):
# None of the examples in this test depend on haystack ordering.
c = collections
mro = functools._compose_mro
bases = [c.Sequence, c.MutableMapping, c.Mapping, c.Set]
for haystack in permutations(bases):
m = mro(dict, haystack)
self.assertEqual(m, [dict, c.MutableMapping, c.Mapping,
c.Collection, c.Sized, c.Iterable,
c.Container, object])
bases = [c.Container, c.Mapping, c.MutableMapping, c.OrderedDict]
for haystack in permutations(bases):
m = mro(c.ChainMap, haystack)
self.assertEqual(m, [c.ChainMap, c.MutableMapping, c.Mapping,
c.Collection, c.Sized, c.Iterable,
c.Container, object])
# If there's a generic function with implementations registered for
# both Sized and Container, passing a defaultdict to it results in an
# ambiguous dispatch which will cause a RuntimeError (see
# test_mro_conflicts).
bases = [c.Container, c.Sized, str]
for haystack in permutations(bases):
m = mro(c.defaultdict, [c.Sized, c.Container, str])
self.assertEqual(m, [c.defaultdict, dict, c.Sized, c.Container,
object])
# MutableSequence below is registered directly on D. In other words, it
# precedes MutableMapping which means single dispatch will always
# choose MutableSequence here.
class D(c.defaultdict):
pass
c.MutableSequence.register(D)
bases = [c.MutableSequence, c.MutableMapping]
for haystack in permutations(bases):
m = mro(D, bases)
self.assertEqual(m, [D, c.MutableSequence, c.Sequence, c.Reversible,
c.defaultdict, dict, c.MutableMapping, c.Mapping,
c.Collection, c.Sized, c.Iterable, c.Container,
object])
# Container and Callable are registered on different base classes and
# a generic function supporting both should always pick the Callable
# implementation if a C instance is passed.
class C(c.defaultdict):
def __call__(self):
pass
bases = [c.Sized, c.Callable, c.Container, c.Mapping]
for haystack in permutations(bases):
m = mro(C, haystack)
self.assertEqual(m, [C, c.Callable, c.defaultdict, dict, c.Mapping,
c.Collection, c.Sized, c.Iterable,
c.Container, object])
def test_register_abc(self):
c = collections
d = {"a": "b"}
l = [1, 2, 3]
s = {object(), None}
f = frozenset(s)
t = (1, 2, 3)
@functools.singledispatch
def g(obj):
return "base"
self.assertEqual(g(d), "base")
self.assertEqual(g(l), "base")
self.assertEqual(g(s), "base")
self.assertEqual(g(f), "base")
self.assertEqual(g(t), "base")
g.register(c.Sized, lambda obj: "sized")
self.assertEqual(g(d), "sized")
self.assertEqual(g(l), "sized")
self.assertEqual(g(s), "sized")
self.assertEqual(g(f), "sized")
self.assertEqual(g(t), "sized")
g.register(c.MutableMapping, lambda obj: "mutablemapping")
self.assertEqual(g(d), "mutablemapping")
self.assertEqual(g(l), "sized")
self.assertEqual(g(s), "sized")
self.assertEqual(g(f), "sized")
self.assertEqual(g(t), "sized")
g.register(c.ChainMap, lambda obj: "chainmap")
self.assertEqual(g(d), "mutablemapping") # irrelevant ABCs registered
self.assertEqual(g(l), "sized")
self.assertEqual(g(s), "sized")
self.assertEqual(g(f), "sized")
self.assertEqual(g(t), "sized")
g.register(c.MutableSequence, lambda obj: "mutablesequence")
self.assertEqual(g(d), "mutablemapping")
self.assertEqual(g(l), "mutablesequence")
self.assertEqual(g(s), "sized")
self.assertEqual(g(f), "sized")
self.assertEqual(g(t), "sized")
g.register(c.MutableSet, lambda obj: "mutableset")
self.assertEqual(g(d), "mutablemapping")
self.assertEqual(g(l), "mutablesequence")
self.assertEqual(g(s), "mutableset")
self.assertEqual(g(f), "sized")
self.assertEqual(g(t), "sized")
g.register(c.Mapping, lambda obj: "mapping")
self.assertEqual(g(d), "mutablemapping") # not specific enough
self.assertEqual(g(l), "mutablesequence")
self.assertEqual(g(s), "mutableset")
self.assertEqual(g(f), "sized")
self.assertEqual(g(t), "sized")
g.register(c.Sequence, lambda obj: "sequence")
self.assertEqual(g(d), "mutablemapping")
self.assertEqual(g(l), "mutablesequence")
self.assertEqual(g(s), "mutableset")
self.assertEqual(g(f), "sized")
self.assertEqual(g(t), "sequence")
g.register(c.Set, lambda obj: "set")
self.assertEqual(g(d), "mutablemapping")
self.assertEqual(g(l), "mutablesequence")
self.assertEqual(g(s), "mutableset")
self.assertEqual(g(f), "set")
self.assertEqual(g(t), "sequence")
g.register(dict, lambda obj: "dict")
self.assertEqual(g(d), "dict")
self.assertEqual(g(l), "mutablesequence")
self.assertEqual(g(s), "mutableset")
self.assertEqual(g(f), "set")
self.assertEqual(g(t), "sequence")
g.register(list, lambda obj: "list")
self.assertEqual(g(d), "dict")
self.assertEqual(g(l), "list")
self.assertEqual(g(s), "mutableset")
self.assertEqual(g(f), "set")
self.assertEqual(g(t), "sequence")
g.register(set, lambda obj: "concrete-set")
self.assertEqual(g(d), "dict")
self.assertEqual(g(l), "list")
self.assertEqual(g(s), "concrete-set")
self.assertEqual(g(f), "set")
self.assertEqual(g(t), "sequence")
g.register(frozenset, lambda obj: "frozen-set")
self.assertEqual(g(d), "dict")
self.assertEqual(g(l), "list")
self.assertEqual(g(s), "concrete-set")
self.assertEqual(g(f), "frozen-set")
self.assertEqual(g(t), "sequence")
g.register(tuple, lambda obj: "tuple")
self.assertEqual(g(d), "dict")
self.assertEqual(g(l), "list")
self.assertEqual(g(s), "concrete-set")
self.assertEqual(g(f), "frozen-set")
self.assertEqual(g(t), "tuple")
def test_c3_abc(self):
c = collections
mro = functools._c3_mro
class A(object):
pass
class B(A):
def __len__(self):
return 0 # implies Sized
@c.Container.register
class C(object):
pass
class D(object):
pass # unrelated
class X(D, C, B):
def __call__(self):
pass # implies Callable
expected = [X, c.Callable, D, C, c.Container, B, c.Sized, A, object]
for abcs in permutations([c.Sized, c.Callable, c.Container]):
self.assertEqual(mro(X, abcs=abcs), expected)
# unrelated ABCs don't appear in the resulting MRO
many_abcs = [c.Mapping, c.Sized, c.Callable, c.Container, c.Iterable]
self.assertEqual(mro(X, abcs=many_abcs), expected)
def test_false_meta(self):
# see issue23572
class MetaA(type):
def __len__(self):
return 0
class A(metaclass=MetaA):
pass
class AA(A):
pass
@functools.singledispatch
def fun(a):
return 'base A'
@fun.register(A)
def _(a):
return 'fun A'
aa = AA()
self.assertEqual(fun(aa), 'fun A')
def test_mro_conflicts(self):
c = collections
@functools.singledispatch
def g(arg):
return "base"
class O(c.Sized):
def __len__(self):
return 0
o = O()
self.assertEqual(g(o), "base")
g.register(c.Iterable, lambda arg: "iterable")
g.register(c.Container, lambda arg: "container")
g.register(c.Sized, lambda arg: "sized")
g.register(c.Set, lambda arg: "set")
self.assertEqual(g(o), "sized")
c.Iterable.register(O)
self.assertEqual(g(o), "sized") # because it's explicitly in __mro__
c.Container.register(O)
self.assertEqual(g(o), "sized") # see above: Sized is in __mro__
c.Set.register(O)
self.assertEqual(g(o), "set") # because c.Set is a subclass of
# c.Sized and c.Container
class P:
pass
p = P()
self.assertEqual(g(p), "base")
c.Iterable.register(P)
self.assertEqual(g(p), "iterable")
c.Container.register(P)
with self.assertRaises(RuntimeError) as re_one:
g(p)
self.assertIn(
str(re_one.exception),
(("Ambiguous dispatch: <class 'collections.abc.Container'> "
"or <class 'collections.abc.Iterable'>"),
("Ambiguous dispatch: <class 'collections.abc.Iterable'> "
"or <class 'collections.abc.Container'>")),
)
class Q(c.Sized):
def __len__(self):
return 0
q = Q()
self.assertEqual(g(q), "sized")
c.Iterable.register(Q)
self.assertEqual(g(q), "sized") # because it's explicitly in __mro__
c.Set.register(Q)
self.assertEqual(g(q), "set") # because c.Set is a subclass of
# c.Sized and c.Iterable
@functools.singledispatch
def h(arg):
return "base"
@h.register(c.Sized)
def _(arg):
return "sized"
@h.register(c.Container)
def _(arg):
return "container"
# Even though Sized and Container are explicit bases of MutableMapping,
# this ABC is implicitly registered on defaultdict which makes all of
# MutableMapping's bases implicit as well from defaultdict's
# perspective.
with self.assertRaises(RuntimeError) as re_two:
h(c.defaultdict(lambda: 0))
self.assertIn(
str(re_two.exception),
(("Ambiguous dispatch: <class 'collections.abc.Container'> "
"or <class 'collections.abc.Sized'>"),
("Ambiguous dispatch: <class 'collections.abc.Sized'> "
"or <class 'collections.abc.Container'>")),
)
class R(c.defaultdict):
pass
c.MutableSequence.register(R)
@functools.singledispatch
def i(arg):
return "base"
@i.register(c.MutableMapping)
def _(arg):
return "mapping"
@i.register(c.MutableSequence)
def _(arg):
return "sequence"
r = R()
self.assertEqual(i(r), "sequence")
class S:
pass
class T(S, c.Sized):
def __len__(self):
return 0
t = T()
self.assertEqual(h(t), "sized")
c.Container.register(T)
self.assertEqual(h(t), "sized") # because it's explicitly in the MRO
class U:
def __len__(self):
return 0
u = U()
self.assertEqual(h(u), "sized") # implicit Sized subclass inferred
# from the existence of __len__()
c.Container.register(U)
# There is no preference for registered versus inferred ABCs.
with self.assertRaises(RuntimeError) as re_three:
h(u)
self.assertIn(
str(re_three.exception),
(("Ambiguous dispatch: <class 'collections.abc.Container'> "
"or <class 'collections.abc.Sized'>"),
("Ambiguous dispatch: <class 'collections.abc.Sized'> "
"or <class 'collections.abc.Container'>")),
)
class V(c.Sized, S):
def __len__(self):
return 0
@functools.singledispatch
def j(arg):
return "base"
@j.register(S)
def _(arg):
return "s"
@j.register(c.Container)
def _(arg):
return "container"
v = V()
self.assertEqual(j(v), "s")
c.Container.register(V)
self.assertEqual(j(v), "container") # because it ends up right after
# Sized in the MRO
def test_cache_invalidation(self):
from collections import UserDict
class TracingDict(UserDict):
def __init__(self, *args, **kwargs):
super(TracingDict, self).__init__(*args, **kwargs)
self.set_ops = []
self.get_ops = []
def __getitem__(self, key):
result = self.data[key]
self.get_ops.append(key)
return result
def __setitem__(self, key, value):
self.set_ops.append(key)
self.data[key] = value
def clear(self):
self.data.clear()
_orig_wkd = functools.WeakKeyDictionary
td = TracingDict()
functools.WeakKeyDictionary = lambda: td
c = collections
@functools.singledispatch
def g(arg):
return "base"
d = {}
l = []
self.assertEqual(len(td), 0)
self.assertEqual(g(d), "base")
self.assertEqual(len(td), 1)
self.assertEqual(td.get_ops, [])
self.assertEqual(td.set_ops, [dict])
self.assertEqual(td.data[dict], g.registry[object])
self.assertEqual(g(l), "base")
self.assertEqual(len(td), 2)
self.assertEqual(td.get_ops, [])
self.assertEqual(td.set_ops, [dict, list])
self.assertEqual(td.data[dict], g.registry[object])
self.assertEqual(td.data[list], g.registry[object])
self.assertEqual(td.data[dict], td.data[list])
self.assertEqual(g(l), "base")
self.assertEqual(g(d), "base")
self.assertEqual(td.get_ops, [list, dict])
self.assertEqual(td.set_ops, [dict, list])
g.register(list, lambda arg: "list")
self.assertEqual(td.get_ops, [list, dict])
self.assertEqual(len(td), 0)
self.assertEqual(g(d), "base")
self.assertEqual(len(td), 1)
self.assertEqual(td.get_ops, [list, dict])
self.assertEqual(td.set_ops, [dict, list, dict])
self.assertEqual(td.data[dict],
functools._find_impl(dict, g.registry))
self.assertEqual(g(l), "list")
self.assertEqual(len(td), 2)
self.assertEqual(td.get_ops, [list, dict])
self.assertEqual(td.set_ops, [dict, list, dict, list])
self.assertEqual(td.data[list],
functools._find_impl(list, g.registry))
class X:
pass
c.MutableMapping.register(X) # Will not invalidate the cache,
# not using ABCs yet.
self.assertEqual(g(d), "base")
self.assertEqual(g(l), "list")
self.assertEqual(td.get_ops, [list, dict, dict, list])
self.assertEqual(td.set_ops, [dict, list, dict, list])
g.register(c.Sized, lambda arg: "sized")
self.assertEqual(len(td), 0)
self.assertEqual(g(d), "sized")
self.assertEqual(len(td), 1)
self.assertEqual(td.get_ops, [list, dict, dict, list])
self.assertEqual(td.set_ops, [dict, list, dict, list, dict])
self.assertEqual(g(l), "list")
self.assertEqual(len(td), 2)
self.assertEqual(td.get_ops, [list, dict, dict, list])
self.assertEqual(td.set_ops, [dict, list, dict, list, dict, list])
self.assertEqual(g(l), "list")
self.assertEqual(g(d), "sized")
self.assertEqual(td.get_ops, [list, dict, dict, list, list, dict])
self.assertEqual(td.set_ops, [dict, list, dict, list, dict, list])
g.dispatch(list)
g.dispatch(dict)
self.assertEqual(td.get_ops, [list, dict, dict, list, list, dict,
list, dict])
self.assertEqual(td.set_ops, [dict, list, dict, list, dict, list])
c.MutableSet.register(X) # Will invalidate the cache.
self.assertEqual(len(td), 2) # Stale cache.
self.assertEqual(g(l), "list")
self.assertEqual(len(td), 1)
g.register(c.MutableMapping, lambda arg: "mutablemapping")
self.assertEqual(len(td), 0)
self.assertEqual(g(d), "mutablemapping")
self.assertEqual(len(td), 1)
self.assertEqual(g(l), "list")
self.assertEqual(len(td), 2)
g.register(dict, lambda arg: "dict")
self.assertEqual(g(d), "dict")
self.assertEqual(g(l), "list")
g._clear_cache()
self.assertEqual(len(td), 0)
functools.WeakKeyDictionary = _orig_wkd
def test_invalid_positional_argument(self):
@functools.singledispatch
def f(*args):
pass
msg = 'f requires at least 1 positional argument'
with self.assertRaisesRegex(TypeError, msg):
f()
if __name__ == '__main__':
unittest.main()
| 79,033 | 2,106 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_difflib.py | import difflib
from test.support import run_unittest, findfile
import unittest
import doctest
import sys
class TestWithAscii(unittest.TestCase):
def test_one_insert(self):
sm = difflib.SequenceMatcher(None, 'b' * 100, 'a' + 'b' * 100)
self.assertAlmostEqual(sm.ratio(), 0.995, places=3)
self.assertEqual(list(sm.get_opcodes()),
[ ('insert', 0, 0, 0, 1),
('equal', 0, 100, 1, 101)])
self.assertEqual(sm.bpopular, set())
sm = difflib.SequenceMatcher(None, 'b' * 100, 'b' * 50 + 'a' + 'b' * 50)
self.assertAlmostEqual(sm.ratio(), 0.995, places=3)
self.assertEqual(list(sm.get_opcodes()),
[ ('equal', 0, 50, 0, 50),
('insert', 50, 50, 50, 51),
('equal', 50, 100, 51, 101)])
self.assertEqual(sm.bpopular, set())
def test_one_delete(self):
sm = difflib.SequenceMatcher(None, 'a' * 40 + 'c' + 'b' * 40, 'a' * 40 + 'b' * 40)
self.assertAlmostEqual(sm.ratio(), 0.994, places=3)
self.assertEqual(list(sm.get_opcodes()),
[ ('equal', 0, 40, 0, 40),
('delete', 40, 41, 40, 40),
('equal', 41, 81, 40, 80)])
def test_bjunk(self):
sm = difflib.SequenceMatcher(isjunk=lambda x: x == ' ',
a='a' * 40 + 'b' * 40, b='a' * 44 + 'b' * 40)
self.assertEqual(sm.bjunk, set())
sm = difflib.SequenceMatcher(isjunk=lambda x: x == ' ',
a='a' * 40 + 'b' * 40, b='a' * 44 + 'b' * 40 + ' ' * 20)
self.assertEqual(sm.bjunk, {' '})
sm = difflib.SequenceMatcher(isjunk=lambda x: x in [' ', 'b'],
a='a' * 40 + 'b' * 40, b='a' * 44 + 'b' * 40 + ' ' * 20)
self.assertEqual(sm.bjunk, {' ', 'b'})
class TestAutojunk(unittest.TestCase):
"""Tests for the autojunk parameter added in 2.7"""
def test_one_insert_homogenous_sequence(self):
# By default autojunk=True and the heuristic kicks in for a sequence
# of length 200+
seq1 = 'b' * 200
seq2 = 'a' + 'b' * 200
sm = difflib.SequenceMatcher(None, seq1, seq2)
self.assertAlmostEqual(sm.ratio(), 0, places=3)
self.assertEqual(sm.bpopular, {'b'})
# Now turn the heuristic off
sm = difflib.SequenceMatcher(None, seq1, seq2, autojunk=False)
self.assertAlmostEqual(sm.ratio(), 0.9975, places=3)
self.assertEqual(sm.bpopular, set())
class TestSFbugs(unittest.TestCase):
def test_ratio_for_null_seqn(self):
# Check clearing of SF bug 763023
s = difflib.SequenceMatcher(None, [], [])
self.assertEqual(s.ratio(), 1)
self.assertEqual(s.quick_ratio(), 1)
self.assertEqual(s.real_quick_ratio(), 1)
def test_comparing_empty_lists(self):
# Check fix for bug #979794
group_gen = difflib.SequenceMatcher(None, [], []).get_grouped_opcodes()
self.assertRaises(StopIteration, next, group_gen)
diff_gen = difflib.unified_diff([], [])
self.assertRaises(StopIteration, next, diff_gen)
def test_matching_blocks_cache(self):
# Issue #21635
s = difflib.SequenceMatcher(None, "abxcd", "abcd")
first = s.get_matching_blocks()
second = s.get_matching_blocks()
self.assertEqual(second[0].size, 2)
self.assertEqual(second[1].size, 2)
self.assertEqual(second[2].size, 0)
def test_added_tab_hint(self):
# Check fix for bug #1488943
diff = list(difflib.Differ().compare(["\tI am a buggy"],["\t\tI am a bug"]))
self.assertEqual("- \tI am a buggy", diff[0])
self.assertEqual("? --\n", diff[1])
self.assertEqual("+ \t\tI am a bug", diff[2])
self.assertEqual("? +\n", diff[3])
def test_mdiff_catch_stop_iteration(self):
# Issue #33224
self.assertEqual(
list(difflib._mdiff(["2"], ["3"], 1)),
[((1, '\x00-2\x01'), (1, '\x00+3\x01'), True)],
)
patch914575_from1 = """
1. Beautiful is beTTer than ugly.
2. Explicit is better than implicit.
3. Simple is better than complex.
4. Complex is better than complicated.
"""
patch914575_to1 = """
1. Beautiful is better than ugly.
3. Simple is better than complex.
4. Complicated is better than complex.
5. Flat is better than nested.
"""
patch914575_nonascii_from1 = """
1. Beautiful is beTTer than ugly.
2. Explicit is better than ımplıcıt.
3. Simple is better than complex.
4. Complex is better than complicated.
"""
patch914575_nonascii_to1 = """
1. Beautiful is better than ügly.
3. Sımple is better than complex.
4. Complicated is better than cömplex.
5. Flat is better than nested.
"""
patch914575_from2 = """
\t\tLine 1: preceded by from:[tt] to:[ssss]
\t\tLine 2: preceded by from:[sstt] to:[sssst]
\t \tLine 3: preceded by from:[sstst] to:[ssssss]
Line 4: \thas from:[sst] to:[sss] after :
Line 5: has from:[t] to:[ss] at end\t
"""
patch914575_to2 = """
Line 1: preceded by from:[tt] to:[ssss]
\tLine 2: preceded by from:[sstt] to:[sssst]
Line 3: preceded by from:[sstst] to:[ssssss]
Line 4: has from:[sst] to:[sss] after :
Line 5: has from:[t] to:[ss] at end
"""
patch914575_from3 = """line 0
1234567890123456789012345689012345
line 1
line 2
line 3
line 4 changed
line 5 changed
line 6 changed
line 7
line 8 subtracted
line 9
1234567890123456789012345689012345
short line
just fits in!!
just fits in two lines yup!!
the end"""
patch914575_to3 = """line 0
1234567890123456789012345689012345
line 1
line 2 added
line 3
line 4 chanGEd
line 5a chanGed
line 6a changEd
line 7
line 8
line 9
1234567890
another long line that needs to be wrapped
just fitS in!!
just fits in two lineS yup!!
the end"""
class TestSFpatches(unittest.TestCase):
def test_html_diff(self):
# Check SF patch 914575 for generating HTML differences
f1a = ((patch914575_from1 + '123\n'*10)*3)
t1a = (patch914575_to1 + '123\n'*10)*3
f1b = '456\n'*10 + f1a
t1b = '456\n'*10 + t1a
f1a = f1a.splitlines()
t1a = t1a.splitlines()
f1b = f1b.splitlines()
t1b = t1b.splitlines()
f2 = patch914575_from2.splitlines()
t2 = patch914575_to2.splitlines()
f3 = patch914575_from3
t3 = patch914575_to3
i = difflib.HtmlDiff()
j = difflib.HtmlDiff(tabsize=2)
k = difflib.HtmlDiff(wrapcolumn=14)
full = i.make_file(f1a,t1a,'from','to',context=False,numlines=5)
tables = '\n'.join(
[
'<h2>Context (first diff within numlines=5(default))</h2>',
i.make_table(f1a,t1a,'from','to',context=True),
'<h2>Context (first diff after numlines=5(default))</h2>',
i.make_table(f1b,t1b,'from','to',context=True),
'<h2>Context (numlines=6)</h2>',
i.make_table(f1a,t1a,'from','to',context=True,numlines=6),
'<h2>Context (numlines=0)</h2>',
i.make_table(f1a,t1a,'from','to',context=True,numlines=0),
'<h2>Same Context</h2>',
i.make_table(f1a,f1a,'from','to',context=True),
'<h2>Same Full</h2>',
i.make_table(f1a,f1a,'from','to',context=False),
'<h2>Empty Context</h2>',
i.make_table([],[],'from','to',context=True),
'<h2>Empty Full</h2>',
i.make_table([],[],'from','to',context=False),
'<h2>tabsize=2</h2>',
j.make_table(f2,t2),
'<h2>tabsize=default</h2>',
i.make_table(f2,t2),
'<h2>Context (wrapcolumn=14,numlines=0)</h2>',
k.make_table(f3.splitlines(),t3.splitlines(),context=True,numlines=0),
'<h2>wrapcolumn=14,splitlines()</h2>',
k.make_table(f3.splitlines(),t3.splitlines()),
'<h2>wrapcolumn=14,splitlines(True)</h2>',
k.make_table(f3.splitlines(True),t3.splitlines(True)),
])
actual = full.replace('</body>','\n%s\n</body>' % tables)
# temporarily uncomment next two lines to baseline this test
#with open('test_difflib_expect.html','w') as fp:
# fp.write(actual)
with open(findfile('/zip/.python/test/test_difflib_expect.html')) as fp:
self.assertEqual(actual, fp.read())
def test_recursion_limit(self):
# Check if the problem described in patch #1413711 exists.
limit = sys.getrecursionlimit()
old = [(i%2 and "K:%d" or "V:A:%d") % i for i in range(limit*2)]
new = [(i%2 and "K:%d" or "V:B:%d") % i for i in range(limit*2)]
difflib.SequenceMatcher(None, old, new).get_opcodes()
def test_make_file_default_charset(self):
html_diff = difflib.HtmlDiff()
output = html_diff.make_file(patch914575_from1.splitlines(),
patch914575_to1.splitlines())
self.assertIn('content="text/html; charset=utf-8"', output)
def test_make_file_iso88591_charset(self):
html_diff = difflib.HtmlDiff()
output = html_diff.make_file(patch914575_from1.splitlines(),
patch914575_to1.splitlines(),
charset='iso-8859-1')
self.assertIn('content="text/html; charset=iso-8859-1"', output)
def test_make_file_usascii_charset_with_nonascii_input(self):
html_diff = difflib.HtmlDiff()
output = html_diff.make_file(patch914575_nonascii_from1.splitlines(),
patch914575_nonascii_to1.splitlines(),
charset='us-ascii')
self.assertIn('content="text/html; charset=us-ascii"', output)
self.assertIn('ımplıcıt', output)
class TestOutputFormat(unittest.TestCase):
def test_tab_delimiter(self):
args = ['one', 'two', 'Original', 'Current',
'2005-01-26 23:30:50', '2010-04-02 10:20:52']
ud = difflib.unified_diff(*args, lineterm='')
self.assertEqual(list(ud)[0:2], [
"--- Original\t2005-01-26 23:30:50",
"+++ Current\t2010-04-02 10:20:52"])
cd = difflib.context_diff(*args, lineterm='')
self.assertEqual(list(cd)[0:2], [
"*** Original\t2005-01-26 23:30:50",
"--- Current\t2010-04-02 10:20:52"])
def test_no_trailing_tab_on_empty_filedate(self):
args = ['one', 'two', 'Original', 'Current']
ud = difflib.unified_diff(*args, lineterm='')
self.assertEqual(list(ud)[0:2], ["--- Original", "+++ Current"])
cd = difflib.context_diff(*args, lineterm='')
self.assertEqual(list(cd)[0:2], ["*** Original", "--- Current"])
def test_range_format_unified(self):
# Per the diff spec at http://www.unix.org/single_unix_specification/
spec = '''\
Each <range> field shall be of the form:
%1d", <beginning line number> if the range contains exactly one line,
and:
"%1d,%1d", <beginning line number>, <number of lines> otherwise.
If a range is empty, its beginning line number shall be the number of
the line just before the range, or 0 if the empty range starts the file.
'''
fmt = difflib._format_range_unified
self.assertEqual(fmt(3,3), '3,0')
self.assertEqual(fmt(3,4), '4')
self.assertEqual(fmt(3,5), '4,2')
self.assertEqual(fmt(3,6), '4,3')
self.assertEqual(fmt(0,0), '0,0')
def test_range_format_context(self):
# Per the diff spec at http://www.unix.org/single_unix_specification/
spec = '''\
The range of lines in file1 shall be written in the following format
if the range contains two or more lines:
"*** %d,%d ****\n", <beginning line number>, <ending line number>
and the following format otherwise:
"*** %d ****\n", <ending line number>
The ending line number of an empty range shall be the number of the preceding line,
or 0 if the range is at the start of the file.
Next, the range of lines in file2 shall be written in the following format
if the range contains two or more lines:
"--- %d,%d ----\n", <beginning line number>, <ending line number>
and the following format otherwise:
"--- %d ----\n", <ending line number>
'''
fmt = difflib._format_range_context
self.assertEqual(fmt(3,3), '3')
self.assertEqual(fmt(3,4), '4')
self.assertEqual(fmt(3,5), '4,5')
self.assertEqual(fmt(3,6), '4,6')
self.assertEqual(fmt(0,0), '0')
class TestBytes(unittest.TestCase):
# don't really care about the content of the output, just the fact
# that it's bytes and we don't crash
def check(self, diff):
diff = list(diff) # trigger exceptions first
for line in diff:
self.assertIsInstance(
line, bytes,
"all lines of diff should be bytes, but got: %r" % line)
def test_byte_content(self):
# if we receive byte strings, we return byte strings
a = [b'hello', b'andr\xe9'] # iso-8859-1 bytes
b = [b'hello', b'andr\xc3\xa9'] # utf-8 bytes
unified = difflib.unified_diff
context = difflib.context_diff
check = self.check
check(difflib.diff_bytes(unified, a, a))
check(difflib.diff_bytes(unified, a, b))
# now with filenames (content and filenames are all bytes!)
check(difflib.diff_bytes(unified, a, a, b'a', b'a'))
check(difflib.diff_bytes(unified, a, b, b'a', b'b'))
# and with filenames and dates
check(difflib.diff_bytes(unified, a, a, b'a', b'a', b'2005', b'2013'))
check(difflib.diff_bytes(unified, a, b, b'a', b'b', b'2005', b'2013'))
# same all over again, with context diff
check(difflib.diff_bytes(context, a, a))
check(difflib.diff_bytes(context, a, b))
check(difflib.diff_bytes(context, a, a, b'a', b'a'))
check(difflib.diff_bytes(context, a, b, b'a', b'b'))
check(difflib.diff_bytes(context, a, a, b'a', b'a', b'2005', b'2013'))
check(difflib.diff_bytes(context, a, b, b'a', b'b', b'2005', b'2013'))
def test_byte_filenames(self):
# somebody renamed a file from ISO-8859-2 to UTF-8
fna = b'\xb3odz.txt' # "Åodz.txt"
fnb = b'\xc5\x82odz.txt'
# they transcoded the content at the same time
a = [b'\xa3odz is a city in Poland.']
b = [b'\xc5\x81odz is a city in Poland.']
check = self.check
unified = difflib.unified_diff
context = difflib.context_diff
check(difflib.diff_bytes(unified, a, b, fna, fnb))
check(difflib.diff_bytes(context, a, b, fna, fnb))
def assertDiff(expect, actual):
# do not compare expect and equal as lists, because unittest
# uses difflib to report difference between lists
actual = list(actual)
self.assertEqual(len(expect), len(actual))
for e, a in zip(expect, actual):
self.assertEqual(e, a)
expect = [
b'--- \xb3odz.txt',
b'+++ \xc5\x82odz.txt',
b'@@ -1 +1 @@',
b'-\xa3odz is a city in Poland.',
b'+\xc5\x81odz is a city in Poland.',
]
actual = difflib.diff_bytes(unified, a, b, fna, fnb, lineterm=b'')
assertDiff(expect, actual)
# with dates (plain ASCII)
datea = b'2005-03-18'
dateb = b'2005-03-19'
check(difflib.diff_bytes(unified, a, b, fna, fnb, datea, dateb))
check(difflib.diff_bytes(context, a, b, fna, fnb, datea, dateb))
expect = [
# note the mixed encodings here: this is deeply wrong by every
# tenet of Unicode, but it doesn't crash, it's parseable by
# patch, and it's how UNIX(tm) diff behaves
b'--- \xb3odz.txt\t2005-03-18',
b'+++ \xc5\x82odz.txt\t2005-03-19',
b'@@ -1 +1 @@',
b'-\xa3odz is a city in Poland.',
b'+\xc5\x81odz is a city in Poland.',
]
actual = difflib.diff_bytes(unified, a, b, fna, fnb, datea, dateb,
lineterm=b'')
assertDiff(expect, actual)
def test_mixed_types_content(self):
# type of input content must be consistent: all str or all bytes
a = [b'hello']
b = ['hello']
unified = difflib.unified_diff
context = difflib.context_diff
expect = "lines to compare must be str, not bytes (b'hello')"
self._assert_type_error(expect, unified, a, b)
self._assert_type_error(expect, unified, b, a)
self._assert_type_error(expect, context, a, b)
self._assert_type_error(expect, context, b, a)
expect = "all arguments must be bytes, not str ('hello')"
self._assert_type_error(expect, difflib.diff_bytes, unified, a, b)
self._assert_type_error(expect, difflib.diff_bytes, unified, b, a)
self._assert_type_error(expect, difflib.diff_bytes, context, a, b)
self._assert_type_error(expect, difflib.diff_bytes, context, b, a)
def test_mixed_types_filenames(self):
# cannot pass filenames as bytes if content is str (this may not be
# the right behaviour, but at least the test demonstrates how
# things work)
a = ['hello\n']
b = ['ohell\n']
fna = b'ol\xe9.txt' # filename transcoded from ISO-8859-1
fnb = b'ol\xc3a9.txt' # to UTF-8
self._assert_type_error(
"all arguments must be str, not: b'ol\\xe9.txt'",
difflib.unified_diff, a, b, fna, fnb)
def test_mixed_types_dates(self):
# type of dates must be consistent with type of contents
a = [b'foo\n']
b = [b'bar\n']
datea = '1 fév'
dateb = '3 fév'
self._assert_type_error(
"all arguments must be bytes, not str ('1 fév')",
difflib.diff_bytes, difflib.unified_diff,
a, b, b'a', b'b', datea, dateb)
# if input is str, non-ASCII dates are fine
a = ['foo\n']
b = ['bar\n']
list(difflib.unified_diff(a, b, 'a', 'b', datea, dateb))
def _assert_type_error(self, msg, generator, *args):
with self.assertRaises(TypeError) as ctx:
list(generator(*args))
self.assertEqual(msg, str(ctx.exception))
class TestJunkAPIs(unittest.TestCase):
def test_is_line_junk_true(self):
for line in ['#', ' ', ' #', '# ', ' # ', '']:
self.assertTrue(difflib.IS_LINE_JUNK(line), repr(line))
def test_is_line_junk_false(self):
for line in ['##', ' ##', '## ', 'abc ', 'abc #', 'Mr. Moose is up!']:
self.assertFalse(difflib.IS_LINE_JUNK(line), repr(line))
def test_is_line_junk_REDOS(self):
evil_input = ('\t' * 1000000) + '##'
self.assertFalse(difflib.IS_LINE_JUNK(evil_input))
def test_is_character_junk_true(self):
for char in [' ', '\t']:
self.assertTrue(difflib.IS_CHARACTER_JUNK(char), repr(char))
def test_is_character_junk_false(self):
for char in ['a', '#', '\n', '\f', '\r', '\v']:
self.assertFalse(difflib.IS_CHARACTER_JUNK(char), repr(char))
def test_main():
difflib.HtmlDiff._default_prefix = 0
Doctests = doctest.DocTestSuite(difflib)
run_unittest(
TestWithAscii, TestAutojunk, TestSFpatches, TestSFbugs,
TestOutputFormat, TestBytes, TestJunkAPIs, Doctests)
if __name__ == '__main__':
test_main()
| 19,841 | 507 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_codecencodings_iso2022.py | # Codec encoding tests for ISO 2022 encodings.
from test import multibytecodec_support
import unittest
COMMON_CODEC_TESTS = (
# invalid bytes
(b'ab\xFFcd', 'replace', 'ab\uFFFDcd'),
(b'ab\x1Bdef', 'replace', 'ab\x1Bdef'),
(b'ab\x1B$def', 'replace', 'ab\uFFFD'),
)
class Test_ISO2022_JP(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'iso2022_jp'
tstring = multibytecodec_support.load_teststring('iso2022_jp')
codectests = COMMON_CODEC_TESTS + (
(b'ab\x1BNdef', 'replace', 'ab\x1BNdef'),
)
class Test_ISO2022_JP2(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'iso2022_jp_2'
tstring = multibytecodec_support.load_teststring('iso2022_jp')
codectests = COMMON_CODEC_TESTS + (
(b'ab\x1BNdef', 'replace', 'abdef'),
)
class Test_ISO2022_KR(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'iso2022_kr'
tstring = multibytecodec_support.load_teststring('iso2022_kr')
codectests = COMMON_CODEC_TESTS + (
(b'ab\x1BNdef', 'replace', 'ab\x1BNdef'),
)
# iso2022_kr.txt cannot be used to test "chunk coding": the escape
# sequence is only written on the first line
@unittest.skip('iso2022_kr.txt cannot be used to test "chunk coding"')
def test_chunkcoding(self):
pass
if __name__ == "__main__":
unittest.main()
| 1,390 | 42 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_strtod.py | # Tests for the correctly-rounded string -> float conversions
# introduced in Python 2.7 and 3.1.
import random
import unittest
import re
import sys
import test.support
if getattr(sys, 'float_repr_style', '') != 'short':
raise unittest.SkipTest('correctly-rounded string->float conversions '
'not available on this system')
# Correctly rounded str -> float in pure Python, for comparison.
strtod_parser = re.compile(r""" # A numeric string consists of:
(?P<sign>[-+])? # an optional sign, followed by
(?=\d|\.\d) # a number with at least one digit
(?P<int>\d*) # having a (possibly empty) integer part
(?:\.(?P<frac>\d*))? # followed by an optional fractional part
(?:E(?P<exp>[-+]?\d+))? # and an optional exponent
\Z
""", re.VERBOSE | re.IGNORECASE).match
# Pure Python version of correctly rounded string->float conversion.
# Avoids any use of floating-point by returning the result as a hex string.
def strtod(s, mant_dig=53, min_exp = -1021, max_exp = 1024):
"""Convert a finite decimal string to a hex string representing an
IEEE 754 binary64 float. Return 'inf' or '-inf' on overflow.
This function makes no use of floating-point arithmetic at any
stage."""
# parse string into a pair of integers 'a' and 'b' such that
# abs(decimal value) = a/b, along with a boolean 'negative'.
m = strtod_parser(s)
if m is None:
raise ValueError('invalid numeric string')
fraction = m.group('frac') or ''
intpart = int(m.group('int') + fraction)
exp = int(m.group('exp') or '0') - len(fraction)
negative = m.group('sign') == '-'
a, b = intpart*10**max(exp, 0), 10**max(0, -exp)
# quick return for zeros
if not a:
return '-0x0.0p+0' if negative else '0x0.0p+0'
# compute exponent e for result; may be one too small in the case
# that the rounded value of a/b lies in a different binade from a/b
d = a.bit_length() - b.bit_length()
d += (a >> d if d >= 0 else a << -d) >= b
e = max(d, min_exp) - mant_dig
# approximate a/b by number of the form q * 2**e; adjust e if necessary
a, b = a << max(-e, 0), b << max(e, 0)
q, r = divmod(a, b)
if 2*r > b or 2*r == b and q & 1:
q += 1
if q.bit_length() == mant_dig+1:
q //= 2
e += 1
# double check that (q, e) has the right form
assert q.bit_length() <= mant_dig and e >= min_exp - mant_dig
assert q.bit_length() == mant_dig or e == min_exp - mant_dig
# check for overflow and underflow
if e + q.bit_length() > max_exp:
return '-inf' if negative else 'inf'
if not q:
return '-0x0.0p+0' if negative else '0x0.0p+0'
# for hex representation, shift so # bits after point is a multiple of 4
hexdigs = 1 + (mant_dig-2)//4
shift = 3 - (mant_dig-2)%4
q, e = q << shift, e - shift
return '{}0x{:x}.{:0{}x}p{:+d}'.format(
'-' if negative else '',
q // 16**hexdigs,
q % 16**hexdigs,
hexdigs,
e + 4*hexdigs)
TEST_SIZE = 10
class StrtodTests(unittest.TestCase):
def check_strtod(self, s):
"""Compare the result of Python's builtin correctly rounded
string->float conversion (using float) to a pure Python
correctly rounded string->float implementation. Fail if the
two methods give different results."""
try:
fs = float(s)
except OverflowError:
got = '-inf' if s[0] == '-' else 'inf'
except MemoryError:
got = 'memory error'
else:
got = fs.hex()
expected = strtod(s)
self.assertEqual(expected, got,
"Incorrectly rounded str->float conversion for {}: "
"expected {}, got {}".format(s, expected, got))
def test_short_halfway_cases(self):
# exact halfway cases with a small number of significant digits
for k in 0, 5, 10, 15, 20:
# upper = smallest integer >= 2**54/5**k
upper = -(-2**54//5**k)
# lower = smallest odd number >= 2**53/5**k
lower = -(-2**53//5**k)
if lower % 2 == 0:
lower += 1
for i in range(TEST_SIZE):
# Select a random odd n in [2**53/5**k,
# 2**54/5**k). Then n * 10**k gives a halfway case
# with small number of significant digits.
n, e = random.randrange(lower, upper, 2), k
# Remove any additional powers of 5.
while n % 5 == 0:
n, e = n // 5, e + 1
assert n % 10 in (1, 3, 7, 9)
# Try numbers of the form n * 2**p2 * 10**e, p2 >= 0,
# until n * 2**p2 has more than 20 significant digits.
digits, exponent = n, e
while digits < 10**20:
s = '{}e{}'.format(digits, exponent)
self.check_strtod(s)
# Same again, but with extra trailing zeros.
s = '{}e{}'.format(digits * 10**40, exponent - 40)
self.check_strtod(s)
digits *= 2
# Try numbers of the form n * 5**p2 * 10**(e - p5), p5
# >= 0, with n * 5**p5 < 10**20.
digits, exponent = n, e
while digits < 10**20:
s = '{}e{}'.format(digits, exponent)
self.check_strtod(s)
# Same again, but with extra trailing zeros.
s = '{}e{}'.format(digits * 10**40, exponent - 40)
self.check_strtod(s)
digits *= 5
exponent -= 1
def test_halfway_cases(self):
# test halfway cases for the round-half-to-even rule
for i in range(100 * TEST_SIZE):
# bit pattern for a random finite positive (or +0.0) float
bits = random.randrange(2047*2**52)
# convert bit pattern to a number of the form m * 2**e
e, m = divmod(bits, 2**52)
if e:
m, e = m + 2**52, e - 1
e -= 1074
# add 0.5 ulps
m, e = 2*m + 1, e - 1
# convert to a decimal string
if e >= 0:
digits = m << e
exponent = 0
else:
# m * 2**e = (m * 5**-e) * 10**e
digits = m * 5**-e
exponent = e
s = '{}e{}'.format(digits, exponent)
self.check_strtod(s)
def test_boundaries(self):
# boundaries expressed as triples (n, e, u), where
# n*10**e is an approximation to the boundary value and
# u*10**e is 1ulp
boundaries = [
(10000000000000000000, -19, 1110), # a power of 2 boundary (1.0)
(17976931348623159077, 289, 1995), # overflow boundary (2.**1024)
(22250738585072013831, -327, 4941), # normal/subnormal (2.**-1022)
(0, -327, 4941), # zero
]
for n, e, u in boundaries:
for j in range(1000):
digits = n + random.randrange(-3*u, 3*u)
exponent = e
s = '{}e{}'.format(digits, exponent)
self.check_strtod(s)
n *= 10
u *= 10
e -= 1
def test_underflow_boundary(self):
# test values close to 2**-1075, the underflow boundary; similar
# to boundary_tests, except that the random error doesn't scale
# with n
for exponent in range(-400, -320):
base = 10**-exponent // 2**1075
for j in range(TEST_SIZE):
digits = base + random.randrange(-1000, 1000)
s = '{}e{}'.format(digits, exponent)
self.check_strtod(s)
def test_bigcomp(self):
for ndigs in 5, 10, 14, 15, 16, 17, 18, 19, 20, 40, 41, 50:
dig10 = 10**ndigs
for i in range(10 * TEST_SIZE):
digits = random.randrange(dig10)
exponent = random.randrange(-400, 400)
s = '{}e{}'.format(digits, exponent)
self.check_strtod(s)
def test_parsing(self):
# make '0' more likely to be chosen than other digits
digits = '000000123456789'
signs = ('+', '-', '')
# put together random short valid strings
# \d*[.\d*]?e
for i in range(1000):
for j in range(TEST_SIZE):
s = random.choice(signs)
intpart_len = random.randrange(5)
s += ''.join(random.choice(digits) for _ in range(intpart_len))
if random.choice([True, False]):
s += '.'
fracpart_len = random.randrange(5)
s += ''.join(random.choice(digits)
for _ in range(fracpart_len))
else:
fracpart_len = 0
if random.choice([True, False]):
s += random.choice(['e', 'E'])
s += random.choice(signs)
exponent_len = random.randrange(1, 4)
s += ''.join(random.choice(digits)
for _ in range(exponent_len))
if intpart_len + fracpart_len:
self.check_strtod(s)
else:
try:
float(s)
except ValueError:
pass
else:
assert False, "expected ValueError"
@test.support.bigmemtest(size=test.support._2G+10, memuse=3, dry_run=False)
def test_oversized_digit_strings(self, maxsize):
# Input string whose length doesn't fit in an INT.
s = "1." + "1" * maxsize
with self.assertRaises(ValueError):
float(s)
del s
s = "0." + "0" * maxsize + "1"
with self.assertRaises(ValueError):
float(s)
del s
def test_large_exponents(self):
# Verify that the clipping of the exponent in strtod doesn't affect the
# output values.
def positive_exp(n):
""" Long string with value 1.0 and exponent n"""
return '0.{}1e+{}'.format('0'*(n-1), n)
def negative_exp(n):
""" Long string with value 1.0 and exponent -n"""
return '1{}e-{}'.format('0'*n, n)
self.assertEqual(float(positive_exp(10000)), 1.0)
self.assertEqual(float(positive_exp(20000)), 1.0)
self.assertEqual(float(positive_exp(30000)), 1.0)
self.assertEqual(float(negative_exp(10000)), 1.0)
self.assertEqual(float(negative_exp(20000)), 1.0)
self.assertEqual(float(negative_exp(30000)), 1.0)
def test_particular(self):
# inputs that produced crashes or incorrectly rounded results with
# previous versions of dtoa.c, for various reasons
test_strings = [
# issue 7632 bug 1, originally reported failing case
'2183167012312112312312.23538020374420446192e-370',
# 5 instances of issue 7632 bug 2
'12579816049008305546974391768996369464963024663104e-357',
'17489628565202117263145367596028389348922981857013e-357',
'18487398785991994634182916638542680759613590482273e-357',
'32002864200581033134358724675198044527469366773928e-358',
'94393431193180696942841837085033647913224148539854e-358',
'73608278998966969345824653500136787876436005957953e-358',
'64774478836417299491718435234611299336288082136054e-358',
'13704940134126574534878641876947980878824688451169e-357',
'46697445774047060960624497964425416610480524760471e-358',
# failing case for bug introduced by METD in r77451 (attempted
# fix for issue 7632, bug 2), and fixed in r77482.
'28639097178261763178489759107321392745108491825303e-311',
# two numbers demonstrating a flaw in the bigcomp 'dig == 0'
# correction block (issue 7632, bug 3)
'1.00000000000000001e44',
'1.0000000000000000100000000000000000000001e44',
# dtoa.c bug for numbers just smaller than a power of 2 (issue
# 7632, bug 4)
'99999999999999994487665465554760717039532578546e-47',
# failing case for off-by-one error introduced by METD in
# r77483 (dtoa.c cleanup), fixed in r77490
'965437176333654931799035513671997118345570045914469' #...
'6213413350821416312194420007991306908470147322020121018368e0',
# incorrect lsb detection for round-half-to-even when
# bc->scale != 0 (issue 7632, bug 6).
'104308485241983990666713401708072175773165034278685' #...
'682646111762292409330928739751702404658197872319129' #...
'036519947435319418387839758990478549477777586673075' #...
'945844895981012024387992135617064532141489278815239' #...
'849108105951619997829153633535314849999674266169258' #...
'928940692239684771590065027025835804863585454872499' #...
'320500023126142553932654370362024104462255244034053' #...
'203998964360882487378334860197725139151265590832887' #...
'433736189468858614521708567646743455601905935595381' #...
'852723723645799866672558576993978025033590728687206' #...
'296379801363024094048327273913079612469982585674824' #...
'156000783167963081616214710691759864332339239688734' #...
'656548790656486646106983450809073750535624894296242' #...
'072010195710276073042036425579852459556183541199012' #...
'652571123898996574563824424330960027873516082763671875e-1075',
# demonstration that original fix for issue 7632 bug 1 was
# buggy; the exit condition was too strong
'247032822920623295e-341',
# demonstrate similar problem to issue 7632 bug1: crash
# with 'oversized quotient in quorem' message.
'99037485700245683102805043437346965248029601286431e-373',
'99617639833743863161109961162881027406769510558457e-373',
'98852915025769345295749278351563179840130565591462e-372',
'99059944827693569659153042769690930905148015876788e-373',
'98914979205069368270421829889078356254059760327101e-372',
# issue 7632 bug 5: the following 2 strings convert differently
'1000000000000000000000000000000000000000e-16',
'10000000000000000000000000000000000000000e-17',
# issue 7632 bug 7
'991633793189150720000000000000000000000000000000000000000e-33',
# And another, similar, failing halfway case
'4106250198039490000000000000000000000000000000000000000e-38',
# issue 7632 bug 8: the following produced 10.0
'10.900000000000000012345678912345678912345',
# two humongous values from issue 7743
'116512874940594195638617907092569881519034793229385' #...
'228569165191541890846564669771714896916084883987920' #...
'473321268100296857636200926065340769682863349205363' #...
'349247637660671783209907949273683040397979984107806' #...
'461822693332712828397617946036239581632976585100633' #...
'520260770761060725403904123144384571612073732754774' #...
'588211944406465572591022081973828448927338602556287' #...
'851831745419397433012491884869454462440536895047499' #...
'436551974649731917170099387762871020403582994193439' #...
'761933412166821484015883631622539314203799034497982' #...
'130038741741727907429575673302461380386596501187482' #...
'006257527709842179336488381672818798450229339123527' #...
'858844448336815912020452294624916993546388956561522' #...
'161875352572590420823607478788399460162228308693742' #...
'05287663441403533948204085390898399055004119873046875e-1075',
'525440653352955266109661060358202819561258984964913' #...
'892256527849758956045218257059713765874251436193619' #...
'443248205998870001633865657517447355992225852945912' #...
'016668660000210283807209850662224417504752264995360' #...
'631512007753855801075373057632157738752800840302596' #...
'237050247910530538250008682272783660778181628040733' #...
'653121492436408812668023478001208529190359254322340' #...
'397575185248844788515410722958784640926528544043090' #...
'115352513640884988017342469275006999104519620946430' #...
'818767147966495485406577703972687838176778993472989' #...
'561959000047036638938396333146685137903018376496408' #...
'319705333868476925297317136513970189073693314710318' #...
'991252811050501448326875232850600451776091303043715' #...
'157191292827614046876950225714743118291034780466325' #...
'085141343734564915193426994587206432697337118211527' #...
'278968731294639353354774788602467795167875117481660' #...
'4738791256853675690543663283782215866825e-1180',
# exercise exit conditions in bigcomp comparison loop
'2602129298404963083833853479113577253105939995688e2',
'260212929840496308383385347911357725310593999568896e0',
'26021292984049630838338534791135772531059399956889601e-2',
'260212929840496308383385347911357725310593999568895e0',
'260212929840496308383385347911357725310593999568897e0',
'260212929840496308383385347911357725310593999568996e0',
'260212929840496308383385347911357725310593999568866e0',
# 2**53
'9007199254740992.00',
# 2**1024 - 2**970: exact overflow boundary. All values
# smaller than this should round to something finite; any value
# greater than or equal to this one overflows.
'179769313486231580793728971405303415079934132710037' #...
'826936173778980444968292764750946649017977587207096' #...
'330286416692887910946555547851940402630657488671505' #...
'820681908902000708383676273854845817711531764475730' #...
'270069855571366959622842914819860834936475292719074' #...
'168444365510704342711559699508093042880177904174497792',
# 2**1024 - 2**970 - tiny
'179769313486231580793728971405303415079934132710037' #...
'826936173778980444968292764750946649017977587207096' #...
'330286416692887910946555547851940402630657488671505' #...
'820681908902000708383676273854845817711531764475730' #...
'270069855571366959622842914819860834936475292719074' #...
'168444365510704342711559699508093042880177904174497791.999',
# 2**1024 - 2**970 + tiny
'179769313486231580793728971405303415079934132710037' #...
'826936173778980444968292764750946649017977587207096' #...
'330286416692887910946555547851940402630657488671505' #...
'820681908902000708383676273854845817711531764475730' #...
'270069855571366959622842914819860834936475292719074' #...
'168444365510704342711559699508093042880177904174497792.001',
# 1 - 2**-54, +-tiny
'999999999999999944488848768742172978818416595458984375e-54',
'9999999999999999444888487687421729788184165954589843749999999e-54',
'9999999999999999444888487687421729788184165954589843750000001e-54',
# Value found by Rick Regan that gives a result of 2**-968
# under Gay's dtoa.c (as of Nov 04, 2010); since fixed.
# (Fixed some time ago in Python's dtoa.c.)
'0.0000000000000000000000000000000000000000100000000' #...
'000000000576129113423785429971690421191214034235435' #...
'087147763178149762956868991692289869941246658073194' #...
'51982237978882039897143840789794921875',
]
for s in test_strings:
self.check_strtod(s)
if __name__ == "__main__":
unittest.main()
| 20,537 | 434 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/badsyntax_future6.py | """This is a test"""
"this isn't a doc string"
from __future__ import nested_scopes
def f(x):
def g(y):
return x + y
return g
result = f(2)(4)
| 161 | 11 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_doctest2.txt | This is a sample doctest in a text file.
In this example, we'll rely on some silly setup:
>>> import test.test_doctest
>>> test.test_doctest.sillySetup
True
This test also has some (random) encoded (utf-8) unicode text:
ÃÂÃÂÃÂÃÂÃÂ
This doesn't cause a problem in the tect surrounding the examples, but
we include it here (in this test text file) to make sure. :)
| 392 | 15 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_kdf.py | import hashlib
import unittest
import binascii
TRANS_5C = bytes((x ^ 0x5C) for x in range(256))
TRANS_36 = bytes((x ^ 0x36) for x in range(256))
class Pbkdf2Test(unittest.TestCase):
def test_rfc6070_sha1_iter1(self):
self.assertEqual(
'0c60c80f961f0e71f3a9b524af6012062fe037a6',
hashlib.pbkdf2_hmac(hash_name='sha1',
password=b'password',
salt=b'salt',
iterations=1,
dklen=20).hex())
def test_rfc6070_sha1_iter2(self):
self.assertEqual(
'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957',
hashlib.pbkdf2_hmac(hash_name='sha1',
password=b'password',
salt=b'salt',
iterations=2,
dklen=20).hex())
def pbkdf2_hmac_golden(hash_name, password, salt, iterations, dklen=None):
"""Password based key derivation function 2 (PKCS #5 v2.0)
This Python implementations based on the hmac module about as fast
as Mbedtls's PKCS5_PBKDF2_HMAC for short passwords and much faster
for long passwords.
"""
if not isinstance(hash_name, str):
raise TypeError(hash_name)
if not isinstance(password, (bytes, bytearray)):
password = bytes(memoryview(password))
if not isinstance(salt, (bytes, bytearray)):
salt = bytes(memoryview(salt))
# Fast inline HMAC implementation
inner = hashlib.new(hash_name)
outer = hashlib.new(hash_name)
blocksize = getattr(inner, 'block_size', 64)
if len(password) > blocksize:
password = hashlib.new(hash_name, password).digest()
password = password + b'\x00' * (blocksize - len(password))
inner.update(password.translate(TRANS_36))
outer.update(password.translate(TRANS_5C))
def prf(msg, inner=inner, outer=outer):
# PBKDF2_HMAC uses the password as key. We can re-use the same
# digest objects and just update copies to skip initialization.
icpy = inner.copy()
ocpy = outer.copy()
icpy.update(msg)
ocpy.update(icpy.digest())
return ocpy.digest()
if iterations < 1:
raise ValueError(iterations)
if dklen is None:
dklen = outer.digest_size
if dklen < 1:
raise ValueError(dklen)
dkey = b''
loop = 1
from_bytes = int.from_bytes
while len(dkey) < dklen:
prev = prf(salt + loop.to_bytes(4, 'big'))
# endianess doesn't matter here as long to / from use the same
rkey = int.from_bytes(prev, 'big')
for i in range(iterations - 1):
prev = prf(prev)
# rkey = rkey ^ prev
rkey ^= from_bytes(prev, 'big')
loop += 1
dkey += rkey.to_bytes(inner.digest_size, 'big')
return dkey[:dklen]
class KDFTests(unittest.TestCase):
pbkdf2_test_vectors = [
(b'password', b'salt', 1, None),
(b'password', b'salt', 2, None),
(b'password', b'salt', 4096, None),
# too slow, it takes over a minute on a fast CPU.
#(b'password', b'salt', 16777216, None),
(b'passwordPASSWORDpassword', b'saltSALTsaltSALTsaltSALTsaltSALTsalt',
4096, -1),
(b'pass\0word', b'sa\0lt', 4096, 16),
]
scrypt_test_vectors = [
(b'', b'', 16, 1, 1, binascii.unhexlify('77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906')),
(b'password', b'NaCl', 1024, 8, 16, binascii.unhexlify('fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640')),
(b'pleaseletmein', b'SodiumChloride', 16384, 8, 1, binascii.unhexlify('7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887')),
]
pbkdf2_results = {
"sha1": [
# official test vectors from RFC 6070
(bytes.fromhex('0c60c80f961f0e71f3a9b524af6012062fe037a6'), None),
(bytes.fromhex('ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), None),
(bytes.fromhex('4b007901b765489abead49d926f721d065a429c1'), None),
#(bytes.fromhex('eefe3d61cd4da4e4e9945b3d6ba2158c2634e984'), None),
(bytes.fromhex('3d2eec4fe41c849b80c8d83662c0e44a8b291a964c'
'f2f07038'), 25),
(bytes.fromhex('56fa6aa75548099dcc37d7f03425e0c3'), None),],
"sha256": [
(bytes.fromhex('120fb6cffcf8b32c43e7225256c4f837'
'a86548c92ccc35480805987cb70be17b'), None),
(bytes.fromhex('ae4d0c95af6b46d32d0adff928f06dd0'
'2a303f8ef3c251dfd6e2d85a95474c43'), None),
(bytes.fromhex('c5e478d59288c841aa530db6845c4c8d'
'962893a001ce4e11a4963873aa98134a'), None),
#(bytes.fromhex('cf81c66fe8cfc04d1f31ecb65dab4089'
# 'f7f179e89b3b0bcb17ad10e3ac6eba46'), None),
(bytes.fromhex('348c89dbcbd32b2f32d814b8116e84cf2b17'
'347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9'), 40),
(bytes.fromhex('89b69d0516f829893c696226650a8687'), None),],
"sha512": [
(bytes.fromhex('867f70cf1ade02cff3752599a3a53dc4af34c7a669815ae5'
'd513554e1c8cf252c02d470a285a0501bad999bfe943c08f'
'050235d7d68b1da55e63f73b60a57fce'), None),
(bytes.fromhex('e1d9c16aa681708a45f5c7c4e215ceb66e011a2e9f004071'
'3f18aefdb866d53cf76cab2868a39b9f7840edce4fef5a82'
'be67335c77a6068e04112754f27ccf4e'), None),
(bytes.fromhex('d197b1b33db0143e018b12f3d1d1479e6cdebdcc97c5c0f8'
'7f6902e072f457b5143f30602641b3d55cd335988cb36b84'
'376060ecd532e039b742a239434af2d5'), None),
(bytes.fromhex('8c0511f4c6e597c6ac6315d8f0362e225f3c501495ba23b8'
'68c005174dc4ee71115b59f9e60cd9532fa33e0f75aefe30'
'225c583a186cd82bd4daea9724a3d3b8'), 64),
(bytes.fromhex('9d9e9c4cd21fe4be24d5b8244c759665'), None),],
}
def _test_pbkdf2_hmac(self, pbkdf2):
for digest_name, results in self.pbkdf2_results.items():
for i, vector in enumerate(self.pbkdf2_test_vectors):
password, salt, rounds, dklen = vector
expected, overwrite_dklen = results[i]
if overwrite_dklen:
dklen = overwrite_dklen
out = pbkdf2(digest_name, password, salt, rounds, dklen)
self.assertEqual(out, expected,
(digest_name, password, salt, rounds, dklen))
out = pbkdf2(digest_name, memoryview(password),
memoryview(salt), rounds, dklen)
out = pbkdf2(digest_name, bytearray(password),
bytearray(salt), rounds, dklen)
self.assertEqual(out, expected)
if dklen is None:
out = pbkdf2(digest_name, password, salt, rounds)
self.assertEqual(out, expected,
(digest_name, password, salt, rounds))
self.assertRaises(TypeError, pbkdf2, b'sha1', b'pass', b'salt', 1)
self.assertRaises(TypeError, pbkdf2, 'sha1', 'pass', 'salt', 1)
self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', 0)
self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', -1)
self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', 1, 0)
self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', 1, -1)
with self.assertRaisesRegex(ValueError, 'unsupported hash type'):
pbkdf2('unknown', b'pass', b'salt', 1)
out = pbkdf2(hash_name='sha1', password=b'password', salt=b'salt',
iterations=1, dklen=None)
self.assertEqual(out, self.pbkdf2_results['sha1'][0][0])
def test_pbkdf2_hmac_py(self):
self._test_pbkdf2_hmac(pbkdf2_hmac_golden)
def test_pbkdf2_hmac_c(self):
self._test_pbkdf2_hmac(hashlib.pbkdf2_hmac)
@unittest.skipUnless(hasattr(hashlib, 'scrypt'),
'Test requires OpenSSL > 1.1')
def test_scrypt(self):
for password, salt, n, r, p, expected in self.scrypt_test_vectors:
result = hashlib.scrypt(password, salt=salt, n=n, r=r, p=p)
self.assertEqual(result, expected)
# this values should work
hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1)
# password and salt must be bytes-like
with self.assertRaises(TypeError):
hashlib.scrypt('password', salt=b'salt', n=2, r=8, p=1)
with self.assertRaises(TypeError):
hashlib.scrypt(b'password', salt='salt', n=2, r=8, p=1)
# require keyword args
with self.assertRaises(TypeError):
hashlib.scrypt(b'password')
with self.assertRaises(TypeError):
hashlib.scrypt(b'password', b'salt')
with self.assertRaises(TypeError):
hashlib.scrypt(b'password', 2, 8, 1, salt=b'salt')
for n in [-1, 0, 1, None]:
with self.assertRaises((ValueError, OverflowError, TypeError)):
hashlib.scrypt(b'password', salt=b'salt', n=n, r=8, p=1)
for r in [-1, 0, None]:
with self.assertRaises((ValueError, OverflowError, TypeError)):
hashlib.scrypt(b'password', salt=b'salt', n=2, r=r, p=1)
for p in [-1, 0, None]:
with self.assertRaises((ValueError, OverflowError, TypeError)):
hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=p)
for maxmem in [-1, None]:
with self.assertRaises((ValueError, OverflowError, TypeError)):
hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1,
maxmem=maxmem)
for dklen in [-1, None]:
with self.assertRaises((ValueError, OverflowError, TypeError)):
hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1,
dklen=dklen)
if __name__ == '__main__':
unittest.main()
| 10,429 | 219 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_fileio.py | # Adapted from test_file.py by Daniel Stutzbach
import sys
import os
import io
import errno
import cosmo
import unittest
from array import array
from weakref import proxy
from functools import wraps
from test.support import (TESTFN, TESTFN_UNICODE, check_warnings, run_unittest,
make_bad_fd, cpython_only, swap_attr)
from collections import UserList
import _io # C implementation of io
import _pyio # Python implementation of io
class AutoFileTests:
# file tests for which a test file is automatically set up
def setUp(self):
self.f = self.FileIO(TESTFN, 'w')
def tearDown(self):
if self.f:
self.f.close()
os.remove(TESTFN)
def testWeakRefs(self):
# verify weak references
p = proxy(self.f)
p.write(bytes(range(10)))
self.assertEqual(self.f.tell(), p.tell())
self.f.close()
self.f = None
self.assertRaises(ReferenceError, getattr, p, 'tell')
def testSeekTell(self):
self.f.write(bytes(range(20)))
self.assertEqual(self.f.tell(), 20)
self.f.seek(0)
self.assertEqual(self.f.tell(), 0)
self.f.seek(10)
self.assertEqual(self.f.tell(), 10)
self.f.seek(5, 1)
self.assertEqual(self.f.tell(), 15)
self.f.seek(-5, 1)
self.assertEqual(self.f.tell(), 10)
self.f.seek(-5, 2)
self.assertEqual(self.f.tell(), 15)
def testAttributes(self):
# verify expected attributes exist
f = self.f
self.assertEqual(f.mode, "wb")
self.assertEqual(f.closed, False)
# verify the attributes are readonly
for attr in 'mode', 'closed':
self.assertRaises((AttributeError, TypeError),
setattr, f, attr, 'oops')
def testBlksize(self):
# test private _blksize attribute
blksize = io.DEFAULT_BUFFER_SIZE
# try to get preferred blksize from stat.st_blksize, if available
if hasattr(os, 'fstat'):
fst = os.fstat(self.f.fileno())
blksize = getattr(fst, 'st_blksize', blksize)
self.assertEqual(self.f._blksize, blksize)
# verify readinto
def testReadintoByteArray(self):
self.f.write(bytes([1, 2, 0, 255]))
self.f.close()
ba = bytearray(b'abcdefgh')
with self.FileIO(TESTFN, 'r') as f:
n = f.readinto(ba)
self.assertEqual(ba, b'\x01\x02\x00\xffefgh')
self.assertEqual(n, 4)
def _testReadintoMemoryview(self):
self.f.write(bytes([1, 2, 0, 255]))
self.f.close()
m = memoryview(bytearray(b'abcdefgh'))
with self.FileIO(TESTFN, 'r') as f:
n = f.readinto(m)
self.assertEqual(m, b'\x01\x02\x00\xffefgh')
self.assertEqual(n, 4)
m = memoryview(bytearray(b'abcdefgh')).cast('H', shape=[2, 2])
with self.FileIO(TESTFN, 'r') as f:
n = f.readinto(m)
self.assertEqual(bytes(m), b'\x01\x02\x00\xffefgh')
self.assertEqual(n, 4)
def _testReadintoArray(self):
self.f.write(bytes([1, 2, 0, 255]))
self.f.close()
a = array('B', b'abcdefgh')
with self.FileIO(TESTFN, 'r') as f:
n = f.readinto(a)
self.assertEqual(a, array('B', [1, 2, 0, 255, 101, 102, 103, 104]))
self.assertEqual(n, 4)
a = array('b', b'abcdefgh')
with self.FileIO(TESTFN, 'r') as f:
n = f.readinto(a)
self.assertEqual(a, array('b', [1, 2, 0, -1, 101, 102, 103, 104]))
self.assertEqual(n, 4)
a = array('I', b'abcdefgh')
with self.FileIO(TESTFN, 'r') as f:
n = f.readinto(a)
self.assertEqual(a, array('I', b'\x01\x02\x00\xffefgh'))
self.assertEqual(n, 4)
def testWritelinesList(self):
l = [b'123', b'456']
self.f.writelines(l)
self.f.close()
self.f = self.FileIO(TESTFN, 'rb')
buf = self.f.read()
self.assertEqual(buf, b'123456')
def testWritelinesUserList(self):
l = UserList([b'123', b'456'])
self.f.writelines(l)
self.f.close()
self.f = self.FileIO(TESTFN, 'rb')
buf = self.f.read()
self.assertEqual(buf, b'123456')
def testWritelinesError(self):
self.assertRaises(TypeError, self.f.writelines, [1, 2, 3])
self.assertRaises(TypeError, self.f.writelines, None)
self.assertRaises(TypeError, self.f.writelines, "abc")
def test_none_args(self):
self.f.write(b"hi\nbye\nabc")
self.f.close()
self.f = self.FileIO(TESTFN, 'r')
self.assertEqual(self.f.read(None), b"hi\nbye\nabc")
self.f.seek(0)
self.assertEqual(self.f.readline(None), b"hi\n")
self.assertEqual(self.f.readlines(None), [b"bye\n", b"abc"])
def test_reject(self):
self.assertRaises(TypeError, self.f.write, "Hello!")
def testRepr(self):
self.assertEqual(repr(self.f),
"<%s.FileIO name=%r mode=%r closefd=True>" %
(self.modulename, self.f.name, self.f.mode))
del self.f.name
self.assertEqual(repr(self.f),
"<%s.FileIO fd=%r mode=%r closefd=True>" %
(self.modulename, self.f.fileno(), self.f.mode))
self.f.close()
self.assertEqual(repr(self.f),
"<%s.FileIO [closed]>" % (self.modulename,))
def testReprNoCloseFD(self):
fd = os.open(TESTFN, os.O_RDONLY)
try:
with self.FileIO(fd, 'r', closefd=False) as f:
self.assertEqual(repr(f),
"<%s.FileIO name=%r mode=%r closefd=False>" %
(self.modulename, f.name, f.mode))
finally:
os.close(fd)
@unittest.skipIf(cosmo.MODE.startswith("tiny"), "no stack awareness in tiny mode")
def testRecursiveRepr(self):
# Issue #25455
with swap_attr(self.f, 'name', self.f):
try:
repr(self.f) # Should not crash
except (RuntimeError, MemoryError):
pass
else:
assert False
def testErrors(self):
f = self.f
self.assertFalse(f.isatty())
self.assertFalse(f.closed)
#self.assertEqual(f.name, TESTFN)
self.assertRaises(ValueError, f.read, 10) # Open for reading
f.close()
self.assertTrue(f.closed)
f = self.FileIO(TESTFN, 'r')
self.assertRaises(TypeError, f.readinto, "")
self.assertFalse(f.closed)
f.close()
self.assertTrue(f.closed)
def testMethods(self):
methods = ['fileno', 'isatty', 'seekable', 'readable', 'writable',
'read', 'readall', 'readline', 'readlines',
'tell', 'truncate', 'flush']
self.f.close()
self.assertTrue(self.f.closed)
for methodname in methods:
method = getattr(self.f, methodname)
# should raise on closed file
self.assertRaises(ValueError, method)
self.assertRaises(TypeError, self.f.readinto)
self.assertRaises(ValueError, self.f.readinto, bytearray(1))
self.assertRaises(TypeError, self.f.seek)
self.assertRaises(ValueError, self.f.seek, 0)
self.assertRaises(TypeError, self.f.write)
self.assertRaises(ValueError, self.f.write, b'')
self.assertRaises(TypeError, self.f.writelines)
self.assertRaises(ValueError, self.f.writelines, b'')
def testOpendir(self):
# Issue 3703: opening a directory should fill the errno
# Windows always returns "[Errno 13]: Permission denied
# Unix uses fstat and returns "[Errno 21]: Is a directory"
try:
self.FileIO('.', 'r')
except OSError as e:
self.assertNotEqual(e.errno, 0)
self.assertEqual(e.filename, ".")
else:
self.fail("Should have raised OSError")
@unittest.skipIf(True, "[jart] Breaks Landlock LSM [why??]")
@unittest.skipIf(os.name == 'nt', "test only works on a POSIX-like system")
def testOpenDirFD(self):
fd = os.open('.', os.O_RDONLY)
with self.assertRaises(OSError) as cm:
self.FileIO(fd, 'r')
os.close(fd)
self.assertEqual(cm.exception.errno, errno.EISDIR)
#A set of functions testing that we get expected behaviour if someone has
#manually closed the internal file descriptor. First, a decorator:
def ClosedFD(func):
@wraps(func)
def wrapper(self):
#forcibly close the fd before invoking the problem function
f = self.f
os.close(f.fileno())
try:
func(self, f)
finally:
try:
self.f.close()
except OSError:
pass
return wrapper
def ClosedFDRaises(func):
@wraps(func)
def wrapper(self):
#forcibly close the fd before invoking the problem function
f = self.f
os.close(f.fileno())
try:
func(self, f)
except OSError as e:
self.assertEqual(e.errno, errno.EBADF)
else:
self.fail("Should have raised OSError")
finally:
try:
self.f.close()
except OSError:
pass
return wrapper
@ClosedFDRaises
def testErrnoOnClose(self, f):
f.close()
@ClosedFDRaises
def testErrnoOnClosedWrite(self, f):
f.write(b'a')
@ClosedFDRaises
def testErrnoOnClosedSeek(self, f):
f.seek(0)
@ClosedFDRaises
def testErrnoOnClosedTell(self, f):
f.tell()
@ClosedFDRaises
def testErrnoOnClosedTruncate(self, f):
f.truncate(0)
@ClosedFD
def testErrnoOnClosedSeekable(self, f):
f.seekable()
@ClosedFD
def testErrnoOnClosedReadable(self, f):
f.readable()
@ClosedFD
def testErrnoOnClosedWritable(self, f):
f.writable()
@ClosedFD
def testErrnoOnClosedFileno(self, f):
f.fileno()
@ClosedFD
def testErrnoOnClosedIsatty(self, f):
self.assertEqual(f.isatty(), False)
def ReopenForRead(self):
try:
self.f.close()
except OSError:
pass
self.f = self.FileIO(TESTFN, 'r')
os.close(self.f.fileno())
return self.f
@ClosedFDRaises
def testErrnoOnClosedRead(self, f):
f = self.ReopenForRead()
f.read(1)
@ClosedFDRaises
def testErrnoOnClosedReadall(self, f):
f = self.ReopenForRead()
f.readall()
@ClosedFDRaises
def testErrnoOnClosedReadinto(self, f):
f = self.ReopenForRead()
a = array('b', b'x'*10)
f.readinto(a)
class CAutoFileTests(AutoFileTests, unittest.TestCase):
FileIO = _io.FileIO
modulename = '_io'
class PyAutoFileTests(AutoFileTests, unittest.TestCase):
FileIO = _pyio.FileIO
modulename = '_pyio'
class OtherFileTests:
def testAbles(self):
try:
f = self.FileIO(TESTFN, "w")
self.assertEqual(f.readable(), False)
self.assertEqual(f.writable(), True)
self.assertEqual(f.seekable(), True)
f.close()
f = self.FileIO(TESTFN, "r")
self.assertEqual(f.readable(), True)
self.assertEqual(f.writable(), False)
self.assertEqual(f.seekable(), True)
f.close()
f = self.FileIO(TESTFN, "a+")
self.assertEqual(f.readable(), True)
self.assertEqual(f.writable(), True)
self.assertEqual(f.seekable(), True)
self.assertEqual(f.isatty(), False)
f.close()
if sys.platform != "win32":
try:
f = self.FileIO("/dev/tty", "a")
except OSError:
# When run in a cron job there just aren't any
# ttys, so skip the test. This also handles other
# OS'es that don't support /dev/tty.
pass
else:
self.assertEqual(f.readable(), False)
self.assertEqual(f.writable(), True)
if sys.platform != "darwin" and \
'bsd' not in sys.platform and \
not sys.platform.startswith(('sunos', 'aix')):
# Somehow /dev/tty appears seekable on some BSDs
self.assertEqual(f.seekable(), False)
self.assertEqual(f.isatty(), True)
f.close()
finally:
os.unlink(TESTFN)
def testInvalidModeStrings(self):
# check invalid mode strings
for mode in ("", "aU", "wU+", "rw", "rt"):
try:
f = self.FileIO(TESTFN, mode)
except ValueError:
pass
else:
f.close()
self.fail('%r is an invalid file mode' % mode)
def testModeStrings(self):
# test that the mode attribute is correct for various mode strings
# given as init args
try:
for modes in [('w', 'wb'), ('wb', 'wb'), ('wb+', 'rb+'),
('w+b', 'rb+'), ('a', 'ab'), ('ab', 'ab'),
('ab+', 'ab+'), ('a+b', 'ab+'), ('r', 'rb'),
('rb', 'rb'), ('rb+', 'rb+'), ('r+b', 'rb+')]:
# read modes are last so that TESTFN will exist first
with self.FileIO(TESTFN, modes[0]) as f:
self.assertEqual(f.mode, modes[1])
finally:
if os.path.exists(TESTFN):
os.unlink(TESTFN)
def testUnicodeOpen(self):
# verify repr works for unicode too
f = self.FileIO(str(TESTFN), "w")
f.close()
os.unlink(TESTFN)
def testBytesOpen(self):
# Opening a bytes filename
try:
fn = TESTFN.encode("ascii")
except UnicodeEncodeError:
self.skipTest('could not encode %r to ascii' % TESTFN)
f = self.FileIO(fn, "w")
try:
f.write(b"abc")
f.close()
with open(TESTFN, "rb") as f:
self.assertEqual(f.read(), b"abc")
finally:
os.unlink(TESTFN)
@unittest.skipIf(sys.getfilesystemencoding() != 'utf-8',
"test only works for utf-8 filesystems")
def testUtf8BytesOpen(self):
# Opening a UTF-8 bytes filename
try:
fn = TESTFN_UNICODE.encode("utf-8")
except UnicodeEncodeError:
self.skipTest('could not encode %r to utf-8' % TESTFN_UNICODE)
f = self.FileIO(fn, "w")
try:
f.write(b"abc")
f.close()
with open(TESTFN_UNICODE, "rb") as f:
self.assertEqual(f.read(), b"abc")
finally:
os.unlink(TESTFN_UNICODE)
def testConstructorHandlesNULChars(self):
fn_with_NUL = 'foo\0bar'
self.assertRaises(ValueError, self.FileIO, fn_with_NUL, 'w')
self.assertRaises(ValueError, self.FileIO, bytes(fn_with_NUL, 'ascii'), 'w')
def testInvalidFd(self):
self.assertRaises(ValueError, self.FileIO, -10)
self.assertRaises(OSError, self.FileIO, make_bad_fd())
if sys.platform == 'win32':
import msvcrt
self.assertRaises(OSError, msvcrt.get_osfhandle, make_bad_fd())
def testBadModeArgument(self):
# verify that we get a sensible error message for bad mode argument
bad_mode = "qwerty"
try:
f = self.FileIO(TESTFN, bad_mode)
except ValueError as msg:
if msg.args[0] != 0:
s = str(msg)
if TESTFN in s or bad_mode not in s:
self.fail("bad error message for invalid mode: %s" % s)
# if msg.args[0] == 0, we're probably on Windows where there may be
# no obvious way to discover why open() failed.
else:
f.close()
self.fail("no error for invalid mode: %s" % bad_mode)
def testTruncate(self):
f = self.FileIO(TESTFN, 'w')
f.write(bytes(bytearray(range(10))))
self.assertEqual(f.tell(), 10)
f.truncate(5)
self.assertEqual(f.tell(), 10)
self.assertEqual(f.seek(0, io.SEEK_END), 5)
f.truncate(15)
self.assertEqual(f.tell(), 5)
self.assertEqual(f.seek(0, io.SEEK_END), 15)
f.close()
def testTruncateOnWindows(self):
def bug801631():
# SF bug <http://www.python.org/sf/801631>
# "file.truncate fault on windows"
f = self.FileIO(TESTFN, 'w')
f.write(bytes(range(11)))
f.close()
f = self.FileIO(TESTFN,'r+')
data = f.read(5)
if data != bytes(range(5)):
self.fail("Read on file opened for update failed %r" % data)
if f.tell() != 5:
self.fail("File pos after read wrong %d" % f.tell())
f.truncate()
if f.tell() != 5:
self.fail("File pos after ftruncate wrong %d" % f.tell())
f.close()
size = os.path.getsize(TESTFN)
if size != 5:
self.fail("File size after ftruncate wrong %d" % size)
try:
bug801631()
finally:
os.unlink(TESTFN)
def testAppend(self):
try:
f = open(TESTFN, 'wb')
f.write(b'spam')
f.close()
f = open(TESTFN, 'ab')
f.write(b'eggs')
f.close()
f = open(TESTFN, 'rb')
d = f.read()
f.close()
self.assertEqual(d, b'spameggs')
finally:
try:
os.unlink(TESTFN)
except:
pass
def testInvalidInit(self):
self.assertRaises(TypeError, self.FileIO, "1", 0, 0)
def testWarnings(self):
with check_warnings(quiet=True) as w:
self.assertEqual(w.warnings, [])
self.assertRaises(TypeError, self.FileIO, [])
self.assertEqual(w.warnings, [])
self.assertRaises(ValueError, self.FileIO, "/some/invalid/name", "rt")
self.assertEqual(w.warnings, [])
@unittest.skipIf(cosmo.MODE in ('tiny', 'rel'),
"fails on missing .py file in rel mode")
def testUnclosedFDOnException(self):
class MyException(Exception): pass
class MyFileIO(self.FileIO):
def __setattr__(self, name, value):
if name == "name":
raise MyException("blocked setting name")
return super(MyFileIO, self).__setattr__(name, value)
fd = os.open(__file__, os.O_RDONLY)
self.assertRaises(MyException, MyFileIO, fd)
os.close(fd) # should not raise OSError(EBADF)
class COtherFileTests(OtherFileTests, unittest.TestCase):
FileIO = _io.FileIO
modulename = '_io'
@cpython_only
def testInvalidFd_overflow(self):
# Issue 15989
import _testcapi
self.assertRaises(TypeError, self.FileIO, _testcapi.INT_MAX + 1)
self.assertRaises(TypeError, self.FileIO, _testcapi.INT_MIN - 1)
class PyOtherFileTests(OtherFileTests, unittest.TestCase):
FileIO = _pyio.FileIO
modulename = '_pyio'
def test_main():
# Historically, these tests have been sloppy about removing TESTFN.
# So get rid of it no matter what.
try:
run_unittest(CAutoFileTests, PyAutoFileTests,
COtherFileTests, PyOtherFileTests)
finally:
if os.path.exists(TESTFN):
os.unlink(TESTFN)
if __name__ == '__main__':
test_main()
| 20,010 | 605 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_userdict.py | # Check every path through every method of UserDict
from test import mapping_tests
import unittest
import collections
d0 = {}
d1 = {"one": 1}
d2 = {"one": 1, "two": 2}
d3 = {"one": 1, "two": 3, "three": 5}
d4 = {"one": None, "two": None}
d5 = {"one": 1, "two": 1}
class UserDictTest(mapping_tests.TestHashMappingProtocol):
type2test = collections.UserDict
def test_all(self):
# Test constructors
u = collections.UserDict()
u0 = collections.UserDict(d0)
u1 = collections.UserDict(d1)
u2 = collections.UserDict(d2)
uu = collections.UserDict(u)
uu0 = collections.UserDict(u0)
uu1 = collections.UserDict(u1)
uu2 = collections.UserDict(u2)
# keyword arg constructor
self.assertEqual(collections.UserDict(one=1, two=2), d2)
# item sequence constructor
self.assertEqual(collections.UserDict([('one',1), ('two',2)]), d2)
with self.assertWarnsRegex(DeprecationWarning, "'dict'"):
self.assertEqual(collections.UserDict(dict=[('one',1), ('two',2)]), d2)
# both together
self.assertEqual(collections.UserDict([('one',1), ('two',2)], two=3, three=5), d3)
# alternate constructor
self.assertEqual(collections.UserDict.fromkeys('one two'.split()), d4)
self.assertEqual(collections.UserDict().fromkeys('one two'.split()), d4)
self.assertEqual(collections.UserDict.fromkeys('one two'.split(), 1), d5)
self.assertEqual(collections.UserDict().fromkeys('one two'.split(), 1), d5)
self.assertTrue(u1.fromkeys('one two'.split()) is not u1)
self.assertIsInstance(u1.fromkeys('one two'.split()), collections.UserDict)
self.assertIsInstance(u2.fromkeys('one two'.split()), collections.UserDict)
# Test __repr__
self.assertEqual(str(u0), str(d0))
self.assertEqual(repr(u1), repr(d1))
self.assertIn(repr(u2), ("{'one': 1, 'two': 2}",
"{'two': 2, 'one': 1}"))
# Test rich comparison and __len__
all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2]
for a in all:
for b in all:
self.assertEqual(a == b, len(a) == len(b))
# Test __getitem__
self.assertEqual(u2["one"], 1)
self.assertRaises(KeyError, u1.__getitem__, "two")
# Test __setitem__
u3 = collections.UserDict(u2)
u3["two"] = 2
u3["three"] = 3
# Test __delitem__
del u3["three"]
self.assertRaises(KeyError, u3.__delitem__, "three")
# Test clear
u3.clear()
self.assertEqual(u3, {})
# Test copy()
u2a = u2.copy()
self.assertEqual(u2a, u2)
u2b = collections.UserDict(x=42, y=23)
u2c = u2b.copy() # making a copy of a UserDict is special cased
self.assertEqual(u2b, u2c)
class MyUserDict(collections.UserDict):
def display(self): print(self)
m2 = MyUserDict(u2)
m2a = m2.copy()
self.assertEqual(m2a, m2)
# SF bug #476616 -- copy() of UserDict subclass shared data
m2['foo'] = 'bar'
self.assertNotEqual(m2a, m2)
# Test keys, items, values
self.assertEqual(sorted(u2.keys()), sorted(d2.keys()))
self.assertEqual(sorted(u2.items()), sorted(d2.items()))
self.assertEqual(sorted(u2.values()), sorted(d2.values()))
# Test "in".
for i in u2.keys():
self.assertIn(i, u2)
self.assertEqual(i in u1, i in d1)
self.assertEqual(i in u0, i in d0)
# Test update
t = collections.UserDict()
t.update(u2)
self.assertEqual(t, u2)
# Test get
for i in u2.keys():
self.assertEqual(u2.get(i), u2[i])
self.assertEqual(u1.get(i), d1.get(i))
self.assertEqual(u0.get(i), d0.get(i))
# Test "in" iteration.
for i in range(20):
u2[i] = str(i)
ikeys = []
for k in u2:
ikeys.append(k)
keys = u2.keys()
self.assertEqual(set(ikeys), set(keys))
# Test setdefault
t = collections.UserDict()
self.assertEqual(t.setdefault("x", 42), 42)
self.assertIn("x", t)
self.assertEqual(t.setdefault("x", 23), 42)
# Test pop
t = collections.UserDict(x=42)
self.assertEqual(t.pop("x"), 42)
self.assertRaises(KeyError, t.pop, "x")
self.assertEqual(t.pop("x", 1), 1)
t["x"] = 42
self.assertEqual(t.pop("x", 1), 42)
# Test popitem
t = collections.UserDict(x=42)
self.assertEqual(t.popitem(), ("x", 42))
self.assertRaises(KeyError, t.popitem)
def test_init(self):
for kw in 'self', 'other', 'iterable':
self.assertEqual(list(collections.UserDict(**{kw: 42}).items()),
[(kw, 42)])
self.assertEqual(list(collections.UserDict({}, dict=42).items()),
[('dict', 42)])
self.assertEqual(list(collections.UserDict({}, dict=None).items()),
[('dict', None)])
with self.assertWarnsRegex(DeprecationWarning, "'dict'"):
self.assertEqual(list(collections.UserDict(dict={'a': 42}).items()),
[('a', 42)])
self.assertRaises(TypeError, collections.UserDict, 42)
self.assertRaises(TypeError, collections.UserDict, (), ())
self.assertRaises(TypeError, collections.UserDict.__init__)
def test_update(self):
for kw in 'self', 'dict', 'other', 'iterable':
d = collections.UserDict()
d.update(**{kw: 42})
self.assertEqual(list(d.items()), [(kw, 42)])
self.assertRaises(TypeError, collections.UserDict().update, 42)
self.assertRaises(TypeError, collections.UserDict().update, {}, {})
self.assertRaises(TypeError, collections.UserDict.update)
def test_missing(self):
# Make sure UserDict doesn't have a __missing__ method
self.assertEqual(hasattr(collections.UserDict, "__missing__"), False)
# Test several cases:
# (D) subclass defines __missing__ method returning a value
# (E) subclass defines __missing__ method raising RuntimeError
# (F) subclass sets __missing__ instance variable (no effect)
# (G) subclass doesn't define __missing__ at all
class D(collections.UserDict):
def __missing__(self, key):
return 42
d = D({1: 2, 3: 4})
self.assertEqual(d[1], 2)
self.assertEqual(d[3], 4)
self.assertNotIn(2, d)
self.assertNotIn(2, d.keys())
self.assertEqual(d[2], 42)
class E(collections.UserDict):
def __missing__(self, key):
raise RuntimeError(key)
e = E()
try:
e[42]
except RuntimeError as err:
self.assertEqual(err.args, (42,))
else:
self.fail("e[42] didn't raise RuntimeError")
class F(collections.UserDict):
def __init__(self):
# An instance variable __missing__ should have no effect
self.__missing__ = lambda key: None
collections.UserDict.__init__(self)
f = F()
try:
f[42]
except KeyError as err:
self.assertEqual(err.args, (42,))
else:
self.fail("f[42] didn't raise KeyError")
class G(collections.UserDict):
pass
g = G()
try:
g[42]
except KeyError as err:
self.assertEqual(err.args, (42,))
else:
self.fail("g[42] didn't raise KeyError")
if __name__ == "__main__":
unittest.main()
| 7,821 | 221 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_file.py | import sys
import os
import unittest
from array import array
from weakref import proxy
import io
import _pyio as pyio
from test.support import TESTFN
from test import support
from collections import UserList
class AutoFileTests:
# file tests for which a test file is automatically set up
def setUp(self):
self.f = self.open(TESTFN, 'wb')
def tearDown(self):
if self.f:
self.f.close()
support.unlink(TESTFN)
def testWeakRefs(self):
# verify weak references
p = proxy(self.f)
p.write(b'teststring')
self.assertEqual(self.f.tell(), p.tell())
self.f.close()
self.f = None
self.assertRaises(ReferenceError, getattr, p, 'tell')
def testAttributes(self):
# verify expected attributes exist
f = self.f
f.name # merely shouldn't blow up
f.mode # ditto
f.closed # ditto
def testReadinto(self):
# verify readinto
self.f.write(b'12')
self.f.close()
a = array('b', b'x'*10)
self.f = self.open(TESTFN, 'rb')
n = self.f.readinto(a)
self.assertEqual(b'12', a.tobytes()[:n])
def testReadinto_text(self):
# verify readinto refuses text files
a = array('b', b'x'*10)
self.f.close()
self.f = self.open(TESTFN, 'r')
if hasattr(self.f, "readinto"):
self.assertRaises(TypeError, self.f.readinto, a)
def testWritelinesUserList(self):
# verify writelines with instance sequence
l = UserList([b'1', b'2'])
self.f.writelines(l)
self.f.close()
self.f = self.open(TESTFN, 'rb')
buf = self.f.read()
self.assertEqual(buf, b'12')
def testWritelinesIntegers(self):
# verify writelines with integers
self.assertRaises(TypeError, self.f.writelines, [1, 2, 3])
def testWritelinesIntegersUserList(self):
# verify writelines with integers in UserList
l = UserList([1,2,3])
self.assertRaises(TypeError, self.f.writelines, l)
def testWritelinesNonString(self):
# verify writelines with non-string object
class NonString:
pass
self.assertRaises(TypeError, self.f.writelines,
[NonString(), NonString()])
def testErrors(self):
f = self.f
self.assertEqual(f.name, TESTFN)
self.assertFalse(f.isatty())
self.assertFalse(f.closed)
if hasattr(f, "readinto"):
self.assertRaises((OSError, TypeError), f.readinto, "")
f.close()
self.assertTrue(f.closed)
def testMethods(self):
methods = [('fileno', ()),
('flush', ()),
('isatty', ()),
('__next__', ()),
('read', ()),
('write', (b"",)),
('readline', ()),
('readlines', ()),
('seek', (0,)),
('tell', ()),
('write', (b"",)),
('writelines', ([],)),
('__iter__', ()),
]
methods.append(('truncate', ()))
# __exit__ should close the file
self.f.__exit__(None, None, None)
self.assertTrue(self.f.closed)
for methodname, args in methods:
method = getattr(self.f, methodname)
# should raise on closed file
self.assertRaises(ValueError, method, *args)
# file is closed, __exit__ shouldn't do anything
self.assertEqual(self.f.__exit__(None, None, None), None)
# it must also return None if an exception was given
try:
1/0
except:
self.assertEqual(self.f.__exit__(*sys.exc_info()), None)
def testReadWhenWriting(self):
self.assertRaises(OSError, self.f.read)
class CAutoFileTests(AutoFileTests, unittest.TestCase):
open = io.open
class PyAutoFileTests(AutoFileTests, unittest.TestCase):
open = staticmethod(pyio.open)
class OtherFileTests:
def tearDown(self):
support.unlink(TESTFN)
def testModeStrings(self):
# check invalid mode strings
self.open(TESTFN, 'wb').close()
for mode in ("", "aU", "wU+", "U+", "+U", "rU+"):
try:
f = self.open(TESTFN, mode)
except ValueError:
pass
else:
f.close()
self.fail('%r is an invalid file mode' % mode)
def testBadModeArgument(self):
# verify that we get a sensible error message for bad mode argument
bad_mode = "qwerty"
try:
f = self.open(TESTFN, bad_mode)
except ValueError as msg:
if msg.args[0] != 0:
s = str(msg)
if TESTFN in s or bad_mode not in s:
self.fail("bad error message for invalid mode: %s" % s)
# if msg.args[0] == 0, we're probably on Windows where there may be
# no obvious way to discover why open() failed.
else:
f.close()
self.fail("no error for invalid mode: %s" % bad_mode)
def testSetBufferSize(self):
# make sure that explicitly setting the buffer size doesn't cause
# misbehaviour especially with repeated close() calls
for s in (-1, 0, 1, 512):
try:
f = self.open(TESTFN, 'wb', s)
f.write(str(s).encode("ascii"))
f.close()
f.close()
f = self.open(TESTFN, 'rb', s)
d = int(f.read().decode("ascii"))
f.close()
f.close()
except OSError as msg:
self.fail('error setting buffer size %d: %s' % (s, str(msg)))
self.assertEqual(d, s)
def testTruncateOnWindows(self):
# SF bug <http://www.python.org/sf/801631>
# "file.truncate fault on windows"
f = self.open(TESTFN, 'wb')
try:
f.write(b'12345678901') # 11 bytes
f.close()
f = self.open(TESTFN,'rb+')
data = f.read(5)
if data != b'12345':
self.fail("Read on file opened for update failed %r" % data)
if f.tell() != 5:
self.fail("File pos after read wrong %d" % f.tell())
f.truncate()
if f.tell() != 5:
self.fail("File pos after ftruncate wrong %d" % f.tell())
f.close()
size = os.path.getsize(TESTFN)
if size != 5:
self.fail("File size after ftruncate wrong %d" % size)
finally:
f.close()
def testIteration(self):
# Test the complex interaction when mixing file-iteration and the
# various read* methods.
dataoffset = 16384
filler = b"ham\n"
assert not dataoffset % len(filler), \
"dataoffset must be multiple of len(filler)"
nchunks = dataoffset // len(filler)
testlines = [
b"spam, spam and eggs\n",
b"eggs, spam, ham and spam\n",
b"saussages, spam, spam and eggs\n",
b"spam, ham, spam and eggs\n",
b"spam, spam, spam, spam, spam, ham, spam\n",
b"wonderful spaaaaaam.\n"
]
methods = [("readline", ()), ("read", ()), ("readlines", ()),
("readinto", (array("b", b" "*100),))]
# Prepare the testfile
bag = self.open(TESTFN, "wb")
bag.write(filler * nchunks)
bag.writelines(testlines)
bag.close()
# Test for appropriate errors mixing read* and iteration
for methodname, args in methods:
f = self.open(TESTFN, 'rb')
self.assertEqual(next(f), filler)
meth = getattr(f, methodname)
meth(*args) # This simply shouldn't fail
f.close()
# Test to see if harmless (by accident) mixing of read* and
# iteration still works. This depends on the size of the internal
# iteration buffer (currently 8192,) but we can test it in a
# flexible manner. Each line in the bag o' ham is 4 bytes
# ("h", "a", "m", "\n"), so 4096 lines of that should get us
# exactly on the buffer boundary for any power-of-2 buffersize
# between 4 and 16384 (inclusive).
f = self.open(TESTFN, 'rb')
for i in range(nchunks):
next(f)
testline = testlines.pop(0)
try:
line = f.readline()
except ValueError:
self.fail("readline() after next() with supposedly empty "
"iteration-buffer failed anyway")
if line != testline:
self.fail("readline() after next() with empty buffer "
"failed. Got %r, expected %r" % (line, testline))
testline = testlines.pop(0)
buf = array("b", b"\x00" * len(testline))
try:
f.readinto(buf)
except ValueError:
self.fail("readinto() after next() with supposedly empty "
"iteration-buffer failed anyway")
line = buf.tobytes()
if line != testline:
self.fail("readinto() after next() with empty buffer "
"failed. Got %r, expected %r" % (line, testline))
testline = testlines.pop(0)
try:
line = f.read(len(testline))
except ValueError:
self.fail("read() after next() with supposedly empty "
"iteration-buffer failed anyway")
if line != testline:
self.fail("read() after next() with empty buffer "
"failed. Got %r, expected %r" % (line, testline))
try:
lines = f.readlines()
except ValueError:
self.fail("readlines() after next() with supposedly empty "
"iteration-buffer failed anyway")
if lines != testlines:
self.fail("readlines() after next() with empty buffer "
"failed. Got %r, expected %r" % (line, testline))
f.close()
# Reading after iteration hit EOF shouldn't hurt either
f = self.open(TESTFN, 'rb')
try:
for line in f:
pass
try:
f.readline()
f.readinto(buf)
f.read()
f.readlines()
except ValueError:
self.fail("read* failed after next() consumed file")
finally:
f.close()
class COtherFileTests(OtherFileTests, unittest.TestCase):
open = io.open
class PyOtherFileTests(OtherFileTests, unittest.TestCase):
open = staticmethod(pyio.open)
if __name__ == '__main__':
unittest.main()
| 10,868 | 323 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_devpoll.py | # Test case for the select.devpoll() function
# Initial tests are copied as is from "test_poll.py"
import os
import random
import select
import unittest
from test.support import run_unittest, cpython_only
if not hasattr(select, 'devpoll') :
raise unittest.SkipTest('test works only on Solaris OS family')
def find_ready_matching(ready, flag):
match = []
for fd, mode in ready:
if mode & flag:
match.append(fd)
return match
class DevPollTests(unittest.TestCase):
def test_devpoll1(self):
# Basic functional test of poll object
# Create a bunch of pipe and test that poll works with them.
p = select.devpoll()
NUM_PIPES = 12
MSG = b" This is a test."
MSG_LEN = len(MSG)
readers = []
writers = []
r2w = {}
w2r = {}
for i in range(NUM_PIPES):
rd, wr = os.pipe()
p.register(rd)
p.modify(rd, select.POLLIN)
p.register(wr, select.POLLOUT)
readers.append(rd)
writers.append(wr)
r2w[rd] = wr
w2r[wr] = rd
bufs = []
while writers:
ready = p.poll()
ready_writers = find_ready_matching(ready, select.POLLOUT)
if not ready_writers:
self.fail("no pipes ready for writing")
wr = random.choice(ready_writers)
os.write(wr, MSG)
ready = p.poll()
ready_readers = find_ready_matching(ready, select.POLLIN)
if not ready_readers:
self.fail("no pipes ready for reading")
self.assertEqual([w2r[wr]], ready_readers)
rd = ready_readers[0]
buf = os.read(rd, MSG_LEN)
self.assertEqual(len(buf), MSG_LEN)
bufs.append(buf)
os.close(r2w[rd]) ; os.close(rd)
p.unregister(r2w[rd])
p.unregister(rd)
writers.remove(r2w[rd])
self.assertEqual(bufs, [MSG] * NUM_PIPES)
def test_timeout_overflow(self):
pollster = select.devpoll()
w, r = os.pipe()
pollster.register(w)
pollster.poll(-1)
self.assertRaises(OverflowError, pollster.poll, -2)
self.assertRaises(OverflowError, pollster.poll, -1 << 31)
self.assertRaises(OverflowError, pollster.poll, -1 << 64)
pollster.poll(0)
pollster.poll(1)
pollster.poll(1 << 30)
self.assertRaises(OverflowError, pollster.poll, 1 << 31)
self.assertRaises(OverflowError, pollster.poll, 1 << 63)
self.assertRaises(OverflowError, pollster.poll, 1 << 64)
def test_close(self):
open_file = open(__file__, "rb")
self.addCleanup(open_file.close)
fd = open_file.fileno()
devpoll = select.devpoll()
# test fileno() method and closed attribute
self.assertIsInstance(devpoll.fileno(), int)
self.assertFalse(devpoll.closed)
# test close()
devpoll.close()
self.assertTrue(devpoll.closed)
self.assertRaises(ValueError, devpoll.fileno)
# close() can be called more than once
devpoll.close()
# operations must fail with ValueError("I/O operation on closed ...")
self.assertRaises(ValueError, devpoll.modify, fd, select.POLLIN)
self.assertRaises(ValueError, devpoll.poll)
self.assertRaises(ValueError, devpoll.register, fd, fd, select.POLLIN)
self.assertRaises(ValueError, devpoll.unregister, fd)
def test_fd_non_inheritable(self):
devpoll = select.devpoll()
self.addCleanup(devpoll.close)
self.assertEqual(os.get_inheritable(devpoll.fileno()), False)
def test_events_mask_overflow(self):
pollster = select.devpoll()
w, r = os.pipe()
pollster.register(w)
# Issue #17919
self.assertRaises(OverflowError, pollster.register, 0, -1)
self.assertRaises(OverflowError, pollster.register, 0, 1 << 64)
self.assertRaises(OverflowError, pollster.modify, 1, -1)
self.assertRaises(OverflowError, pollster.modify, 1, 1 << 64)
@cpython_only
def test_events_mask_overflow_c_limits(self):
from _testcapi import USHRT_MAX
pollster = select.devpoll()
w, r = os.pipe()
pollster.register(w)
# Issue #17919
self.assertRaises(OverflowError, pollster.register, 0, USHRT_MAX + 1)
self.assertRaises(OverflowError, pollster.modify, 1, USHRT_MAX + 1)
def test_main():
run_unittest(DevPollTests)
if __name__ == '__main__':
test_main()
| 4,618 | 146 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_multiprocessing_forkserver.py | import unittest
import test._test_multiprocessing
import sys
from test import support
if support.PGO:
raise unittest.SkipTest("test is not helpful for PGO")
if sys.platform == "win32":
raise unittest.SkipTest("forkserver is not available on Windows")
test._test_multiprocessing.install_tests_in_module_dict(globals(), 'forkserver')
if __name__ == '__main__':
unittest.main()
| 392 | 17 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/empty.vbs | 'Empty VBS file, does nothing. Helper for Lib\test\test_startfile.py. | 70 | 1 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_shlex.py | import io
import shlex
import string
import unittest
# The original test data set was from shellwords, by Hartmut Goebel.
data = r"""x|x|
foo bar|foo|bar|
foo bar|foo|bar|
foo bar |foo|bar|
foo bar bla fasel|foo|bar|bla|fasel|
x y z xxxx|x|y|z|xxxx|
\x bar|\|x|bar|
\ x bar|\|x|bar|
\ bar|\|bar|
foo \x bar|foo|\|x|bar|
foo \ x bar|foo|\|x|bar|
foo \ bar|foo|\|bar|
foo "bar" bla|foo|"bar"|bla|
"foo" "bar" "bla"|"foo"|"bar"|"bla"|
"foo" bar "bla"|"foo"|bar|"bla"|
"foo" bar bla|"foo"|bar|bla|
foo 'bar' bla|foo|'bar'|bla|
'foo' 'bar' 'bla'|'foo'|'bar'|'bla'|
'foo' bar 'bla'|'foo'|bar|'bla'|
'foo' bar bla|'foo'|bar|bla|
blurb foo"bar"bar"fasel" baz|blurb|foo"bar"bar"fasel"|baz|
blurb foo'bar'bar'fasel' baz|blurb|foo'bar'bar'fasel'|baz|
""|""|
''|''|
foo "" bar|foo|""|bar|
foo '' bar|foo|''|bar|
foo "" "" "" bar|foo|""|""|""|bar|
foo '' '' '' bar|foo|''|''|''|bar|
\""|\|""|
"\"|"\"|
"foo\ bar"|"foo\ bar"|
"foo\\ bar"|"foo\\ bar"|
"foo\\ bar\"|"foo\\ bar\"|
"foo\\" bar\""|"foo\\"|bar|\|""|
"foo\\ bar\" dfadf"|"foo\\ bar\"|dfadf"|
"foo\\\ bar\" dfadf"|"foo\\\ bar\"|dfadf"|
"foo\\\x bar\" dfadf"|"foo\\\x bar\"|dfadf"|
"foo\x bar\" dfadf"|"foo\x bar\"|dfadf"|
\''|\|''|
'foo\ bar'|'foo\ bar'|
'foo\\ bar'|'foo\\ bar'|
"foo\\\x bar\" df'a\ 'df'|"foo\\\x bar\"|df'a|\|'df'|
\"foo"|\|"foo"|
\"foo"\x|\|"foo"|\|x|
"foo\x"|"foo\x"|
"foo\ "|"foo\ "|
foo\ xx|foo|\|xx|
foo\ x\x|foo|\|x|\|x|
foo\ x\x\""|foo|\|x|\|x|\|""|
"foo\ x\x"|"foo\ x\x"|
"foo\ x\x\\"|"foo\ x\x\\"|
"foo\ x\x\\""foobar"|"foo\ x\x\\"|"foobar"|
"foo\ x\x\\"\''"foobar"|"foo\ x\x\\"|\|''|"foobar"|
"foo\ x\x\\"\'"fo'obar"|"foo\ x\x\\"|\|'"fo'|obar"|
"foo\ x\x\\"\'"fo'obar" 'don'\''t'|"foo\ x\x\\"|\|'"fo'|obar"|'don'|\|''|t'|
'foo\ bar'|'foo\ bar'|
'foo\\ bar'|'foo\\ bar'|
foo\ bar|foo|\|bar|
foo#bar\nbaz|foobaz|
:-) ;-)|:|-|)|;|-|)|
áéÃóú|á|é|Ã|ó|ú|
"""
posix_data = r"""x|x|
foo bar|foo|bar|
foo bar|foo|bar|
foo bar |foo|bar|
foo bar bla fasel|foo|bar|bla|fasel|
x y z xxxx|x|y|z|xxxx|
\x bar|x|bar|
\ x bar| x|bar|
\ bar| bar|
foo \x bar|foo|x|bar|
foo \ x bar|foo| x|bar|
foo \ bar|foo| bar|
foo "bar" bla|foo|bar|bla|
"foo" "bar" "bla"|foo|bar|bla|
"foo" bar "bla"|foo|bar|bla|
"foo" bar bla|foo|bar|bla|
foo 'bar' bla|foo|bar|bla|
'foo' 'bar' 'bla'|foo|bar|bla|
'foo' bar 'bla'|foo|bar|bla|
'foo' bar bla|foo|bar|bla|
blurb foo"bar"bar"fasel" baz|blurb|foobarbarfasel|baz|
blurb foo'bar'bar'fasel' baz|blurb|foobarbarfasel|baz|
""||
''||
foo "" bar|foo||bar|
foo '' bar|foo||bar|
foo "" "" "" bar|foo||||bar|
foo '' '' '' bar|foo||||bar|
\"|"|
"\""|"|
"foo\ bar"|foo\ bar|
"foo\\ bar"|foo\ bar|
"foo\\ bar\""|foo\ bar"|
"foo\\" bar\"|foo\|bar"|
"foo\\ bar\" dfadf"|foo\ bar" dfadf|
"foo\\\ bar\" dfadf"|foo\\ bar" dfadf|
"foo\\\x bar\" dfadf"|foo\\x bar" dfadf|
"foo\x bar\" dfadf"|foo\x bar" dfadf|
\'|'|
'foo\ bar'|foo\ bar|
'foo\\ bar'|foo\\ bar|
"foo\\\x bar\" df'a\ 'df"|foo\\x bar" df'a\ 'df|
\"foo|"foo|
\"foo\x|"foox|
"foo\x"|foo\x|
"foo\ "|foo\ |
foo\ xx|foo xx|
foo\ x\x|foo xx|
foo\ x\x\"|foo xx"|
"foo\ x\x"|foo\ x\x|
"foo\ x\x\\"|foo\ x\x\|
"foo\ x\x\\""foobar"|foo\ x\x\foobar|
"foo\ x\x\\"\'"foobar"|foo\ x\x\'foobar|
"foo\ x\x\\"\'"fo'obar"|foo\ x\x\'fo'obar|
"foo\ x\x\\"\'"fo'obar" 'don'\''t'|foo\ x\x\'fo'obar|don't|
"foo\ x\x\\"\'"fo'obar" 'don'\''t' \\|foo\ x\x\'fo'obar|don't|\|
'foo\ bar'|foo\ bar|
'foo\\ bar'|foo\\ bar|
foo\ bar|foo bar|
foo#bar\nbaz|foo|baz|
:-) ;-)|:-)|;-)|
áéÃóú|áéÃóú|
"""
class ShlexTest(unittest.TestCase):
def setUp(self):
self.data = [x.split("|")[:-1]
for x in data.splitlines()]
self.posix_data = [x.split("|")[:-1]
for x in posix_data.splitlines()]
for item in self.data:
item[0] = item[0].replace(r"\n", "\n")
for item in self.posix_data:
item[0] = item[0].replace(r"\n", "\n")
def splitTest(self, data, comments):
for i in range(len(data)):
l = shlex.split(data[i][0], comments=comments)
self.assertEqual(l, data[i][1:],
"%s: %s != %s" %
(data[i][0], l, data[i][1:]))
def oldSplit(self, s):
ret = []
lex = shlex.shlex(io.StringIO(s))
tok = lex.get_token()
while tok:
ret.append(tok)
tok = lex.get_token()
return ret
def testSplitPosix(self):
"""Test data splitting with posix parser"""
self.splitTest(self.posix_data, comments=True)
def testCompat(self):
"""Test compatibility interface"""
for i in range(len(self.data)):
l = self.oldSplit(self.data[i][0])
self.assertEqual(l, self.data[i][1:],
"%s: %s != %s" %
(self.data[i][0], l, self.data[i][1:]))
def testSyntaxSplitAmpersandAndPipe(self):
"""Test handling of syntax splitting of &, |"""
# Could take these forms: &&, &, |&, ;&, ;;&
# of course, the same applies to | and ||
# these should all parse to the same output
for delimiter in ('&&', '&', '|&', ';&', ';;&',
'||', '|', '&|', ';|', ';;|'):
src = ['echo hi %s echo bye' % delimiter,
'echo hi%secho bye' % delimiter]
ref = ['echo', 'hi', delimiter, 'echo', 'bye']
for ss in src:
s = shlex.shlex(ss, punctuation_chars=True)
result = list(s)
self.assertEqual(ref, result, "While splitting '%s'" % ss)
def testSyntaxSplitSemicolon(self):
"""Test handling of syntax splitting of ;"""
# Could take these forms: ;, ;;, ;&, ;;&
# these should all parse to the same output
for delimiter in (';', ';;', ';&', ';;&'):
src = ['echo hi %s echo bye' % delimiter,
'echo hi%s echo bye' % delimiter,
'echo hi%secho bye' % delimiter]
ref = ['echo', 'hi', delimiter, 'echo', 'bye']
for ss in src:
s = shlex.shlex(ss, punctuation_chars=True)
result = list(s)
self.assertEqual(ref, result, "While splitting '%s'" % ss)
def testSyntaxSplitRedirect(self):
"""Test handling of syntax splitting of >"""
# of course, the same applies to <, |
# these should all parse to the same output
for delimiter in ('<', '|'):
src = ['echo hi %s out' % delimiter,
'echo hi%s out' % delimiter,
'echo hi%sout' % delimiter]
ref = ['echo', 'hi', delimiter, 'out']
for ss in src:
s = shlex.shlex(ss, punctuation_chars=True)
result = list(s)
self.assertEqual(ref, result, "While splitting '%s'" % ss)
def testSyntaxSplitParen(self):
"""Test handling of syntax splitting of ()"""
# these should all parse to the same output
src = ['( echo hi )',
'(echo hi)']
ref = ['(', 'echo', 'hi', ')']
for ss in src:
s = shlex.shlex(ss, punctuation_chars=True)
result = list(s)
self.assertEqual(ref, result, "While splitting '%s'" % ss)
def testSyntaxSplitCustom(self):
"""Test handling of syntax splitting with custom chars"""
ref = ['~/a', '&', '&', 'b-c', '--color=auto', '||', 'd', '*.py?']
ss = "~/a && b-c --color=auto || d *.py?"
s = shlex.shlex(ss, punctuation_chars="|")
result = list(s)
self.assertEqual(ref, result, "While splitting '%s'" % ss)
def testTokenTypes(self):
"""Test that tokens are split with types as expected."""
for source, expected in (
('a && b || c',
[('a', 'a'), ('&&', 'c'), ('b', 'a'),
('||', 'c'), ('c', 'a')]),
):
s = shlex.shlex(source, punctuation_chars=True)
observed = []
while True:
t = s.get_token()
if t == s.eof:
break
if t[0] in s.punctuation_chars:
tt = 'c'
else:
tt = 'a'
observed.append((t, tt))
self.assertEqual(observed, expected)
def testPunctuationInWordChars(self):
"""Test that any punctuation chars are removed from wordchars"""
s = shlex.shlex('a_b__c', punctuation_chars='_')
self.assertNotIn('_', s.wordchars)
self.assertEqual(list(s), ['a', '_', 'b', '__', 'c'])
def testPunctuationWithWhitespaceSplit(self):
"""Test that with whitespace_split, behaviour is as expected"""
s = shlex.shlex('a && b || c', punctuation_chars='&')
# whitespace_split is False, so splitting will be based on
# punctuation_chars
self.assertEqual(list(s), ['a', '&&', 'b', '|', '|', 'c'])
s = shlex.shlex('a && b || c', punctuation_chars='&')
s.whitespace_split = True
# whitespace_split is True, so splitting will be based on
# white space
self.assertEqual(list(s), ['a', '&&', 'b', '||', 'c'])
def testPunctuationWithPosix(self):
"""Test that punctuation_chars and posix behave correctly together."""
# see Issue #29132
s = shlex.shlex('f >"abc"', posix=True, punctuation_chars=True)
self.assertEqual(list(s), ['f', '>', 'abc'])
s = shlex.shlex('f >\\"abc\\"', posix=True, punctuation_chars=True)
self.assertEqual(list(s), ['f', '>', '"abc"'])
def testEmptyStringHandling(self):
"""Test that parsing of empty strings is correctly handled."""
# see Issue #21999
expected = ['', ')', 'abc']
for punct in (False, True):
s = shlex.shlex("'')abc", posix=True, punctuation_chars=punct)
slist = list(s)
self.assertEqual(slist, expected)
expected = ["''", ')', 'abc']
s = shlex.shlex("'')abc", punctuation_chars=True)
self.assertEqual(list(s), expected)
def testQuote(self):
safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./'
unicode_sample = '\xe9\xe0\xdf' # e + acute accent, a + grave, sharp s
unsafe = '"`$\\!' + unicode_sample
self.assertEqual(shlex.quote(''), "''")
self.assertEqual(shlex.quote(safeunquoted), safeunquoted)
self.assertEqual(shlex.quote('test file name'), "'test file name'")
for u in unsafe:
self.assertEqual(shlex.quote('test%sname' % u),
"'test%sname'" % u)
for u in unsafe:
self.assertEqual(shlex.quote("test%s'name'" % u),
"'test%s'\"'\"'name'\"'\"''" % u)
# Allow this test to be used with old shlex.py
if not getattr(shlex, "split", None):
for methname in dir(ShlexTest):
if methname.startswith("test") and methname != "testCompat":
delattr(ShlexTest, methname)
if __name__ == "__main__":
unittest.main()
| 11,179 | 319 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_urllib2.py | import unittest
from test import support
from test import test_urllib
import os
import io
import socket
import array
import sys
import tempfile
import subprocess
import urllib.request
# The proxy bypass method imported below has logic specific to the OSX
# proxy config data structure but is testable on all platforms.
from urllib.request import (Request, OpenerDirector, HTTPBasicAuthHandler,
HTTPPasswordMgrWithPriorAuth, _parse_proxy,
_proxy_bypass_macosx_sysconf,
AbstractDigestAuthHandler)
from urllib.parse import urlparse
import urllib.error
import http.client
# XXX
# Request
# CacheFTPHandler (hard to write)
# parse_keqv_list, parse_http_list, HTTPDigestAuthHandler
class TrivialTests(unittest.TestCase):
def test___all__(self):
# Verify which names are exposed
for module in 'request', 'response', 'parse', 'error', 'robotparser':
context = {}
exec('from urllib.%s import *' % module, context)
del context['__builtins__']
if module == 'request' and os.name == 'nt':
u, p = context.pop('url2pathname'), context.pop('pathname2url')
self.assertEqual(u.__module__, 'nturl2path')
self.assertEqual(p.__module__, 'nturl2path')
for k, v in context.items():
self.assertEqual(v.__module__, 'urllib.%s' % module,
"%r is exposed in 'urllib.%s' but defined in %r" %
(k, module, v.__module__))
def test_trivial(self):
# A couple trivial tests
self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url')
# XXX Name hacking to get this to work on Windows.
fname = os.path.abspath(urllib.request.__file__).replace(os.sep, '/')
if os.name == 'nt':
file_url = "file:///%s" % fname
else:
file_url = "file://%s" % fname
f = urllib.request.urlopen(file_url)
f.read()
f.close()
def test_parse_http_list(self):
tests = [
('a,b,c', ['a', 'b', 'c']),
('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']),
('a, b, "c", "d", "e,f", g, h',
['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']),
('a="b\\"c", d="e\\,f", g="h\\\\i"',
['a="b"c"', 'd="e,f"', 'g="h\\i"'])]
for string, list in tests:
self.assertEqual(urllib.request.parse_http_list(string), list)
def test_URLError_reasonstr(self):
err = urllib.error.URLError('reason')
self.assertIn(err.reason, str(err))
class RequestHdrsTests(unittest.TestCase):
def test_request_headers_dict(self):
"""
The Request.headers dictionary is not a documented interface. It
should stay that way, because the complete set of headers are only
accessible through the .get_header(), .has_header(), .header_items()
interface. However, .headers pre-dates those methods, and so real code
will be using the dictionary.
The introduction in 2.4 of those methods was a mistake for the same
reason: code that previously saw all (urllib2 user)-provided headers in
.headers now sees only a subset.
"""
url = "http://example.com"
self.assertEqual(Request(url,
headers={"Spam-eggs": "blah"}
).headers["Spam-eggs"], "blah")
self.assertEqual(Request(url,
headers={"spam-EggS": "blah"}
).headers["Spam-eggs"], "blah")
def test_request_headers_methods(self):
"""
Note the case normalization of header names here, to
.capitalize()-case. This should be preserved for
backwards-compatibility. (In the HTTP case, normalization to
.title()-case is done by urllib2 before sending headers to
http.client).
Note that e.g. r.has_header("spam-EggS") is currently False, and
r.get_header("spam-EggS") returns None, but that could be changed in
future.
Method r.remove_header should remove items both from r.headers and
r.unredirected_hdrs dictionaries
"""
url = "http://example.com"
req = Request(url, headers={"Spam-eggs": "blah"})
self.assertTrue(req.has_header("Spam-eggs"))
self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')])
req.add_header("Foo-Bar", "baz")
self.assertEqual(sorted(req.header_items()),
[('Foo-bar', 'baz'), ('Spam-eggs', 'blah')])
self.assertFalse(req.has_header("Not-there"))
self.assertIsNone(req.get_header("Not-there"))
self.assertEqual(req.get_header("Not-there", "default"), "default")
req.remove_header("Spam-eggs")
self.assertFalse(req.has_header("Spam-eggs"))
req.add_unredirected_header("Unredirected-spam", "Eggs")
self.assertTrue(req.has_header("Unredirected-spam"))
req.remove_header("Unredirected-spam")
self.assertFalse(req.has_header("Unredirected-spam"))
def test_password_manager(self):
mgr = urllib.request.HTTPPasswordMgr()
add = mgr.add_password
find_user_pass = mgr.find_user_password
add("Some Realm", "http://example.com/", "joe", "password")
add("Some Realm", "http://example.com/ni", "ni", "ni")
add("Some Realm", "http://c.example.com:3128", "3", "c")
add("Some Realm", "d.example.com", "4", "d")
add("Some Realm", "e.example.com:3128", "5", "e")
# For the same realm, password set the highest path is the winner.
self.assertEqual(find_user_pass("Some Realm", "example.com"),
('joe', 'password'))
self.assertEqual(find_user_pass("Some Realm", "http://example.com/ni"),
('joe', 'password'))
self.assertEqual(find_user_pass("Some Realm", "http://example.com"),
('joe', 'password'))
self.assertEqual(find_user_pass("Some Realm", "http://example.com/"),
('joe', 'password'))
self.assertEqual(find_user_pass("Some Realm",
"http://example.com/spam"),
('joe', 'password'))
self.assertEqual(find_user_pass("Some Realm",
"http://example.com/spam/spam"),
('joe', 'password'))
# You can have different passwords for different paths.
add("c", "http://example.com/foo", "foo", "ni")
add("c", "http://example.com/bar", "bar", "nini")
self.assertEqual(find_user_pass("c", "http://example.com/foo"),
('foo', 'ni'))
self.assertEqual(find_user_pass("c", "http://example.com/bar"),
('bar', 'nini'))
# For the same path, newer password should be considered.
add("b", "http://example.com/", "first", "blah")
add("b", "http://example.com/", "second", "spam")
self.assertEqual(find_user_pass("b", "http://example.com/"),
('second', 'spam'))
# No special relationship between a.example.com and example.com:
add("a", "http://example.com", "1", "a")
self.assertEqual(find_user_pass("a", "http://example.com/"),
('1', 'a'))
self.assertEqual(find_user_pass("a", "http://a.example.com/"),
(None, None))
# Ports:
self.assertEqual(find_user_pass("Some Realm", "c.example.com"),
(None, None))
self.assertEqual(find_user_pass("Some Realm", "c.example.com:3128"),
('3', 'c'))
self.assertEqual(
find_user_pass("Some Realm", "http://c.example.com:3128"),
('3', 'c'))
self.assertEqual(find_user_pass("Some Realm", "d.example.com"),
('4', 'd'))
self.assertEqual(find_user_pass("Some Realm", "e.example.com:3128"),
('5', 'e'))
def test_password_manager_default_port(self):
"""
The point to note here is that we can't guess the default port if
there's no scheme. This applies to both add_password and
find_user_password.
"""
mgr = urllib.request.HTTPPasswordMgr()
add = mgr.add_password
find_user_pass = mgr.find_user_password
add("f", "http://g.example.com:80", "10", "j")
add("g", "http://h.example.com", "11", "k")
add("h", "i.example.com:80", "12", "l")
add("i", "j.example.com", "13", "m")
self.assertEqual(find_user_pass("f", "g.example.com:100"),
(None, None))
self.assertEqual(find_user_pass("f", "g.example.com:80"),
('10', 'j'))
self.assertEqual(find_user_pass("f", "g.example.com"),
(None, None))
self.assertEqual(find_user_pass("f", "http://g.example.com:100"),
(None, None))
self.assertEqual(find_user_pass("f", "http://g.example.com:80"),
('10', 'j'))
self.assertEqual(find_user_pass("f", "http://g.example.com"),
('10', 'j'))
self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k'))
self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k'))
self.assertEqual(find_user_pass("g", "http://h.example.com:80"),
('11', 'k'))
self.assertEqual(find_user_pass("h", "i.example.com"), (None, None))
self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l'))
self.assertEqual(find_user_pass("h", "http://i.example.com:80"),
('12', 'l'))
self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm'))
self.assertEqual(find_user_pass("i", "j.example.com:80"),
(None, None))
self.assertEqual(find_user_pass("i", "http://j.example.com"),
('13', 'm'))
self.assertEqual(find_user_pass("i", "http://j.example.com:80"),
(None, None))
class MockOpener:
addheaders = []
def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
self.req, self.data, self.timeout = req, data, timeout
def error(self, proto, *args):
self.proto, self.args = proto, args
class MockFile:
def read(self, count=None):
pass
def readline(self, count=None):
pass
def close(self):
pass
class MockHeaders(dict):
def getheaders(self, name):
return list(self.values())
class MockResponse(io.StringIO):
def __init__(self, code, msg, headers, data, url=None):
io.StringIO.__init__(self, data)
self.code, self.msg, self.headers, self.url = code, msg, headers, url
def info(self):
return self.headers
def geturl(self):
return self.url
class MockCookieJar:
def add_cookie_header(self, request):
self.ach_req = request
def extract_cookies(self, response, request):
self.ec_req, self.ec_r = request, response
class FakeMethod:
def __init__(self, meth_name, action, handle):
self.meth_name = meth_name
self.handle = handle
self.action = action
def __call__(self, *args):
return self.handle(self.meth_name, self.action, *args)
class MockHTTPResponse(io.IOBase):
def __init__(self, fp, msg, status, reason):
self.fp = fp
self.msg = msg
self.status = status
self.reason = reason
self.code = 200
def read(self):
return ''
def info(self):
return {}
def geturl(self):
return self.url
class MockHTTPClass:
def __init__(self):
self.level = 0
self.req_headers = []
self.data = None
self.raise_on_endheaders = False
self.sock = None
self._tunnel_headers = {}
def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
self.host = host
self.timeout = timeout
return self
def set_debuglevel(self, level):
self.level = level
def set_tunnel(self, host, port=None, headers=None):
self._tunnel_host = host
self._tunnel_port = port
if headers:
self._tunnel_headers = headers
else:
self._tunnel_headers.clear()
def request(self, method, url, body=None, headers=None, *,
encode_chunked=False):
self.method = method
self.selector = url
if headers is not None:
self.req_headers += headers.items()
self.req_headers.sort()
if body:
self.data = body
self.encode_chunked = encode_chunked
if self.raise_on_endheaders:
raise OSError()
def getresponse(self):
return MockHTTPResponse(MockFile(), {}, 200, "OK")
def close(self):
pass
class MockHandler:
# useful for testing handler machinery
# see add_ordered_mock_handlers() docstring
handler_order = 500
def __init__(self, methods):
self._define_methods(methods)
def _define_methods(self, methods):
for spec in methods:
if len(spec) == 2:
name, action = spec
else:
name, action = spec, None
meth = FakeMethod(name, action, self.handle)
setattr(self.__class__, name, meth)
def handle(self, fn_name, action, *args, **kwds):
self.parent.calls.append((self, fn_name, args, kwds))
if action is None:
return None
elif action == "return self":
return self
elif action == "return response":
res = MockResponse(200, "OK", {}, "")
return res
elif action == "return request":
return Request("http://blah/")
elif action.startswith("error"):
code = action[action.rfind(" ")+1:]
try:
code = int(code)
except ValueError:
pass
res = MockResponse(200, "OK", {}, "")
return self.parent.error("http", args[0], res, code, "", {})
elif action == "raise":
raise urllib.error.URLError("blah")
assert False
def close(self):
pass
def add_parent(self, parent):
self.parent = parent
self.parent.calls = []
def __lt__(self, other):
if not hasattr(other, "handler_order"):
# No handler_order, leave in original order. Yuck.
return True
return self.handler_order < other.handler_order
def add_ordered_mock_handlers(opener, meth_spec):
"""Create MockHandlers and add them to an OpenerDirector.
meth_spec: list of lists of tuples and strings defining methods to define
on handlers. eg:
[["http_error", "ftp_open"], ["http_open"]]
defines methods .http_error() and .ftp_open() on one handler, and
.http_open() on another. These methods just record their arguments and
return None. Using a tuple instead of a string causes the method to
perform some action (see MockHandler.handle()), eg:
[["http_error"], [("http_open", "return request")]]
defines .http_error() on one handler (which simply returns None), and
.http_open() on another handler, which returns a Request object.
"""
handlers = []
count = 0
for meths in meth_spec:
class MockHandlerSubclass(MockHandler):
pass
h = MockHandlerSubclass(meths)
h.handler_order += count
h.add_parent(opener)
count = count + 1
handlers.append(h)
opener.add_handler(h)
return handlers
def build_test_opener(*handler_instances):
opener = OpenerDirector()
for h in handler_instances:
opener.add_handler(h)
return opener
class MockHTTPHandler(urllib.request.BaseHandler):
# useful for testing redirections and auth
# sends supplied headers and code as first response
# sends 200 OK as second response
def __init__(self, code, headers):
self.code = code
self.headers = headers
self.reset()
def reset(self):
self._count = 0
self.requests = []
def http_open(self, req):
import email, copy
self.requests.append(copy.deepcopy(req))
if self._count == 0:
self._count = self._count + 1
name = http.client.responses[self.code]
msg = email.message_from_string(self.headers)
return self.parent.error(
"http", req, MockFile(), self.code, name, msg)
else:
self.req = req
msg = email.message_from_string("\r\n\r\n")
return MockResponse(200, "OK", msg, "", req.get_full_url())
class MockHTTPSHandler(urllib.request.AbstractHTTPHandler):
# Useful for testing the Proxy-Authorization request by verifying the
# properties of httpcon
def __init__(self, debuglevel=0):
urllib.request.AbstractHTTPHandler.__init__(self, debuglevel=debuglevel)
self.httpconn = MockHTTPClass()
def https_open(self, req):
return self.do_open(self.httpconn, req)
class MockHTTPHandlerCheckAuth(urllib.request.BaseHandler):
# useful for testing auth
# sends supplied code response
# checks if auth header is specified in request
def __init__(self, code):
self.code = code
self.has_auth_header = False
def reset(self):
self.has_auth_header = False
def http_open(self, req):
if req.has_header('Authorization'):
self.has_auth_header = True
name = http.client.responses[self.code]
return MockResponse(self.code, name, MockFile(), "", req.get_full_url())
class MockPasswordManager:
def add_password(self, realm, uri, user, password):
self.realm = realm
self.url = uri
self.user = user
self.password = password
def find_user_password(self, realm, authuri):
self.target_realm = realm
self.target_url = authuri
return self.user, self.password
class OpenerDirectorTests(unittest.TestCase):
def test_add_non_handler(self):
class NonHandler(object):
pass
self.assertRaises(TypeError,
OpenerDirector().add_handler, NonHandler())
def test_badly_named_methods(self):
# test work-around for three methods that accidentally follow the
# naming conventions for handler methods
# (*_open() / *_request() / *_response())
# These used to call the accidentally-named methods, causing a
# TypeError in real code; here, returning self from these mock
# methods would either cause no exception, or AttributeError.
from urllib.error import URLError
o = OpenerDirector()
meth_spec = [
[("do_open", "return self"), ("proxy_open", "return self")],
[("redirect_request", "return self")],
]
add_ordered_mock_handlers(o, meth_spec)
o.add_handler(urllib.request.UnknownHandler())
for scheme in "do", "proxy", "redirect":
self.assertRaises(URLError, o.open, scheme+"://example.com/")
def test_handled(self):
# handler returning non-None means no more handlers will be called
o = OpenerDirector()
meth_spec = [
["http_open", "ftp_open", "http_error_302"],
["ftp_open"],
[("http_open", "return self")],
[("http_open", "return self")],
]
handlers = add_ordered_mock_handlers(o, meth_spec)
req = Request("http://example.com/")
r = o.open(req)
# Second .http_open() gets called, third doesn't, since second returned
# non-None. Handlers without .http_open() never get any methods called
# on them.
# In fact, second mock handler defining .http_open() returns self
# (instead of response), which becomes the OpenerDirector's return
# value.
self.assertEqual(r, handlers[2])
calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
for expected, got in zip(calls, o.calls):
handler, name, args, kwds = got
self.assertEqual((handler, name), expected)
self.assertEqual(args, (req,))
def test_handler_order(self):
o = OpenerDirector()
handlers = []
for meths, handler_order in [([("http_open", "return self")], 500),
(["http_open"], 0)]:
class MockHandlerSubclass(MockHandler):
pass
h = MockHandlerSubclass(meths)
h.handler_order = handler_order
handlers.append(h)
o.add_handler(h)
o.open("http://example.com/")
# handlers called in reverse order, thanks to their sort order
self.assertEqual(o.calls[0][0], handlers[1])
self.assertEqual(o.calls[1][0], handlers[0])
def test_raise(self):
# raising URLError stops processing of request
o = OpenerDirector()
meth_spec = [
[("http_open", "raise")],
[("http_open", "return self")],
]
handlers = add_ordered_mock_handlers(o, meth_spec)
req = Request("http://example.com/")
self.assertRaises(urllib.error.URLError, o.open, req)
self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
def test_http_error(self):
# XXX http_error_default
# http errors are a special case
o = OpenerDirector()
meth_spec = [
[("http_open", "error 302")],
[("http_error_400", "raise"), "http_open"],
[("http_error_302", "return response"), "http_error_303",
"http_error"],
[("http_error_302")],
]
handlers = add_ordered_mock_handlers(o, meth_spec)
class Unknown:
def __eq__(self, other):
return True
req = Request("http://example.com/")
o.open(req)
assert len(o.calls) == 2
calls = [(handlers[0], "http_open", (req,)),
(handlers[2], "http_error_302",
(req, Unknown(), 302, "", {}))]
for expected, got in zip(calls, o.calls):
handler, method_name, args = expected
self.assertEqual((handler, method_name), got[:2])
self.assertEqual(args, got[2])
def test_processors(self):
# *_request / *_response methods get called appropriately
o = OpenerDirector()
meth_spec = [
[("http_request", "return request"),
("http_response", "return response")],
[("http_request", "return request"),
("http_response", "return response")],
]
handlers = add_ordered_mock_handlers(o, meth_spec)
req = Request("http://example.com/")
o.open(req)
# processor methods are called on *all* handlers that define them,
# not just the first handler that handles the request
calls = [
(handlers[0], "http_request"), (handlers[1], "http_request"),
(handlers[0], "http_response"), (handlers[1], "http_response")]
for i, (handler, name, args, kwds) in enumerate(o.calls):
if i < 2:
# *_request
self.assertEqual((handler, name), calls[i])
self.assertEqual(len(args), 1)
self.assertIsInstance(args[0], Request)
else:
# *_response
self.assertEqual((handler, name), calls[i])
self.assertEqual(len(args), 2)
self.assertIsInstance(args[0], Request)
# response from opener.open is None, because there's no
# handler that defines http_open to handle it
if args[1] is not None:
self.assertIsInstance(args[1], MockResponse)
def sanepathname2url(path):
try:
path.encode("utf-8")
except UnicodeEncodeError:
raise unittest.SkipTest("path is not encodable to utf8")
urlpath = urllib.request.pathname2url(path)
if os.name == "nt" and urlpath.startswith("///"):
urlpath = urlpath[2:]
# XXX don't ask me about the mac...
return urlpath
class HandlerTests(unittest.TestCase):
def test_ftp(self):
class MockFTPWrapper:
def __init__(self, data):
self.data = data
def retrfile(self, filename, filetype):
self.filename, self.filetype = filename, filetype
return io.StringIO(self.data), len(self.data)
def close(self):
pass
class NullFTPHandler(urllib.request.FTPHandler):
def __init__(self, data):
self.data = data
def connect_ftp(self, user, passwd, host, port, dirs,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
self.user, self.passwd = user, passwd
self.host, self.port = host, port
self.dirs = dirs
self.ftpwrapper = MockFTPWrapper(self.data)
return self.ftpwrapper
import ftplib
data = "rheum rhaponicum"
h = NullFTPHandler(data)
h.parent = MockOpener()
for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
("ftp://localhost/foo/bar/baz.html",
"localhost", ftplib.FTP_PORT, "", "", "I",
["foo", "bar"], "baz.html", "text/html"),
("ftp://parrot@localhost/foo/bar/baz.html",
"localhost", ftplib.FTP_PORT, "parrot", "", "I",
["foo", "bar"], "baz.html", "text/html"),
("ftp://%25parrot@localhost/foo/bar/baz.html",
"localhost", ftplib.FTP_PORT, "%parrot", "", "I",
["foo", "bar"], "baz.html", "text/html"),
("ftp://%2542parrot@localhost/foo/bar/baz.html",
"localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
["foo", "bar"], "baz.html", "text/html"),
("ftp://localhost:80/foo/bar/",
"localhost", 80, "", "", "D",
["foo", "bar"], "", None),
("ftp://localhost/baz.gif;type=a",
"localhost", ftplib.FTP_PORT, "", "", "A",
[], "baz.gif", None), # XXX really this should guess image/gif
]:
req = Request(url)
req.timeout = None
r = h.ftp_open(req)
# ftp authentication not yet implemented by FTPHandler
self.assertEqual(h.user, user)
self.assertEqual(h.passwd, passwd)
self.assertEqual(h.host, socket.gethostbyname(host))
self.assertEqual(h.port, port)
self.assertEqual(h.dirs, dirs)
self.assertEqual(h.ftpwrapper.filename, filename)
self.assertEqual(h.ftpwrapper.filetype, type_)
headers = r.info()
self.assertEqual(headers.get("Content-type"), mimetype)
self.assertEqual(int(headers["Content-length"]), len(data))
def test_file(self):
import email.utils
h = urllib.request.FileHandler()
o = h.parent = MockOpener()
TESTFN = support.TESTFN
urlpath = sanepathname2url(os.path.abspath(TESTFN))
towrite = b"hello, world\n"
urls = [
"file://localhost%s" % urlpath,
"file://%s" % urlpath,
"file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
]
try:
localaddr = socket.gethostbyname(socket.gethostname())
except socket.gaierror:
localaddr = ''
if localaddr:
urls.append("file://%s%s" % (localaddr, urlpath))
for url in urls:
f = open(TESTFN, "wb")
try:
try:
f.write(towrite)
finally:
f.close()
r = h.file_open(Request(url))
try:
data = r.read()
headers = r.info()
respurl = r.geturl()
finally:
r.close()
stats = os.stat(TESTFN)
modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
finally:
os.remove(TESTFN)
self.assertEqual(data, towrite)
self.assertEqual(headers["Content-type"], "text/plain")
self.assertEqual(headers["Content-length"], "13")
self.assertEqual(headers["Last-modified"], modified)
self.assertEqual(respurl, url)
for url in [
"file://localhost:80%s" % urlpath,
"file:///file_does_not_exist.txt",
"file://not-a-local-host.com//dir/file.txt",
"file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
os.getcwd(), TESTFN),
"file://somerandomhost.ontheinternet.com%s/%s" %
(os.getcwd(), TESTFN),
]:
try:
f = open(TESTFN, "wb")
try:
f.write(towrite)
finally:
f.close()
self.assertRaises(urllib.error.URLError,
h.file_open, Request(url))
finally:
os.remove(TESTFN)
h = urllib.request.FileHandler()
o = h.parent = MockOpener()
# XXXX why does // mean ftp (and /// mean not ftp!), and where
# is file: scheme specified? I think this is really a bug, and
# what was intended was to distinguish between URLs like:
# file:/blah.txt (a file)
# file://localhost/blah.txt (a file)
# file:///blah.txt (a file)
# file://ftp.example.com/blah.txt (an ftp URL)
for url, ftp in [
("file://ftp.example.com//foo.txt", False),
("file://ftp.example.com///foo.txt", False),
("file://ftp.example.com/foo.txt", False),
("file://somehost//foo/something.txt", False),
("file://localhost//foo/something.txt", False),
]:
req = Request(url)
try:
h.file_open(req)
except urllib.error.URLError:
self.assertFalse(ftp)
else:
self.assertIs(o.req, req)
self.assertEqual(req.type, "ftp")
self.assertEqual(req.type == "ftp", ftp)
def test_http(self):
h = urllib.request.AbstractHTTPHandler()
o = h.parent = MockOpener()
url = "http://example.com/"
for method, data in [("GET", None), ("POST", b"blah")]:
req = Request(url, data, {"Foo": "bar"})
req.timeout = None
req.add_unredirected_header("Spam", "eggs")
http = MockHTTPClass()
r = h.do_open(http, req)
# result attributes
r.read; r.readline # wrapped MockFile methods
r.info; r.geturl # addinfourl methods
r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
hdrs = r.info()
hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply()
self.assertEqual(r.geturl(), url)
self.assertEqual(http.host, "example.com")
self.assertEqual(http.level, 0)
self.assertEqual(http.method, method)
self.assertEqual(http.selector, "/")
self.assertEqual(http.req_headers,
[("Connection", "close"),
("Foo", "bar"), ("Spam", "eggs")])
self.assertEqual(http.data, data)
# check OSError converted to URLError
http.raise_on_endheaders = True
self.assertRaises(urllib.error.URLError, h.do_open, http, req)
# Check for TypeError on POST data which is str.
req = Request("http://example.com/","badpost")
self.assertRaises(TypeError, h.do_request_, req)
# check adding of standard headers
o.addheaders = [("Spam", "eggs")]
for data in b"", None: # POST, GET
req = Request("http://example.com/", data)
r = MockResponse(200, "OK", {}, "")
newreq = h.do_request_(req)
if data is None: # GET
self.assertNotIn("Content-length", req.unredirected_hdrs)
self.assertNotIn("Content-type", req.unredirected_hdrs)
else: # POST
self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
self.assertEqual(req.unredirected_hdrs["Content-type"],
"application/x-www-form-urlencoded")
# XXX the details of Host could be better tested
self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
# don't clobber existing headers
req.add_unredirected_header("Content-length", "foo")
req.add_unredirected_header("Content-type", "bar")
req.add_unredirected_header("Host", "baz")
req.add_unredirected_header("Spam", "foo")
newreq = h.do_request_(req)
self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
self.assertEqual(req.unredirected_hdrs["Host"], "baz")
self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
def test_http_body_file(self):
# A regular file - chunked encoding is used unless Content Length is
# already set.
h = urllib.request.AbstractHTTPHandler()
o = h.parent = MockOpener()
file_obj = tempfile.NamedTemporaryFile(mode='w+b', delete=False)
file_path = file_obj.name
file_obj.close()
self.addCleanup(os.unlink, file_path)
with open(file_path, "rb") as f:
req = Request("http://example.com/", f, {})
newreq = h.do_request_(req)
te = newreq.get_header('Transfer-encoding')
self.assertEqual(te, "chunked")
self.assertFalse(newreq.has_header('Content-length'))
with open(file_path, "rb") as f:
req = Request("http://example.com/", f, {"Content-Length": 30})
newreq = h.do_request_(req)
self.assertEqual(int(newreq.get_header('Content-length')), 30)
self.assertFalse(newreq.has_header("Transfer-encoding"))
def test_http_body_fileobj(self):
# A file object - chunked encoding is used
# unless Content Length is already set.
# (Note that there are some subtle differences to a regular
# file, that is why we are testing both cases.)
h = urllib.request.AbstractHTTPHandler()
o = h.parent = MockOpener()
file_obj = io.BytesIO()
req = Request("http://example.com/", file_obj, {})
newreq = h.do_request_(req)
self.assertEqual(newreq.get_header('Transfer-encoding'), 'chunked')
self.assertFalse(newreq.has_header('Content-length'))
headers = {"Content-Length": 30}
req = Request("http://example.com/", file_obj, headers)
newreq = h.do_request_(req)
self.assertEqual(int(newreq.get_header('Content-length')), 30)
self.assertFalse(newreq.has_header("Transfer-encoding"))
file_obj.close()
def test_http_body_pipe(self):
# A file reading from a pipe.
# A pipe cannot be seek'ed. There is no way to determine the
# content length up front. Thus, do_request_() should fall
# back to Transfer-encoding chunked.
h = urllib.request.AbstractHTTPHandler()
o = h.parent = MockOpener()
cmd = [sys.executable, "-c", r"pass"]
for headers in {}, {"Content-Length": 30}:
with subprocess.Popen(cmd, stdout=subprocess.PIPE) as proc:
req = Request("http://example.com/", proc.stdout, headers)
newreq = h.do_request_(req)
if not headers:
self.assertEqual(newreq.get_header('Content-length'), None)
self.assertEqual(newreq.get_header('Transfer-encoding'),
'chunked')
else:
self.assertEqual(int(newreq.get_header('Content-length')),
30)
def test_http_body_iterable(self):
# Generic iterable. There is no way to determine the content
# length up front. Fall back to Transfer-encoding chunked.
h = urllib.request.AbstractHTTPHandler()
o = h.parent = MockOpener()
def iterable_body():
yield b"one"
for headers in {}, {"Content-Length": 11}:
req = Request("http://example.com/", iterable_body(), headers)
newreq = h.do_request_(req)
if not headers:
self.assertEqual(newreq.get_header('Content-length'), None)
self.assertEqual(newreq.get_header('Transfer-encoding'),
'chunked')
else:
self.assertEqual(int(newreq.get_header('Content-length')), 11)
def test_http_body_empty_seq(self):
# Zero-length iterable body should be treated like any other iterable
h = urllib.request.AbstractHTTPHandler()
h.parent = MockOpener()
req = h.do_request_(Request("http://example.com/", ()))
self.assertEqual(req.get_header("Transfer-encoding"), "chunked")
self.assertFalse(req.has_header("Content-length"))
def test_http_body_array(self):
# array.array Iterable - Content Length is calculated
h = urllib.request.AbstractHTTPHandler()
o = h.parent = MockOpener()
iterable_array = array.array("I",[1,2,3,4])
for headers in {}, {"Content-Length": 16}:
req = Request("http://example.com/", iterable_array, headers)
newreq = h.do_request_(req)
self.assertEqual(int(newreq.get_header('Content-length')),16)
def test_http_handler_debuglevel(self):
o = OpenerDirector()
h = MockHTTPSHandler(debuglevel=1)
o.add_handler(h)
o.open("https://www.example.com")
self.assertEqual(h._debuglevel, 1)
def test_http_doubleslash(self):
# Checks the presence of any unnecessary double slash in url does not
# break anything. Previously, a double slash directly after the host
# could cause incorrect parsing.
h = urllib.request.AbstractHTTPHandler()
h.parent = MockOpener()
data = b""
ds_urls = [
"http://example.com/foo/bar/baz.html",
"http://example.com//foo/bar/baz.html",
"http://example.com/foo//bar/baz.html",
"http://example.com/foo/bar//baz.html"
]
for ds_url in ds_urls:
ds_req = Request(ds_url, data)
# Check whether host is determined correctly if there is no proxy
np_ds_req = h.do_request_(ds_req)
self.assertEqual(np_ds_req.unredirected_hdrs["Host"], "example.com")
# Check whether host is determined correctly if there is a proxy
ds_req.set_proxy("someproxy:3128", None)
p_ds_req = h.do_request_(ds_req)
self.assertEqual(p_ds_req.unredirected_hdrs["Host"], "example.com")
def test_full_url_setter(self):
# Checks to ensure that components are set correctly after setting the
# full_url of a Request object
urls = [
'http://example.com?foo=bar#baz',
'http://example.com?foo=bar&spam=eggs#bash',
'http://example.com',
]
# testing a reusable request instance, but the url parameter is
# required, so just use a dummy one to instantiate
r = Request('http://example.com')
for url in urls:
r.full_url = url
parsed = urlparse(url)
self.assertEqual(r.get_full_url(), url)
# full_url setter uses splittag to split into components.
# splittag sets the fragment as None while urlparse sets it to ''
self.assertEqual(r.fragment or '', parsed.fragment)
self.assertEqual(urlparse(r.get_full_url()).query, parsed.query)
def test_full_url_deleter(self):
r = Request('http://www.example.com')
del r.full_url
self.assertIsNone(r.full_url)
self.assertIsNone(r.fragment)
self.assertEqual(r.selector, '')
def test_fixpath_in_weirdurls(self):
# Issue4493: urllib2 to supply '/' when to urls where path does not
# start with'/'
h = urllib.request.AbstractHTTPHandler()
h.parent = MockOpener()
weird_url = 'http://www.python.org?getspam'
req = Request(weird_url)
newreq = h.do_request_(req)
self.assertEqual(newreq.host, 'www.python.org')
self.assertEqual(newreq.selector, '/?getspam')
url_without_path = 'http://www.python.org'
req = Request(url_without_path)
newreq = h.do_request_(req)
self.assertEqual(newreq.host, 'www.python.org')
self.assertEqual(newreq.selector, '')
def test_errors(self):
h = urllib.request.HTTPErrorProcessor()
o = h.parent = MockOpener()
url = "http://example.com/"
req = Request(url)
# all 2xx are passed through
r = MockResponse(200, "OK", {}, "", url)
newr = h.http_response(req, r)
self.assertIs(r, newr)
self.assertFalse(hasattr(o, "proto")) # o.error not called
r = MockResponse(202, "Accepted", {}, "", url)
newr = h.http_response(req, r)
self.assertIs(r, newr)
self.assertFalse(hasattr(o, "proto")) # o.error not called
r = MockResponse(206, "Partial content", {}, "", url)
newr = h.http_response(req, r)
self.assertIs(r, newr)
self.assertFalse(hasattr(o, "proto")) # o.error not called
# anything else calls o.error (and MockOpener returns None, here)
r = MockResponse(502, "Bad gateway", {}, "", url)
self.assertIsNone(h.http_response(req, r))
self.assertEqual(o.proto, "http") # o.error called
self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
def test_cookies(self):
cj = MockCookieJar()
h = urllib.request.HTTPCookieProcessor(cj)
h.parent = MockOpener()
req = Request("http://example.com/")
r = MockResponse(200, "OK", {}, "")
newreq = h.http_request(req)
self.assertIs(cj.ach_req, req)
self.assertIs(cj.ach_req, newreq)
self.assertEqual(req.origin_req_host, "example.com")
self.assertFalse(req.unverifiable)
newr = h.http_response(req, r)
self.assertIs(cj.ec_req, req)
self.assertIs(cj.ec_r, r)
self.assertIs(r, newr)
def test_redirect(self):
from_url = "http://example.com/a.html"
to_url = "http://example.com/b.html"
h = urllib.request.HTTPRedirectHandler()
o = h.parent = MockOpener()
# ordinary redirect behaviour
for code in 301, 302, 303, 307:
for data in None, "blah\nblah\n":
method = getattr(h, "http_error_%s" % code)
req = Request(from_url, data)
req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
req.add_header("Nonsense", "viking=withhold")
if data is not None:
req.add_header("Content-Length", str(len(data)))
req.add_unredirected_header("Spam", "spam")
try:
method(req, MockFile(), code, "Blah",
MockHeaders({"location": to_url}))
except urllib.error.HTTPError:
# 307 in response to POST requires user OK
self.assertEqual(code, 307)
self.assertIsNotNone(data)
self.assertEqual(o.req.get_full_url(), to_url)
try:
self.assertEqual(o.req.get_method(), "GET")
except AttributeError:
self.assertFalse(o.req.data)
# now it's a GET, there should not be headers regarding content
# (possibly dragged from before being a POST)
headers = [x.lower() for x in o.req.headers]
self.assertNotIn("content-length", headers)
self.assertNotIn("content-type", headers)
self.assertEqual(o.req.headers["Nonsense"],
"viking=withhold")
self.assertNotIn("Spam", o.req.headers)
self.assertNotIn("Spam", o.req.unredirected_hdrs)
# loop detection
req = Request(from_url)
req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
def redirect(h, req, url=to_url):
h.http_error_302(req, MockFile(), 302, "Blah",
MockHeaders({"location": url}))
# Note that the *original* request shares the same record of
# redirections with the sub-requests caused by the redirections.
# detect infinite loop redirect of a URL to itself
req = Request(from_url, origin_req_host="example.com")
count = 0
req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
try:
while 1:
redirect(h, req, "http://example.com/")
count = count + 1
except urllib.error.HTTPError:
# don't stop until max_repeats, because cookies may introduce state
self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
# detect endless non-repeating chain of redirects
req = Request(from_url, origin_req_host="example.com")
count = 0
req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
try:
while 1:
redirect(h, req, "http://example.com/%d" % count)
count = count + 1
except urllib.error.HTTPError:
self.assertEqual(count,
urllib.request.HTTPRedirectHandler.max_redirections)
def test_invalid_redirect(self):
from_url = "http://example.com/a.html"
valid_schemes = ['http','https','ftp']
invalid_schemes = ['file','imap','ldap']
schemeless_url = "example.com/b.html"
h = urllib.request.HTTPRedirectHandler()
o = h.parent = MockOpener()
req = Request(from_url)
req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
for scheme in invalid_schemes:
invalid_url = scheme + '://' + schemeless_url
self.assertRaises(urllib.error.HTTPError, h.http_error_302,
req, MockFile(), 302, "Security Loophole",
MockHeaders({"location": invalid_url}))
for scheme in valid_schemes:
valid_url = scheme + '://' + schemeless_url
h.http_error_302(req, MockFile(), 302, "That's fine",
MockHeaders({"location": valid_url}))
self.assertEqual(o.req.get_full_url(), valid_url)
def test_relative_redirect(self):
from_url = "http://example.com/a.html"
relative_url = "/b.html"
h = urllib.request.HTTPRedirectHandler()
o = h.parent = MockOpener()
req = Request(from_url)
req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
valid_url = urllib.parse.urljoin(from_url,relative_url)
h.http_error_302(req, MockFile(), 302, "That's fine",
MockHeaders({"location": valid_url}))
self.assertEqual(o.req.get_full_url(), valid_url)
def test_cookie_redirect(self):
# cookies shouldn't leak into redirected requests
from http.cookiejar import CookieJar
from test.test_http_cookiejar import interact_netscape
cj = CookieJar()
interact_netscape(cj, "http://www.example.com/", "spam=eggs")
hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
hdeh = urllib.request.HTTPDefaultErrorHandler()
hrh = urllib.request.HTTPRedirectHandler()
cp = urllib.request.HTTPCookieProcessor(cj)
o = build_test_opener(hh, hdeh, hrh, cp)
o.open("http://www.example.com/")
self.assertFalse(hh.req.has_header("Cookie"))
def test_redirect_fragment(self):
redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
hdeh = urllib.request.HTTPDefaultErrorHandler()
hrh = urllib.request.HTTPRedirectHandler()
o = build_test_opener(hh, hdeh, hrh)
fp = o.open('http://www.example.com')
self.assertEqual(fp.geturl(), redirected_url.strip())
def test_redirect_no_path(self):
# Issue 14132: Relative redirect strips original path
real_class = http.client.HTTPConnection
response1 = b"HTTP/1.1 302 Found\r\nLocation: ?query\r\n\r\n"
http.client.HTTPConnection = test_urllib.fakehttp(response1)
self.addCleanup(setattr, http.client, "HTTPConnection", real_class)
urls = iter(("/path", "/path?query"))
def request(conn, method, url, *pos, **kw):
self.assertEqual(url, next(urls))
real_class.request(conn, method, url, *pos, **kw)
# Change response for subsequent connection
conn.__class__.fakedata = b"HTTP/1.1 200 OK\r\n\r\nHello!"
http.client.HTTPConnection.request = request
fp = urllib.request.urlopen("http://python.org/path")
self.assertEqual(fp.geturl(), "http://python.org/path?query")
def test_redirect_encoding(self):
# Some characters in the redirect target may need special handling,
# but most ASCII characters should be treated as already encoded
class Handler(urllib.request.HTTPHandler):
def http_open(self, req):
result = self.do_open(self.connection, req)
self.last_buf = self.connection.buf
# Set up a normal response for the next request
self.connection = test_urllib.fakehttp(
b'HTTP/1.1 200 OK\r\n'
b'Content-Length: 3\r\n'
b'\r\n'
b'123'
)
return result
handler = Handler()
opener = urllib.request.build_opener(handler)
tests = (
(b'/p\xC3\xA5-dansk/', b'/p%C3%A5-dansk/'),
(b'/spaced%20path/', b'/spaced%20path/'),
(b'/spaced path/', b'/spaced%20path/'),
(b'/?p\xC3\xA5-dansk', b'/?p%C3%A5-dansk'),
)
for [location, result] in tests:
with self.subTest(repr(location)):
handler.connection = test_urllib.fakehttp(
b'HTTP/1.1 302 Redirect\r\n'
b'Location: ' + location + b'\r\n'
b'\r\n'
)
response = opener.open('http://example.com/')
expected = b'GET ' + result + b' '
request = handler.last_buf
self.assertTrue(request.startswith(expected), repr(request))
def test_proxy(self):
o = OpenerDirector()
ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
o.add_handler(ph)
meth_spec = [
[("http_open", "return response")]
]
handlers = add_ordered_mock_handlers(o, meth_spec)
req = Request("http://acme.example.com/")
self.assertEqual(req.host, "acme.example.com")
o.open(req)
self.assertEqual(req.host, "proxy.example.com:3128")
self.assertEqual([(handlers[0], "http_open")],
[tup[0:2] for tup in o.calls])
def test_proxy_no_proxy(self):
os.environ['no_proxy'] = 'python.org'
o = OpenerDirector()
ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
o.add_handler(ph)
req = Request("http://www.perl.org/")
self.assertEqual(req.host, "www.perl.org")
o.open(req)
self.assertEqual(req.host, "proxy.example.com")
req = Request("http://www.python.org")
self.assertEqual(req.host, "www.python.org")
o.open(req)
self.assertEqual(req.host, "www.python.org")
del os.environ['no_proxy']
def test_proxy_no_proxy_all(self):
os.environ['no_proxy'] = '*'
o = OpenerDirector()
ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
o.add_handler(ph)
req = Request("http://www.python.org")
self.assertEqual(req.host, "www.python.org")
o.open(req)
self.assertEqual(req.host, "www.python.org")
del os.environ['no_proxy']
def test_proxy_https(self):
o = OpenerDirector()
ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
o.add_handler(ph)
meth_spec = [
[("https_open", "return response")]
]
handlers = add_ordered_mock_handlers(o, meth_spec)
req = Request("https://www.example.com/")
self.assertEqual(req.host, "www.example.com")
o.open(req)
self.assertEqual(req.host, "proxy.example.com:3128")
self.assertEqual([(handlers[0], "https_open")],
[tup[0:2] for tup in o.calls])
def test_proxy_https_proxy_authorization(self):
o = OpenerDirector()
ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
o.add_handler(ph)
https_handler = MockHTTPSHandler()
o.add_handler(https_handler)
req = Request("https://www.example.com/")
req.add_header("Proxy-Authorization", "FooBar")
req.add_header("User-Agent", "Grail")
self.assertEqual(req.host, "www.example.com")
self.assertIsNone(req._tunnel_host)
o.open(req)
# Verify Proxy-Authorization gets tunneled to request.
# httpsconn req_headers do not have the Proxy-Authorization header but
# the req will have.
self.assertNotIn(("Proxy-Authorization", "FooBar"),
https_handler.httpconn.req_headers)
self.assertIn(("User-Agent", "Grail"),
https_handler.httpconn.req_headers)
self.assertIsNotNone(req._tunnel_host)
self.assertEqual(req.host, "proxy.example.com:3128")
self.assertEqual(req.get_header("Proxy-authorization"), "FooBar")
@unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
def test_osx_proxy_bypass(self):
bypass = {
'exclude_simple': False,
'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
'10.0/16']
}
# Check hosts that should trigger the proxy bypass
for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
'10.0.0.1'):
self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
'expected bypass of %s to be True' % host)
# Check hosts that should not trigger the proxy bypass
for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1',
'notinbypass'):
self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
'expected bypass of %s to be False' % host)
# Check the exclude_simple flag
bypass = {'exclude_simple': True, 'exceptions': []}
self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
def check_basic_auth(self, headers, realm):
with self.subTest(realm=realm, headers=headers):
opener = OpenerDirector()
password_manager = MockPasswordManager()
auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
body = '\r\n'.join(headers) + '\r\n\r\n'
http_handler = MockHTTPHandler(401, body)
opener.add_handler(auth_handler)
opener.add_handler(http_handler)
self._test_basic_auth(opener, auth_handler, "Authorization",
realm, http_handler, password_manager,
"http://acme.example.com/protected",
"http://acme.example.com/protected")
def test_basic_auth(self):
realm = "[email protected]"
realm2 = "[email protected]"
basic = f'Basic realm="{realm}"'
basic2 = f'Basic realm="{realm2}"'
other_no_realm = 'Otherscheme xxx'
digest = (f'Digest realm="{realm2}", '
f'qop="auth, auth-int", '
f'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", '
f'opaque="5ccc069c403ebaf9f0171e9517f40e41"')
for realm_str in (
# test "quote" and 'quote'
f'Basic realm="{realm}"',
f"Basic realm='{realm}'",
# charset is ignored
f'Basic realm="{realm}", charset="UTF-8"',
# Multiple challenges per header
f'{basic}, {basic2}',
f'{basic}, {other_no_realm}',
f'{other_no_realm}, {basic}',
f'{basic}, {digest}',
f'{digest}, {basic}',
):
headers = [f'WWW-Authenticate: {realm_str}']
self.check_basic_auth(headers, realm)
# no quote: expect a warning
with support.check_warnings(("Basic Auth Realm was unquoted",
UserWarning)):
headers = [f'WWW-Authenticate: Basic realm={realm}']
self.check_basic_auth(headers, realm)
# Multiple headers: one challenge per header.
# Use the first Basic realm.
for challenges in (
[basic, basic2],
[basic, digest],
[digest, basic],
):
headers = [f'WWW-Authenticate: {challenge}'
for challenge in challenges]
self.check_basic_auth(headers, realm)
def test_proxy_basic_auth(self):
opener = OpenerDirector()
ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
opener.add_handler(ph)
password_manager = MockPasswordManager()
auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
realm = "ACME Networks"
http_handler = MockHTTPHandler(
407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
opener.add_handler(auth_handler)
opener.add_handler(http_handler)
self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
realm, http_handler, password_manager,
"http://acme.example.com:3128/protected",
"proxy.example.com:3128",
)
def test_basic_and_digest_auth_handlers(self):
# HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
# response (http://python.org/sf/1479302), where it should instead
# return None to allow another handler (especially
# HTTPBasicAuthHandler) to handle the response.
# Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
# try digest first (since it's the strongest auth scheme), so we record
# order of calls here to check digest comes first:
class RecordingOpenerDirector(OpenerDirector):
def __init__(self):
OpenerDirector.__init__(self)
self.recorded = []
def record(self, info):
self.recorded.append(info)
class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
def http_error_401(self, *args, **kwds):
self.parent.record("digest")
urllib.request.HTTPDigestAuthHandler.http_error_401(self,
*args, **kwds)
class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
def http_error_401(self, *args, **kwds):
self.parent.record("basic")
urllib.request.HTTPBasicAuthHandler.http_error_401(self,
*args, **kwds)
opener = RecordingOpenerDirector()
password_manager = MockPasswordManager()
digest_handler = TestDigestAuthHandler(password_manager)
basic_handler = TestBasicAuthHandler(password_manager)
realm = "ACME Networks"
http_handler = MockHTTPHandler(
401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
opener.add_handler(basic_handler)
opener.add_handler(digest_handler)
opener.add_handler(http_handler)
# check basic auth isn't blocked by digest handler failing
self._test_basic_auth(opener, basic_handler, "Authorization",
realm, http_handler, password_manager,
"http://acme.example.com/protected",
"http://acme.example.com/protected",
)
# check digest was tried before basic (twice, because
# _test_basic_auth called .open() twice)
self.assertEqual(opener.recorded, ["digest", "basic"]*2)
def test_unsupported_auth_digest_handler(self):
opener = OpenerDirector()
# While using DigestAuthHandler
digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
http_handler = MockHTTPHandler(
401, 'WWW-Authenticate: Kerberos\r\n\r\n')
opener.add_handler(digest_auth_handler)
opener.add_handler(http_handler)
self.assertRaises(ValueError, opener.open, "http://www.example.com")
def test_unsupported_auth_basic_handler(self):
# While using BasicAuthHandler
opener = OpenerDirector()
basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
http_handler = MockHTTPHandler(
401, 'WWW-Authenticate: NTLM\r\n\r\n')
opener.add_handler(basic_auth_handler)
opener.add_handler(http_handler)
self.assertRaises(ValueError, opener.open, "http://www.example.com")
def _test_basic_auth(self, opener, auth_handler, auth_header,
realm, http_handler, password_manager,
request_url, protected_url):
import base64
user, password = "wile", "coyote"
# .add_password() fed through to password manager
auth_handler.add_password(realm, request_url, user, password)
self.assertEqual(realm, password_manager.realm)
self.assertEqual(request_url, password_manager.url)
self.assertEqual(user, password_manager.user)
self.assertEqual(password, password_manager.password)
opener.open(request_url)
# should have asked the password manager for the username/password
self.assertEqual(password_manager.target_realm, realm)
self.assertEqual(password_manager.target_url, protected_url)
# expect one request without authorization, then one with
self.assertEqual(len(http_handler.requests), 2)
self.assertFalse(http_handler.requests[0].has_header(auth_header))
userpass = bytes('%s:%s' % (user, password), "ascii")
auth_hdr_value = ('Basic ' +
base64.encodebytes(userpass).strip().decode())
self.assertEqual(http_handler.requests[1].get_header(auth_header),
auth_hdr_value)
self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
auth_hdr_value)
# if the password manager can't find a password, the handler won't
# handle the HTTP auth error
password_manager.user = password_manager.password = None
http_handler.reset()
opener.open(request_url)
self.assertEqual(len(http_handler.requests), 1)
self.assertFalse(http_handler.requests[0].has_header(auth_header))
def test_basic_prior_auth_auto_send(self):
# Assume already authenticated if is_authenticated=True
# for APIs like Github that don't return 401
user, password = "wile", "coyote"
request_url = "http://acme.example.com/protected"
http_handler = MockHTTPHandlerCheckAuth(200)
pwd_manager = HTTPPasswordMgrWithPriorAuth()
auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
auth_prior_handler.add_password(
None, request_url, user, password, is_authenticated=True)
is_auth = pwd_manager.is_authenticated(request_url)
self.assertTrue(is_auth)
opener = OpenerDirector()
opener.add_handler(auth_prior_handler)
opener.add_handler(http_handler)
opener.open(request_url)
# expect request to be sent with auth header
self.assertTrue(http_handler.has_auth_header)
def test_basic_prior_auth_send_after_first_success(self):
# Auto send auth header after authentication is successful once
user, password = 'wile', 'coyote'
request_url = 'http://acme.example.com/protected'
realm = 'ACME'
pwd_manager = HTTPPasswordMgrWithPriorAuth()
auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
auth_prior_handler.add_password(realm, request_url, user, password)
is_auth = pwd_manager.is_authenticated(request_url)
self.assertFalse(is_auth)
opener = OpenerDirector()
opener.add_handler(auth_prior_handler)
http_handler = MockHTTPHandler(
401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % None)
opener.add_handler(http_handler)
opener.open(request_url)
is_auth = pwd_manager.is_authenticated(request_url)
self.assertTrue(is_auth)
http_handler = MockHTTPHandlerCheckAuth(200)
self.assertFalse(http_handler.has_auth_header)
opener = OpenerDirector()
opener.add_handler(auth_prior_handler)
opener.add_handler(http_handler)
# After getting 200 from MockHTTPHandler
# Next request sends header in the first request
opener.open(request_url)
# expect request to be sent with auth header
self.assertTrue(http_handler.has_auth_header)
def test_http_closed(self):
"""Test the connection is cleaned up when the response is closed"""
for (transfer, data) in (
("Connection: close", b"data"),
("Transfer-Encoding: chunked", b"4\r\ndata\r\n0\r\n\r\n"),
("Content-Length: 4", b"data"),
):
header = "HTTP/1.1 200 OK\r\n{}\r\n\r\n".format(transfer)
conn = test_urllib.fakehttp(header.encode() + data)
handler = urllib.request.AbstractHTTPHandler()
req = Request("http://dummy/")
req.timeout = None
with handler.do_open(conn, req) as resp:
resp.read()
self.assertTrue(conn.fakesock.closed,
"Connection not closed with {!r}".format(transfer))
def test_invalid_closed(self):
"""Test the connection is cleaned up after an invalid response"""
conn = test_urllib.fakehttp(b"")
handler = urllib.request.AbstractHTTPHandler()
req = Request("http://dummy/")
req.timeout = None
with self.assertRaises(http.client.BadStatusLine):
handler.do_open(conn, req)
self.assertTrue(conn.fakesock.closed, "Connection not closed")
class MiscTests(unittest.TestCase):
def opener_has_handler(self, opener, handler_class):
self.assertTrue(any(h.__class__ == handler_class
for h in opener.handlers))
def test_build_opener(self):
class MyHTTPHandler(urllib.request.HTTPHandler):
pass
class FooHandler(urllib.request.BaseHandler):
def foo_open(self):
pass
class BarHandler(urllib.request.BaseHandler):
def bar_open(self):
pass
build_opener = urllib.request.build_opener
o = build_opener(FooHandler, BarHandler)
self.opener_has_handler(o, FooHandler)
self.opener_has_handler(o, BarHandler)
# can take a mix of classes and instances
o = build_opener(FooHandler, BarHandler())
self.opener_has_handler(o, FooHandler)
self.opener_has_handler(o, BarHandler)
# subclasses of default handlers override default handlers
o = build_opener(MyHTTPHandler)
self.opener_has_handler(o, MyHTTPHandler)
# a particular case of overriding: default handlers can be passed
# in explicitly
o = build_opener()
self.opener_has_handler(o, urllib.request.HTTPHandler)
o = build_opener(urllib.request.HTTPHandler)
self.opener_has_handler(o, urllib.request.HTTPHandler)
o = build_opener(urllib.request.HTTPHandler())
self.opener_has_handler(o, urllib.request.HTTPHandler)
# Issue2670: multiple handlers sharing the same base class
class MyOtherHTTPHandler(urllib.request.HTTPHandler):
pass
o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
self.opener_has_handler(o, MyHTTPHandler)
self.opener_has_handler(o, MyOtherHTTPHandler)
@unittest.skipUnless(support.is_resource_enabled('network'),
'test requires network access')
def test_issue16464(self):
with support.transient_internet("http://www.example.com/"):
opener = urllib.request.build_opener()
request = urllib.request.Request("http://www.example.com/")
self.assertEqual(None, request.data)
opener.open(request, "1".encode("us-ascii"))
self.assertEqual(b"1", request.data)
self.assertEqual("1", request.get_header("Content-length"))
opener.open(request, "1234567890".encode("us-ascii"))
self.assertEqual(b"1234567890", request.data)
self.assertEqual("10", request.get_header("Content-length"))
def test_HTTPError_interface(self):
"""
Issue 13211 reveals that HTTPError didn't implement the URLError
interface even though HTTPError is a subclass of URLError.
"""
msg = 'something bad happened'
url = code = fp = None
hdrs = 'Content-Length: 42'
err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
self.assertTrue(hasattr(err, 'reason'))
self.assertEqual(err.reason, 'something bad happened')
self.assertTrue(hasattr(err, 'headers'))
self.assertEqual(err.headers, 'Content-Length: 42')
expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
self.assertEqual(str(err), expected_errmsg)
expected_errmsg = '<HTTPError %s: %r>' % (err.code, err.msg)
self.assertEqual(repr(err), expected_errmsg)
def test_parse_proxy(self):
parse_proxy_test_cases = [
('proxy.example.com',
(None, None, None, 'proxy.example.com')),
('proxy.example.com:3128',
(None, None, None, 'proxy.example.com:3128')),
('proxy.example.com', (None, None, None, 'proxy.example.com')),
('proxy.example.com:3128',
(None, None, None, 'proxy.example.com:3128')),
# The authority component may optionally include userinfo
# (assumed to be # username:password):
('joe:[email protected]',
(None, 'joe', 'password', 'proxy.example.com')),
('joe:[email protected]:3128',
(None, 'joe', 'password', 'proxy.example.com:3128')),
#Examples with URLS
('http://proxy.example.com/',
('http', None, None, 'proxy.example.com')),
('http://proxy.example.com:3128/',
('http', None, None, 'proxy.example.com:3128')),
('http://joe:[email protected]/',
('http', 'joe', 'password', 'proxy.example.com')),
('http://joe:[email protected]:3128',
('http', 'joe', 'password', 'proxy.example.com:3128')),
# Everything after the authority is ignored
('ftp://joe:[email protected]/rubbish:3128',
('ftp', 'joe', 'password', 'proxy.example.com')),
# Test for no trailing '/' case
('http://joe:[email protected]',
('http', 'joe', 'password', 'proxy.example.com'))
]
for tc, expected in parse_proxy_test_cases:
self.assertEqual(_parse_proxy(tc), expected)
self.assertRaises(ValueError, _parse_proxy, 'file:/ftp.example.com'),
def test_unsupported_algorithm(self):
handler = AbstractDigestAuthHandler()
with self.assertRaises(ValueError) as exc:
handler.get_algorithm_impls('invalid')
self.assertEqual(
str(exc.exception),
"Unsupported digest authentication algorithm 'invalid'"
)
class RequestTests(unittest.TestCase):
class PutRequest(Request):
method = 'PUT'
def setUp(self):
self.get = Request("http://www.python.org/~jeremy/")
self.post = Request("http://www.python.org/~jeremy/",
"data",
headers={"X-Test": "test"})
self.head = Request("http://www.python.org/~jeremy/", method='HEAD')
self.put = self.PutRequest("http://www.python.org/~jeremy/")
self.force_post = self.PutRequest("http://www.python.org/~jeremy/",
method="POST")
def test_method(self):
self.assertEqual("POST", self.post.get_method())
self.assertEqual("GET", self.get.get_method())
self.assertEqual("HEAD", self.head.get_method())
self.assertEqual("PUT", self.put.get_method())
self.assertEqual("POST", self.force_post.get_method())
def test_data(self):
self.assertFalse(self.get.data)
self.assertEqual("GET", self.get.get_method())
self.get.data = "spam"
self.assertTrue(self.get.data)
self.assertEqual("POST", self.get.get_method())
# issue 16464
# if we change data we need to remove content-length header
# (cause it's most probably calculated for previous value)
def test_setting_data_should_remove_content_length(self):
self.assertNotIn("Content-length", self.get.unredirected_hdrs)
self.get.add_unredirected_header("Content-length", 42)
self.assertEqual(42, self.get.unredirected_hdrs["Content-length"])
self.get.data = "spam"
self.assertNotIn("Content-length", self.get.unredirected_hdrs)
# issue 17485 same for deleting data.
def test_deleting_data_should_remove_content_length(self):
self.assertNotIn("Content-length", self.get.unredirected_hdrs)
self.get.data = 'foo'
self.get.add_unredirected_header("Content-length", 3)
self.assertEqual(3, self.get.unredirected_hdrs["Content-length"])
del self.get.data
self.assertNotIn("Content-length", self.get.unredirected_hdrs)
def test_get_full_url(self):
self.assertEqual("http://www.python.org/~jeremy/",
self.get.get_full_url())
def test_selector(self):
self.assertEqual("/~jeremy/", self.get.selector)
req = Request("http://www.python.org/")
self.assertEqual("/", req.selector)
def test_get_type(self):
self.assertEqual("http", self.get.type)
def test_get_host(self):
self.assertEqual("www.python.org", self.get.host)
def test_get_host_unquote(self):
req = Request("http://www.%70ython.org/")
self.assertEqual("www.python.org", req.host)
def test_proxy(self):
self.assertFalse(self.get.has_proxy())
self.get.set_proxy("www.perl.org", "http")
self.assertTrue(self.get.has_proxy())
self.assertEqual("www.python.org", self.get.origin_req_host)
self.assertEqual("www.perl.org", self.get.host)
def test_wrapped_url(self):
req = Request("<URL:http://www.python.org>")
self.assertEqual("www.python.org", req.host)
def test_url_fragment(self):
req = Request("http://www.python.org/?qs=query#fragment=true")
self.assertEqual("/?qs=query", req.selector)
req = Request("http://www.python.org/#fun=true")
self.assertEqual("/", req.selector)
# Issue 11703: geturl() omits fragment in the original URL.
url = 'http://docs.python.org/library/urllib2.html#OK'
req = Request(url)
self.assertEqual(req.get_full_url(), url)
def test_url_fullurl_get_full_url(self):
urls = ['http://docs.python.org',
'http://docs.python.org/library/urllib2.html#OK',
'http://www.python.org/?qs=query#fragment=true']
for url in urls:
req = Request(url)
self.assertEqual(req.get_full_url(), req.full_url)
if __name__ == "__main__":
unittest.main()
| 77,791 | 1,955 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/randv2_64.pck | crandom
Random
p0
(tRp1
(I2
(I2147483648
I1812115682
I2741755497
I1028055730
I809166036
I2773628650
I62321950
I535290043
I349877800
I976167039
I2490696940
I3631326955
I2107991114
I2941205793
I3199611605
I1871971556
I1456108540
I2984591044
I140836801
I4203227310
I3652722980
I4031971234
I555769760
I697301296
I2347638880
I3302335858
I320255162
I2553586608
I1570224361
I2838780912
I2315834918
I2351348158
I3545433015
I2292018579
I1177569331
I758497559
I2913311175
I1014948880
I1793619243
I3982451053
I3850988342
I2393984324
I1583100093
I3144742543
I3655047493
I3507532385
I3094515442
I350042434
I2455294844
I1038739312
I313809152
I189433072
I1653165452
I4186650593
I19281455
I2589680619
I4145931590
I4283266118
I636283172
I943618337
I3170184633
I2308766231
I634615159
I538152647
I2079576891
I1029442616
I3410689412
I1370292761
I1071718978
I2139496322
I1876699543
I3485866187
I3157490130
I1633105386
I1453253160
I3841322080
I3789608924
I4110770792
I95083673
I931354627
I2065389591
I3448339827
I3348204577
I3263528560
I2411324590
I4003055026
I1869670093
I2737231843
I4150701155
I2689667621
I2993263224
I3239890140
I1191430483
I1214399779
I3623428533
I1817058866
I3052274451
I326030082
I1505129312
I2306812262
I1349150363
I1099127895
I2543465574
I2396380193
I503926466
I1607109730
I3451716817
I58037114
I4290081119
I947517597
I3083440186
I520522630
I2948962496
I4184319574
I2957636335
I668374201
I2325446473
I472785314
I3791932366
I573017189
I2185725379
I1262251492
I3525089379
I2951262653
I1305347305
I940958122
I3343754566
I359371744
I3874044973
I396897232
I147188248
I716683703
I4013880315
I1133359586
I1794612249
I3480815192
I3988787804
I1729355809
I573408542
I1419310934
I1770030447
I3552845567
I1693976502
I1271189893
I2298236738
I2049219027
I3464198070
I1233574082
I1007451781
I1838253750
I687096593
I1131375603
I1223013895
I1490478435
I339265439
I4232792659
I491538536
I2816256769
I1044097522
I2566227049
I748762793
I1511830494
I3593259822
I4121279213
I3735541309
I3609794797
I1939942331
I377570434
I1437957554
I1831285696
I55062811
I2046783110
I1303902283
I1838349877
I420993556
I1256392560
I2795216506
I2783687924
I3322303169
I512794749
I308405826
I517164429
I3320436022
I1328403632
I2269184746
I3729522810
I3304314450
I2238756124
I1690581361
I3813277532
I4119706879
I2659447875
I388818978
I2064580814
I1586227676
I2627522685
I2017792269
I547928109
I859107450
I1062238929
I858886237
I3795783146
I4173914756
I3835915965
I3329504821
I3494579904
I838863205
I3399734724
I4247387481
I3618414834
I2984433798
I2165205561
I4260685684
I3045904244
I3450093836
I3597307595
I3215851166
I3162801328
I2558283799
I950068105
I1829664117
I3108542987
I2378860527
I790023460
I280087750
I1171478018
I2333653728
I3976932140
I896746152
I1802494195
I1232873794
I2749440836
I2032037296
I2012091682
I1296131034
I3892133385
I908161334
I2296791795
I548169794
I696265
I893156828
I426904709
I3565374535
I2655906825
I2792178515
I2406814632
I4038847579
I3123934642
I2197503004
I3535032597
I2266216689
I2117613462
I1787448518
I1875089416
I2037165384
I1140676321
I3606296464
I3229138231
I2458267132
I1874651171
I3331900867
I1000557654
I1432861701
I473636323
I2691783927
I1871437447
I1328016401
I4118690062
I449467602
I681789035
I864889442
I1200888928
I75769445
I4008690037
I2464577667
I4167795823
I3070097648
I2579174882
I1216886568
I3810116343
I2249507485
I3266903480
I3671233480
I100191658
I3087121334
I365063087
I3821275176
I2165052848
I1282465245
I3601570637
I3132413236
I2780570459
I3222142917
I3129794692
I2611590811
I947031677
I2991908938
I750997949
I3632575131
I1632014461
I2846484755
I2347261779
I2903959448
I1397316686
I1904578392
I774649578
I3164598558
I2429587609
I738244516
I1563304975
I1399317414
I1021316297
I3187933234
I2126780757
I4011907847
I4095169219
I3358010054
I2729978247
I3736811646
I3009656410
I2893043637
I4027447385
I1239610110
I1488806900
I2674866844
I442876374
I2853687260
I2785921005
I3151378528
I1180567
I2803146964
I982221759
I2192919417
I3087026181
I2480838002
I738452921
I687986185
I3049371676
I3636492954
I3468311299
I2379621102
I788988633
I1643210601
I2983998168
I2492730801
I2586048705
I604073029
I4121082815
I1496476928
I2972357110
I2663116968
I2642628592
I2116052039
I487186279
I2577680328
I3974766614
I730776636
I3842528855
I1929093695
I44626622
I3989908833
I1695426222
I3675479382
I3051784964
I1514876613
I1254036595
I2420450649
I3034377361
I2332990590
I1535175126
I185834384
I1107372900
I1707278185
I1286285295
I3332574225
I2785672437
I883170645
I2005666473
I3403131327
I4122021352
I1464032858
I3702576112
I260554598
I1837731650
I2594435345
I75771049
I2012484289
I3058649775
I29979703
I3861335335
I2506495152
I3786448704
I442947790
I2582724774
I4291336243
I2568189843
I1923072690
I1121589611
I837696302
I3284631720
I3865021324
I3576453165
I2559531629
I1459231762
I3506550036
I3754420159
I2622000757
I124228596
I1084328605
I1692830753
I547273558
I674282621
I655259103
I3188629610
I490502174
I2081001293
I3191330704
I4109943593
I1859948504
I3163806460
I508833168
I1256371033
I2709253790
I2068956572
I3092842814
I3913926529
I2039638759
I981982529
I536094190
I368855295
I51993975
I1597480732
I4058175522
I2155896702
I3196251991
I1081913893
I3952353788
I3545548108
I2370669647
I2206572308
I2576392991
I1732303374
I1153136290
I537641955
I1738691747
I3232854186
I2539632206
I2829760278
I3058187853
I1202425792
I3762361970
I2863949342
I2640635867
I376638744
I1857679757
I330798087
I1457400505
I1135610046
I606400715
I1859536026
I509811335
I529772308
I2579273244
I1890382004
I3959908876
I2612335971
I2834052227
I1434475986
I3684202717
I4015011345
I582567852
I3689969571
I3934753460
I3034960691
I208573292
I4004113742
I3992904842
I2587153719
I3529179079
I1565424987
I779130678
I1048582935
I3213591622
I3607793434
I3951254937
I2047811901
I7508850
I248544605
I4210090324
I2331490884
I70057213
I776474945
I1345528889
I3290403612
I1664955269
I1533143116
I545003424
I4141564478
I1257326139
I868843601
I2337603029
I1918131449
I1843439523
I1125519035
I673340118
I421408852
I1520454906
I1804722630
I3621254196
I2329968000
I39464672
I430583134
I294026512
I53978525
I2892276105
I1418863764
I3419054451
I1391595797
I3544981798
I4191780858
I825672357
I2972000844
I1571305069
I4231982845
I3611916419
I3045163168
I2982349733
I278572141
I4215338078
I839860504
I1819151779
I1412347479
I1386770353
I3914589491
I3783104977
I4124296733
I830546258
I89825624
I4110601328
I2545483429
I300600527
I516641158
I3693021034
I2852912854
I3240039868
I4167407959
I1479557946
I3621188804
I1391590944
I3578441128
I1227055556
I406898396
I3064054983
I25835338
I402664165
I4097682779
I2106728012
I203613622
I3045467686
I1381726438
I3798670110
I1342314961
I3552497361
I535913619
I2625787583
I1606574307
I1101269630
I1950513752
I1121355862
I3586816903
I438529984
I2473182121
I1229997203
I405445940
I1695535315
I427014336
I3916768430
I392298359
I1884642868
I1244730821
I741058080
I567479957
I3527621168
I3191971011
I3267069104
I4108668146
I1520795587
I166581006
I473794477
I1562126550
I929843010
I889533294
I1266556608
I874518650
I3520162092
I3013765049
I4220231414
I547246449
I3998093769
I3737193746
I3872944207
I793651876
I2606384318
I875991012
I1394836334
I4102011644
I854380426
I2618666767
I2568302000
I1995512132
I229491093
I2673500286
I3364550739
I3836923416
I243656987
I3944388983
I4064949677
I1416956378
I1703244487
I3990798829
I2023425781
I3926702214
I1229015501
I3174247824
I624
tp2
Ntp3
b. | 7,365 | 633 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/tokenize_tests-no-coding-cookie-and-utf8-bom-sig-only.txt | # IMPORTANT: this file has the utf-8 BOM signature '\xef\xbb\xbf'
# at the start of it. Make sure this is preserved if any changes
# are made!
# Arbitrary encoded utf-8 text (stolen from test_doctest2.py).
x = 'ÐÐÐÐÐ'
def y():
"""
And again in a comment. ÐÐÐÐÐ
"""
pass
| 303 | 12 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/pydoc_mod.py | """This is a test module for test_pydoc"""
__author__ = "Benjamin Peterson"
__credits__ = "Nobody"
__version__ = "1.2.3.4"
__xyz__ = "X, Y and Z"
class A:
"""Hello and goodbye"""
def __init__():
"""Wow, I have no function!"""
pass
class B(object):
NO_MEANING: str = "eggs"
pass
class C(object):
def say_no(self):
return "no"
def get_answer(self):
""" Return say_no() """
return self.say_no()
def is_it_true(self):
""" Return self.get_answer() """
return self.get_answer()
def doc_func():
"""
This function solves all of the world's problems:
hunger
lack of Python
war
"""
def nodoc_func():
pass
| 713 | 38 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_math.py | # Python test set -- math module
# XXXX Should not do tests around zero only
from test.support import run_unittest, verbose, requires_IEEE_754
from test import support
import unittest
import math
import os
import platform
import struct
import sys
import sysconfig
eps = 1E-05
NAN = float('nan')
INF = float('inf')
NINF = float('-inf')
FLOAT_MAX = sys.float_info.max
# detect evidence of double-rounding: fsum is not always correctly
# rounded on machines that suffer from double rounding.
x, y = 1e16, 2.9999 # use temporary values to defeat peephole optimizer
HAVE_DOUBLE_ROUNDING = (x + y == 1e16 + 4)
math_testcases = '/zip/.python/test/math_testcases.txt'
test_file = '/zip/.python/test/cmath_testcases.txt'
def to_ulps(x):
"""Convert a non-NaN float x to an integer, in such a way that
adjacent floats are converted to adjacent integers. Then
abs(ulps(x) - ulps(y)) gives the difference in ulps between two
floats.
The results from this function will only make sense on platforms
where native doubles are represented in IEEE 754 binary64 format.
Note: 0.0 and -0.0 are converted to 0 and -1, respectively.
"""
n = struct.unpack('<q', struct.pack('<d', x))[0]
if n < 0:
n = ~(n+2**63)
return n
def ulp(x):
"""Return the value of the least significant bit of a
float x, such that the first float bigger than x is x+ulp(x).
Then, given an expected result x and a tolerance of n ulps,
the result y should be such that abs(y-x) <= n * ulp(x).
The results from this function will only make sense on platforms
where native doubles are represented in IEEE 754 binary64 format.
"""
x = abs(float(x))
if math.isnan(x) or math.isinf(x):
return x
# Find next float up from x.
n = struct.unpack('<q', struct.pack('<d', x))[0]
x_next = struct.unpack('<d', struct.pack('<q', n + 1))[0]
if math.isinf(x_next):
# Corner case: x was the largest finite float. Then it's
# not an exact power of two, so we can take the difference
# between x and the previous float.
x_prev = struct.unpack('<d', struct.pack('<q', n - 1))[0]
return x - x_prev
else:
return x_next - x
# Here's a pure Python version of the math.factorial algorithm, for
# documentation and comparison purposes.
#
# Formula:
#
# factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n))
#
# where
#
# factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j
#
# The outer product above is an infinite product, but once i >= n.bit_length,
# (n >> i) < 1 and the corresponding term of the product is empty. So only the
# finitely many terms for 0 <= i < n.bit_length() contribute anything.
#
# We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner
# product in the formula above starts at 1 for i == n.bit_length(); for each i
# < n.bit_length() we get the inner product for i from that for i + 1 by
# multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms,
# this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2).
def count_set_bits(n):
"""Number of '1' bits in binary expansion of a nonnnegative integer."""
return 1 + count_set_bits(n & n - 1) if n else 0
def partial_product(start, stop):
"""Product of integers in range(start, stop, 2), computed recursively.
start and stop should both be odd, with start <= stop.
"""
numfactors = (stop - start) >> 1
if not numfactors:
return 1
elif numfactors == 1:
return start
else:
mid = (start + numfactors) | 1
return partial_product(start, mid) * partial_product(mid, stop)
def py_factorial(n):
"""Factorial of nonnegative integer n, via "Binary Split Factorial Formula"
described at http://www.luschny.de/math/factorial/binarysplitfact.html
"""
inner = outer = 1
for i in reversed(range(n.bit_length())):
inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1)
outer *= inner
return outer << (n - count_set_bits(n))
def ulp_abs_check(expected, got, ulp_tol, abs_tol):
"""Given finite floats `expected` and `got`, check that they're
approximately equal to within the given number of ulps or the
given absolute tolerance, whichever is bigger.
Returns None on success and an error message on failure.
"""
ulp_error = abs(to_ulps(expected) - to_ulps(got))
abs_error = abs(expected - got)
# Succeed if either abs_error <= abs_tol or ulp_error <= ulp_tol.
if abs_error <= abs_tol or ulp_error <= ulp_tol:
return None
else:
fmt = ("error = {:.3g} ({:d} ulps); "
"permitted error = {:.3g} or {:d} ulps")
return fmt.format(abs_error, ulp_error, abs_tol, ulp_tol)
def parse_mtestfile(fname):
"""Parse a file with test values
-- starts a comment
blank lines, or lines containing only a comment, are ignored
other lines are expected to have the form
id fn arg -> expected [flag]*
"""
with open(fname) as fp:
for line in fp:
# strip comments, and skip blank lines
if '--' in line:
line = line[:line.index('--')]
if not line.strip():
continue
lhs, rhs = line.split('->')
id, fn, arg = lhs.split()
rhs_pieces = rhs.split()
exp = rhs_pieces[0]
flags = rhs_pieces[1:]
yield (id, fn, float(arg), float(exp), flags)
def parse_testfile(fname):
"""Parse a file with test values
Empty lines or lines starting with -- are ignored
yields id, fn, arg_real, arg_imag, exp_real, exp_imag
"""
with open(fname) as fp:
for line in fp:
# skip comment lines and blank lines
if line.startswith('--') or not line.strip():
continue
lhs, rhs = line.split('->')
id, fn, arg_real, arg_imag = lhs.split()
rhs_pieces = rhs.split()
exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1]
flags = rhs_pieces[2:]
yield (id, fn,
float(arg_real), float(arg_imag),
float(exp_real), float(exp_imag),
flags)
def result_check(expected, got, ulp_tol=5, abs_tol=0.0):
# Common logic of MathTests.(ftest, test_testcases, test_mtestcases)
"""Compare arguments expected and got, as floats, if either
is a float, using a tolerance expressed in multiples of
ulp(expected) or absolutely (if given and greater).
As a convenience, when neither argument is a float, and for
non-finite floats, exact equality is demanded. Also, nan==nan
as far as this function is concerned.
Returns None on success and an error message on failure.
"""
# Check exactly equal (applies also to strings representing exceptions)
if got == expected:
return None
failure = "not equal"
# Turn mixed float and int comparison (e.g. floor()) to all-float
if isinstance(expected, float) and isinstance(got, int):
got = float(got)
elif isinstance(got, float) and isinstance(expected, int):
expected = float(expected)
if isinstance(expected, float) and isinstance(got, float):
if math.isnan(expected) and math.isnan(got):
# Pass, since both nan
failure = None
elif math.isinf(expected) or math.isinf(got):
# We already know they're not equal, drop through to failure
pass
else:
# Both are finite floats (now). Are they close enough?
failure = ulp_abs_check(expected, got, ulp_tol, abs_tol)
# arguments are not equal, and if numeric, are too far apart
if failure is not None:
fail_fmt = "expected {!r}, got {!r}"
fail_msg = fail_fmt.format(expected, got)
fail_msg += ' ({})'.format(failure)
return fail_msg
else:
return None
# Class providing an __index__ method.
class MyIndexable(object):
def __init__(self, value):
self.value = value
def __index__(self):
return self.value
class MathTests(unittest.TestCase):
def ftest(self, name, got, expected, ulp_tol=5, abs_tol=0.0):
"""Compare arguments expected and got, as floats, if either
is a float, using a tolerance expressed in multiples of
ulp(expected) or absolutely, whichever is greater.
As a convenience, when neither argument is a float, and for
non-finite floats, exact equality is demanded. Also, nan==nan
in this function.
"""
failure = result_check(expected, got, ulp_tol, abs_tol)
if failure is not None:
self.fail("{}: {}".format(name, failure))
def testConstants(self):
# Ref: Abramowitz & Stegun (Dover, 1965)
self.ftest('pi', math.pi, 3.141592653589793238462643)
self.ftest('e', math.e, 2.718281828459045235360287)
self.assertEqual(math.tau, 2*math.pi)
def testAcos(self):
self.assertRaises(TypeError, math.acos)
self.ftest('acos(-1)', math.acos(-1), math.pi)
self.ftest('acos(0)', math.acos(0), math.pi/2)
self.ftest('acos(1)', math.acos(1), 0)
self.assertRaises(ValueError, math.acos, INF)
self.assertRaises(ValueError, math.acos, NINF)
self.assertRaises(ValueError, math.acos, 1 + eps)
self.assertRaises(ValueError, math.acos, -1 - eps)
self.assertTrue(math.isnan(math.acos(NAN)))
def testAcosh(self):
self.assertRaises(TypeError, math.acosh)
self.ftest('acosh(1)', math.acosh(1), 0)
self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168)
self.assertRaises(ValueError, math.acosh, 0)
self.assertRaises(ValueError, math.acosh, -1)
self.assertEqual(math.acosh(INF), INF)
self.assertRaises(ValueError, math.acosh, NINF)
self.assertTrue(math.isnan(math.acosh(NAN)))
def testAsin(self):
self.assertRaises(TypeError, math.asin)
self.ftest('asin(-1)', math.asin(-1), -math.pi/2)
self.ftest('asin(0)', math.asin(0), 0)
self.ftest('asin(1)', math.asin(1), math.pi/2)
self.assertRaises(ValueError, math.asin, INF)
self.assertRaises(ValueError, math.asin, NINF)
self.assertRaises(ValueError, math.asin, 1 + eps)
self.assertRaises(ValueError, math.asin, -1 - eps)
self.assertTrue(math.isnan(math.asin(NAN)))
def testAsinh(self):
self.assertRaises(TypeError, math.asinh)
self.ftest('asinh(0)', math.asinh(0), 0)
self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305)
self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305)
self.assertEqual(math.asinh(INF), INF)
self.assertEqual(math.asinh(NINF), NINF)
self.assertTrue(math.isnan(math.asinh(NAN)))
def testAtan(self):
self.assertRaises(TypeError, math.atan)
self.ftest('atan(-1)', math.atan(-1), -math.pi/4)
self.ftest('atan(0)', math.atan(0), 0)
self.ftest('atan(1)', math.atan(1), math.pi/4)
self.ftest('atan(inf)', math.atan(INF), math.pi/2)
self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
self.assertTrue(math.isnan(math.atan(NAN)))
def testAtanh(self):
self.assertRaises(TypeError, math.atan)
self.ftest('atanh(0)', math.atanh(0), 0)
self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489)
self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489)
self.assertRaises(ValueError, math.atanh, 1)
self.assertRaises(ValueError, math.atanh, -1)
self.assertRaises(ValueError, math.atanh, INF)
self.assertRaises(ValueError, math.atanh, NINF)
self.assertTrue(math.isnan(math.atanh(NAN)))
def testAtan2(self):
self.assertRaises(TypeError, math.atan2)
self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2)
self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4)
self.ftest('atan2(0, 1)', math.atan2(0, 1), 0)
self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4)
self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2)
# math.atan2(0, x)
self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi)
self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi)
self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi)
self.assertEqual(math.atan2(0., 0.), 0.)
self.assertEqual(math.atan2(0., 2.3), 0.)
self.assertEqual(math.atan2(0., INF), 0.)
self.assertTrue(math.isnan(math.atan2(0., NAN)))
# math.atan2(-0, x)
self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi)
self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi)
self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi)
self.assertEqual(math.atan2(-0., 0.), -0.)
self.assertEqual(math.atan2(-0., 2.3), -0.)
self.assertEqual(math.atan2(-0., INF), -0.)
self.assertTrue(math.isnan(math.atan2(-0., NAN)))
# math.atan2(INF, x)
self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4)
self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2)
self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2)
self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2)
self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2)
self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4)
self.assertTrue(math.isnan(math.atan2(INF, NAN)))
# math.atan2(NINF, x)
self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4)
self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2)
self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2)
self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2)
self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2)
self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4)
self.assertTrue(math.isnan(math.atan2(NINF, NAN)))
# math.atan2(+finite, x)
self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi)
self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2)
self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2)
self.assertEqual(math.atan2(2.3, INF), 0.)
self.assertTrue(math.isnan(math.atan2(2.3, NAN)))
# math.atan2(-finite, x)
self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi)
self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2)
self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2)
self.assertEqual(math.atan2(-2.3, INF), -0.)
self.assertTrue(math.isnan(math.atan2(-2.3, NAN)))
# math.atan2(NAN, x)
self.assertTrue(math.isnan(math.atan2(NAN, NINF)))
self.assertTrue(math.isnan(math.atan2(NAN, -2.3)))
self.assertTrue(math.isnan(math.atan2(NAN, -0.)))
self.assertTrue(math.isnan(math.atan2(NAN, 0.)))
self.assertTrue(math.isnan(math.atan2(NAN, 2.3)))
self.assertTrue(math.isnan(math.atan2(NAN, INF)))
self.assertTrue(math.isnan(math.atan2(NAN, NAN)))
def testCeil(self):
self.assertRaises(TypeError, math.ceil)
self.assertEqual(int, type(math.ceil(0.5)))
self.ftest('ceil(0.5)', math.ceil(0.5), 1)
self.ftest('ceil(1.0)', math.ceil(1.0), 1)
self.ftest('ceil(1.5)', math.ceil(1.5), 2)
self.ftest('ceil(-0.5)', math.ceil(-0.5), 0)
self.ftest('ceil(-1.0)', math.ceil(-1.0), -1)
self.ftest('ceil(-1.5)', math.ceil(-1.5), -1)
#self.assertEqual(math.ceil(INF), INF)
#self.assertEqual(math.ceil(NINF), NINF)
#self.assertTrue(math.isnan(math.ceil(NAN)))
class TestCeil:
def __ceil__(self):
return 42
class TestNoCeil:
pass
self.ftest('ceil(TestCeil())', math.ceil(TestCeil()), 42)
self.assertRaises(TypeError, math.ceil, TestNoCeil())
t = TestNoCeil()
t.__ceil__ = lambda *args: args
self.assertRaises(TypeError, math.ceil, t)
self.assertRaises(TypeError, math.ceil, t, 0)
@requires_IEEE_754
def testCopysign(self):
self.assertEqual(math.copysign(1, 42), 1.0)
self.assertEqual(math.copysign(0., 42), 0.0)
self.assertEqual(math.copysign(1., -42), -1.0)
self.assertEqual(math.copysign(3, 0.), 3.0)
self.assertEqual(math.copysign(4., -0.), -4.0)
self.assertRaises(TypeError, math.copysign)
# copysign should let us distinguish signs of zeros
self.assertEqual(math.copysign(1., 0.), 1.)
self.assertEqual(math.copysign(1., -0.), -1.)
self.assertEqual(math.copysign(INF, 0.), INF)
self.assertEqual(math.copysign(INF, -0.), NINF)
self.assertEqual(math.copysign(NINF, 0.), INF)
self.assertEqual(math.copysign(NINF, -0.), NINF)
# and of infinities
self.assertEqual(math.copysign(1., INF), 1.)
self.assertEqual(math.copysign(1., NINF), -1.)
self.assertEqual(math.copysign(INF, INF), INF)
self.assertEqual(math.copysign(INF, NINF), NINF)
self.assertEqual(math.copysign(NINF, INF), INF)
self.assertEqual(math.copysign(NINF, NINF), NINF)
self.assertTrue(math.isnan(math.copysign(NAN, 1.)))
self.assertTrue(math.isnan(math.copysign(NAN, INF)))
self.assertTrue(math.isnan(math.copysign(NAN, NINF)))
self.assertTrue(math.isnan(math.copysign(NAN, NAN)))
# copysign(INF, NAN) may be INF or it may be NINF, since
# we don't know whether the sign bit of NAN is set on any
# given platform.
self.assertTrue(math.isinf(math.copysign(INF, NAN)))
# similarly, copysign(2., NAN) could be 2. or -2.
self.assertEqual(abs(math.copysign(2., NAN)), 2.)
def testCos(self):
self.assertRaises(TypeError, math.cos)
self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0, abs_tol=ulp(1))
self.ftest('cos(0)', math.cos(0), 1)
self.ftest('cos(pi/2)', math.cos(math.pi/2), 0, abs_tol=ulp(1))
self.ftest('cos(pi)', math.cos(math.pi), -1)
try:
self.assertTrue(math.isnan(math.cos(INF)))
self.assertTrue(math.isnan(math.cos(NINF)))
except ValueError:
self.assertRaises(ValueError, math.cos, INF)
self.assertRaises(ValueError, math.cos, NINF)
self.assertTrue(math.isnan(math.cos(NAN)))
def testCosh(self):
self.assertRaises(TypeError, math.cosh)
self.ftest('cosh(0)', math.cosh(0), 1)
self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert
self.assertEqual(math.cosh(INF), INF)
self.assertEqual(math.cosh(NINF), INF)
self.assertTrue(math.isnan(math.cosh(NAN)))
def testDegrees(self):
self.assertRaises(TypeError, math.degrees)
self.ftest('degrees(pi)', math.degrees(math.pi), 180.0)
self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0)
self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0)
self.ftest('degrees(0)', math.degrees(0), 0)
def testExp(self):
self.assertRaises(TypeError, math.exp)
self.ftest('exp(-1)', math.exp(-1), 1/math.e)
self.ftest('exp(0)', math.exp(0), 1)
self.ftest('exp(1)', math.exp(1), math.e)
self.assertEqual(math.exp(INF), INF)
self.assertEqual(math.exp(NINF), 0.)
self.assertTrue(math.isnan(math.exp(NAN)))
self.assertRaises(OverflowError, math.exp, 1000000)
def testFabs(self):
self.assertRaises(TypeError, math.fabs)
self.ftest('fabs(-1)', math.fabs(-1), 1)
self.ftest('fabs(0)', math.fabs(0), 0)
self.ftest('fabs(1)', math.fabs(1), 1)
def testFactorial(self):
self.assertEqual(math.factorial(0), 1)
self.assertEqual(math.factorial(0.0), 1)
total = 1
for i in range(1, 1000):
total *= i
self.assertEqual(math.factorial(i), total)
self.assertEqual(math.factorial(float(i)), total)
self.assertEqual(math.factorial(i), py_factorial(i))
self.assertRaises(ValueError, math.factorial, -1)
self.assertRaises(ValueError, math.factorial, -1.0)
self.assertRaises(ValueError, math.factorial, -10**100)
self.assertRaises(ValueError, math.factorial, -1e100)
self.assertRaises(ValueError, math.factorial, math.pi)
# Other implementations may place different upper bounds.
@support.cpython_only
def testFactorialHugeInputs(self):
# Currently raises ValueError for inputs that are too large
# to fit into a C long.
self.assertRaises(OverflowError, math.factorial, 10**100)
self.assertRaises(OverflowError, math.factorial, 1e100)
def testFloor(self):
self.assertRaises(TypeError, math.floor)
self.assertEqual(int, type(math.floor(0.5)))
self.ftest('floor(0.5)', math.floor(0.5), 0)
self.ftest('floor(1.0)', math.floor(1.0), 1)
self.ftest('floor(1.5)', math.floor(1.5), 1)
self.ftest('floor(-0.5)', math.floor(-0.5), -1)
self.ftest('floor(-1.0)', math.floor(-1.0), -1)
self.ftest('floor(-1.5)', math.floor(-1.5), -2)
# pow() relies on floor() to check for integers
# This fails on some platforms - so check it here
self.ftest('floor(1.23e167)', math.floor(1.23e167), 1.23e167)
self.ftest('floor(-1.23e167)', math.floor(-1.23e167), -1.23e167)
#self.assertEqual(math.ceil(INF), INF)
#self.assertEqual(math.ceil(NINF), NINF)
#self.assertTrue(math.isnan(math.floor(NAN)))
class TestFloor:
def __floor__(self):
return 42
class TestNoFloor:
pass
self.ftest('floor(TestFloor())', math.floor(TestFloor()), 42)
self.assertRaises(TypeError, math.floor, TestNoFloor())
t = TestNoFloor()
t.__floor__ = lambda *args: args
self.assertRaises(TypeError, math.floor, t)
self.assertRaises(TypeError, math.floor, t, 0)
def testFmod(self):
self.assertRaises(TypeError, math.fmod)
self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0)
self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0)
self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0)
self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0)
self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0)
self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0)
self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
self.assertTrue(math.isnan(math.fmod(1., NAN)))
self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
self.assertRaises(ValueError, math.fmod, 1., 0.)
self.assertRaises(ValueError, math.fmod, INF, 1.)
self.assertRaises(ValueError, math.fmod, NINF, 1.)
self.assertRaises(ValueError, math.fmod, INF, 0.)
self.assertEqual(math.fmod(3.0, INF), 3.0)
self.assertEqual(math.fmod(-3.0, INF), -3.0)
self.assertEqual(math.fmod(3.0, NINF), 3.0)
self.assertEqual(math.fmod(-3.0, NINF), -3.0)
self.assertEqual(math.fmod(0.0, 3.0), 0.0)
self.assertEqual(math.fmod(0.0, NINF), 0.0)
def testFrexp(self):
self.assertRaises(TypeError, math.frexp)
def testfrexp(name, result, expected):
(mant, exp), (emant, eexp) = result, expected
if abs(mant-emant) > eps or exp != eexp:
self.fail('%s returned %r, expected %r'%\
(name, result, expected))
testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
testfrexp('frexp(0)', math.frexp(0), (0, 0))
testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
testfrexp('frexp(2)', math.frexp(2), (0.5, 2))
self.assertEqual(math.frexp(INF)[0], INF)
self.assertEqual(math.frexp(NINF)[0], NINF)
self.assertTrue(math.isnan(math.frexp(NAN)[0]))
@requires_IEEE_754
@unittest.skipIf(HAVE_DOUBLE_ROUNDING,
"fsum is not exact on machines with double rounding")
def testFsum(self):
# math.fsum relies on exact rounding for correct operation.
# There's a known problem with IA32 floating-point that causes
# inexact rounding in some situations, and will cause the
# math.fsum tests below to fail; see issue #2937. On non IEEE
# 754 platforms, and on IEEE 754 platforms that exhibit the
# problem described in issue #2937, we simply skip the whole
# test.
# Python version of math.fsum, for comparison. Uses a
# different algorithm based on frexp, ldexp and integer
# arithmetic.
from sys import float_info
mant_dig = float_info.mant_dig
etiny = float_info.min_exp - mant_dig
def msum(iterable):
"""Full precision summation. Compute sum(iterable) without any
intermediate accumulation of error. Based on the 'lsum' function
at http://code.activestate.com/recipes/393090/
"""
tmant, texp = 0, 0
for x in iterable:
mant, exp = math.frexp(x)
mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig
if texp > exp:
tmant <<= texp-exp
texp = exp
else:
mant <<= exp-texp
tmant += mant
# Round tmant * 2**texp to a float. The original recipe
# used float(str(tmant)) * 2.0**texp for this, but that's
# a little unsafe because str -> float conversion can't be
# relied upon to do correct rounding on all platforms.
tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp)
if tail > 0:
h = 1 << (tail-1)
tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1)
texp += tail
return math.ldexp(tmant, texp)
test_values = [
([], 0.0),
([0.0], 0.0),
([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100),
([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0),
([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0),
([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0),
([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0),
([1./n for n in range(1, 1001)],
float.fromhex('0x1.df11f45f4e61ap+2')),
([(-1.)**n/n for n in range(1, 1001)],
float.fromhex('-0x1.62a2af1bd3624p-1')),
([1.7**(i+1)-1.7**i for i in range(1000)] + [-1.7**1000], -1.0),
([1e16, 1., 1e-16], 10000000000000002.0),
([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0),
# exercise code for resizing partials array
([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] +
[-2.**1022],
float.fromhex('0x1.5555555555555p+970')),
]
for i, (vals, expected) in enumerate(test_values):
try:
actual = math.fsum(vals)
except OverflowError:
self.fail("test %d failed: got OverflowError, expected %r "
"for math.fsum(%.100r)" % (i, expected, vals))
except ValueError:
self.fail("test %d failed: got ValueError, expected %r "
"for math.fsum(%.100r)" % (i, expected, vals))
self.assertEqual(actual, expected)
from random import random, gauss, shuffle
for j in range(1000):
vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
s = 0
for i in range(200):
v = gauss(0, random()) ** 7 - s
s += v
vals.append(v)
shuffle(vals)
s = msum(vals)
self.assertEqual(msum(vals), math.fsum(vals))
def testGcd(self):
gcd = math.gcd
self.assertEqual(gcd(0, 0), 0)
self.assertEqual(gcd(1, 0), 1)
self.assertEqual(gcd(-1, 0), 1)
self.assertEqual(gcd(0, 1), 1)
self.assertEqual(gcd(0, -1), 1)
self.assertEqual(gcd(7, 1), 1)
self.assertEqual(gcd(7, -1), 1)
self.assertEqual(gcd(-23, 15), 1)
self.assertEqual(gcd(120, 84), 12)
self.assertEqual(gcd(84, -120), 12)
self.assertEqual(gcd(1216342683557601535506311712,
436522681849110124616458784), 32)
c = 652560
x = 434610456570399902378880679233098819019853229470286994367836600566
y = 1064502245825115327754847244914921553977
a = x * c
b = y * c
self.assertEqual(gcd(a, b), c)
self.assertEqual(gcd(b, a), c)
self.assertEqual(gcd(-a, b), c)
self.assertEqual(gcd(b, -a), c)
self.assertEqual(gcd(a, -b), c)
self.assertEqual(gcd(-b, a), c)
self.assertEqual(gcd(-a, -b), c)
self.assertEqual(gcd(-b, -a), c)
c = 576559230871654959816130551884856912003141446781646602790216406874
a = x * c
b = y * c
self.assertEqual(gcd(a, b), c)
self.assertEqual(gcd(b, a), c)
self.assertEqual(gcd(-a, b), c)
self.assertEqual(gcd(b, -a), c)
self.assertEqual(gcd(a, -b), c)
self.assertEqual(gcd(-b, a), c)
self.assertEqual(gcd(-a, -b), c)
self.assertEqual(gcd(-b, -a), c)
self.assertRaises(TypeError, gcd, 120.0, 84)
self.assertRaises(TypeError, gcd, 120, 84.0)
self.assertEqual(gcd(MyIndexable(120), MyIndexable(84)), 12)
def testHypot(self):
self.assertRaises(TypeError, math.hypot)
self.ftest('hypot(0,0)', math.hypot(0,0), 0)
self.ftest('hypot(3,4)', math.hypot(3,4), 5)
self.assertEqual(math.hypot(NAN, INF), INF)
self.assertEqual(math.hypot(INF, NAN), INF)
self.assertEqual(math.hypot(NAN, NINF), INF)
self.assertEqual(math.hypot(NINF, NAN), INF)
self.assertRaises(OverflowError, math.hypot, FLOAT_MAX, FLOAT_MAX)
self.assertTrue(math.isnan(math.hypot(1.0, NAN)))
self.assertTrue(math.isnan(math.hypot(NAN, -2.0)))
def testLdexp(self):
self.assertRaises(TypeError, math.ldexp)
self.ftest('ldexp(0,1)', math.ldexp(0,1), 0)
self.ftest('ldexp(1,1)', math.ldexp(1,1), 2)
self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5)
self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2)
self.assertRaises(OverflowError, math.ldexp, 1., 1000000)
self.assertRaises(OverflowError, math.ldexp, -1., 1000000)
self.assertEqual(math.ldexp(1., -1000000), 0.)
self.assertEqual(math.ldexp(-1., -1000000), -0.)
self.assertEqual(math.ldexp(INF, 30), INF)
self.assertEqual(math.ldexp(NINF, -213), NINF)
self.assertTrue(math.isnan(math.ldexp(NAN, 0)))
# large second argument
for n in [10**5, 10**10, 10**20, 10**40]:
self.assertEqual(math.ldexp(INF, -n), INF)
self.assertEqual(math.ldexp(NINF, -n), NINF)
self.assertEqual(math.ldexp(1., -n), 0.)
self.assertEqual(math.ldexp(-1., -n), -0.)
self.assertEqual(math.ldexp(0., -n), 0.)
self.assertEqual(math.ldexp(-0., -n), -0.)
self.assertTrue(math.isnan(math.ldexp(NAN, -n)))
self.assertRaises(OverflowError, math.ldexp, 1., n)
self.assertRaises(OverflowError, math.ldexp, -1., n)
self.assertEqual(math.ldexp(0., n), 0.)
self.assertEqual(math.ldexp(-0., n), -0.)
self.assertEqual(math.ldexp(INF, n), INF)
self.assertEqual(math.ldexp(NINF, n), NINF)
self.assertTrue(math.isnan(math.ldexp(NAN, n)))
def testLog(self):
self.assertRaises(TypeError, math.log)
self.ftest('log(1/e)', math.log(1/math.e), -1)
self.ftest('log(1)', math.log(1), 0)
self.ftest('log(e)', math.log(math.e), 1)
self.ftest('log(32,2)', math.log(32,2), 5)
self.ftest('log(10**40, 10)', math.log(10**40, 10), 40)
self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2)
self.ftest('log(10**1000)', math.log(10**1000),
2302.5850929940457)
self.assertRaises(ValueError, math.log, -1.5)
self.assertRaises(ValueError, math.log, -10**1000)
self.assertRaises(ValueError, math.log, NINF)
self.assertEqual(math.log(INF), INF)
self.assertTrue(math.isnan(math.log(NAN)))
def testLog1p(self):
self.assertRaises(TypeError, math.log1p)
for n in [2, 2**90, 2**300]:
self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))
self.assertRaises(ValueError, math.log1p, -1)
self.assertEqual(math.log1p(INF), INF)
@requires_IEEE_754
def testLog2(self):
self.assertRaises(TypeError, math.log2)
# Check some integer values
self.assertEqual(math.log2(1), 0.0)
self.assertEqual(math.log2(2), 1.0)
self.assertEqual(math.log2(4), 2.0)
# Large integer values
self.assertEqual(math.log2(2**1023), 1023.0)
self.assertEqual(math.log2(2**1024), 1024.0)
self.assertEqual(math.log2(2**2000), 2000.0)
self.assertRaises(ValueError, math.log2, -1.5)
self.assertRaises(ValueError, math.log2, NINF)
self.assertTrue(math.isnan(math.log2(NAN)))
@requires_IEEE_754
# log2() is not accurate enough on Mac OS X Tiger (10.4)
@support.requires_mac_ver(10, 5)
def testLog2Exact(self):
# Check that we get exact equality for log2 of powers of 2.
actual = [math.log2(math.ldexp(1.0, n)) for n in range(-1074, 1024)]
expected = [float(n) for n in range(-1074, 1024)]
self.assertEqual(actual, expected)
def testLog10(self):
self.assertRaises(TypeError, math.log10)
self.ftest('log10(0.1)', math.log10(0.1), -1)
self.ftest('log10(1)', math.log10(1), 0)
self.ftest('log10(10)', math.log10(10), 1)
self.ftest('log10(10**1000)', math.log10(10**1000), 1000.0)
self.assertRaises(ValueError, math.log10, -1.5)
self.assertRaises(ValueError, math.log10, -10**1000)
self.assertRaises(ValueError, math.log10, NINF)
self.assertEqual(math.log(INF), INF)
self.assertTrue(math.isnan(math.log10(NAN)))
def testModf(self):
self.assertRaises(TypeError, math.modf)
def testmodf(name, result, expected):
(v1, v2), (e1, e2) = result, expected
if abs(v1-e1) > eps or abs(v2-e2):
self.fail('%s returned %r, expected %r'%\
(name, result, expected))
testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
self.assertEqual(math.modf(INF), (0.0, INF))
self.assertEqual(math.modf(NINF), (-0.0, NINF))
modf_nan = math.modf(NAN)
self.assertTrue(math.isnan(modf_nan[0]))
self.assertTrue(math.isnan(modf_nan[1]))
def testPow(self):
self.assertRaises(TypeError, math.pow)
self.ftest('pow(0,1)', math.pow(0,1), 0)
self.ftest('pow(1,0)', math.pow(1,0), 1)
self.ftest('pow(2,1)', math.pow(2,1), 2)
self.ftest('pow(2,-1)', math.pow(2,-1), 0.5)
self.assertEqual(math.pow(INF, 1), INF)
self.assertEqual(math.pow(NINF, 1), NINF)
self.assertEqual((math.pow(1, INF)), 1.)
self.assertEqual((math.pow(1, NINF)), 1.)
self.assertTrue(math.isnan(math.pow(NAN, 1)))
self.assertTrue(math.isnan(math.pow(2, NAN)))
self.assertTrue(math.isnan(math.pow(0, NAN)))
self.assertEqual(math.pow(1, NAN), 1)
# pow(0., x)
self.assertEqual(math.pow(0., INF), 0.)
self.assertEqual(math.pow(0., 3.), 0.)
self.assertEqual(math.pow(0., 2.3), 0.)
self.assertEqual(math.pow(0., 2.), 0.)
self.assertEqual(math.pow(0., 0.), 1.)
self.assertEqual(math.pow(0., -0.), 1.)
self.assertRaises(ValueError, math.pow, 0., -2.)
self.assertRaises(ValueError, math.pow, 0., -2.3)
self.assertRaises(ValueError, math.pow, 0., -3.)
self.assertRaises(ValueError, math.pow, 0., NINF)
self.assertTrue(math.isnan(math.pow(0., NAN)))
# pow(INF, x)
self.assertEqual(math.pow(INF, INF), INF)
self.assertEqual(math.pow(INF, 3.), INF)
self.assertEqual(math.pow(INF, 2.3), INF)
self.assertEqual(math.pow(INF, 2.), INF)
self.assertEqual(math.pow(INF, 0.), 1.)
self.assertEqual(math.pow(INF, -0.), 1.)
self.assertEqual(math.pow(INF, -2.), 0.)
self.assertEqual(math.pow(INF, -2.3), 0.)
self.assertEqual(math.pow(INF, -3.), 0.)
self.assertEqual(math.pow(INF, NINF), 0.)
self.assertTrue(math.isnan(math.pow(INF, NAN)))
# pow(-0., x)
self.assertEqual(math.pow(-0., INF), 0.)
self.assertEqual(math.pow(-0., 3.), -0.)
self.assertEqual(math.pow(-0., 2.3), 0.)
self.assertEqual(math.pow(-0., 2.), 0.)
self.assertEqual(math.pow(-0., 0.), 1.)
self.assertEqual(math.pow(-0., -0.), 1.)
self.assertRaises(ValueError, math.pow, -0., -2.)
self.assertRaises(ValueError, math.pow, -0., -2.3)
self.assertRaises(ValueError, math.pow, -0., -3.)
self.assertRaises(ValueError, math.pow, -0., NINF)
self.assertTrue(math.isnan(math.pow(-0., NAN)))
# pow(NINF, x)
self.assertEqual(math.pow(NINF, INF), INF)
self.assertEqual(math.pow(NINF, 3.), NINF)
self.assertEqual(math.pow(NINF, 2.3), INF)
self.assertEqual(math.pow(NINF, 2.), INF)
self.assertEqual(math.pow(NINF, 0.), 1.)
self.assertEqual(math.pow(NINF, -0.), 1.)
self.assertEqual(math.pow(NINF, -2.), 0.)
self.assertEqual(math.pow(NINF, -2.3), 0.)
self.assertEqual(math.pow(NINF, -3.), -0.)
self.assertEqual(math.pow(NINF, NINF), 0.)
self.assertTrue(math.isnan(math.pow(NINF, NAN)))
# pow(-1, x)
self.assertEqual(math.pow(-1., INF), 1.)
self.assertEqual(math.pow(-1., 3.), -1.)
self.assertRaises(ValueError, math.pow, -1., 2.3)
self.assertEqual(math.pow(-1., 2.), 1.)
self.assertEqual(math.pow(-1., 0.), 1.)
self.assertEqual(math.pow(-1., -0.), 1.)
self.assertEqual(math.pow(-1., -2.), 1.)
self.assertRaises(ValueError, math.pow, -1., -2.3)
self.assertEqual(math.pow(-1., -3.), -1.)
self.assertEqual(math.pow(-1., NINF), 1.)
self.assertTrue(math.isnan(math.pow(-1., NAN)))
# pow(1, x)
self.assertEqual(math.pow(1., INF), 1.)
self.assertEqual(math.pow(1., 3.), 1.)
self.assertEqual(math.pow(1., 2.3), 1.)
self.assertEqual(math.pow(1., 2.), 1.)
self.assertEqual(math.pow(1., 0.), 1.)
self.assertEqual(math.pow(1., -0.), 1.)
self.assertEqual(math.pow(1., -2.), 1.)
self.assertEqual(math.pow(1., -2.3), 1.)
self.assertEqual(math.pow(1., -3.), 1.)
self.assertEqual(math.pow(1., NINF), 1.)
self.assertEqual(math.pow(1., NAN), 1.)
# pow(x, 0) should be 1 for any x
self.assertEqual(math.pow(2.3, 0.), 1.)
self.assertEqual(math.pow(-2.3, 0.), 1.)
self.assertEqual(math.pow(NAN, 0.), 1.)
self.assertEqual(math.pow(2.3, -0.), 1.)
self.assertEqual(math.pow(-2.3, -0.), 1.)
self.assertEqual(math.pow(NAN, -0.), 1.)
# pow(x, y) is invalid if x is negative and y is not integral
self.assertRaises(ValueError, math.pow, -1., 2.3)
self.assertRaises(ValueError, math.pow, -15., -3.1)
# pow(x, NINF)
self.assertEqual(math.pow(1.9, NINF), 0.)
self.assertEqual(math.pow(1.1, NINF), 0.)
self.assertEqual(math.pow(0.9, NINF), INF)
self.assertEqual(math.pow(0.1, NINF), INF)
self.assertEqual(math.pow(-0.1, NINF), INF)
self.assertEqual(math.pow(-0.9, NINF), INF)
self.assertEqual(math.pow(-1.1, NINF), 0.)
self.assertEqual(math.pow(-1.9, NINF), 0.)
# pow(x, INF)
self.assertEqual(math.pow(1.9, INF), INF)
self.assertEqual(math.pow(1.1, INF), INF)
self.assertEqual(math.pow(0.9, INF), 0.)
self.assertEqual(math.pow(0.1, INF), 0.)
self.assertEqual(math.pow(-0.1, INF), 0.)
self.assertEqual(math.pow(-0.9, INF), 0.)
self.assertEqual(math.pow(-1.1, INF), INF)
self.assertEqual(math.pow(-1.9, INF), INF)
# pow(x, y) should work for x negative, y an integer
self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0)
self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0)
self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0)
self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0)
self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0)
self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5)
self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25)
self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125)
self.assertRaises(ValueError, math.pow, -2.0, -0.5)
self.assertRaises(ValueError, math.pow, -2.0, 0.5)
# the following tests have been commented out since they don't
# really belong here: the implementation of ** for floats is
# independent of the implementation of math.pow
#self.assertEqual(1**NAN, 1)
#self.assertEqual(1**INF, 1)
#self.assertEqual(1**NINF, 1)
#self.assertEqual(1**0, 1)
#self.assertEqual(1.**NAN, 1)
#self.assertEqual(1.**INF, 1)
#self.assertEqual(1.**NINF, 1)
#self.assertEqual(1.**0, 1)
def testRadians(self):
self.assertRaises(TypeError, math.radians)
self.ftest('radians(180)', math.radians(180), math.pi)
self.ftest('radians(90)', math.radians(90), math.pi/2)
self.ftest('radians(-45)', math.radians(-45), -math.pi/4)
self.ftest('radians(0)', math.radians(0), 0)
def testSin(self):
self.assertRaises(TypeError, math.sin)
self.ftest('sin(0)', math.sin(0), 0)
self.ftest('sin(pi/2)', math.sin(math.pi/2), 1)
self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1)
try:
self.assertTrue(math.isnan(math.sin(INF)))
self.assertTrue(math.isnan(math.sin(NINF)))
except ValueError:
self.assertRaises(ValueError, math.sin, INF)
self.assertRaises(ValueError, math.sin, NINF)
self.assertTrue(math.isnan(math.sin(NAN)))
def testSinh(self):
self.assertRaises(TypeError, math.sinh)
self.ftest('sinh(0)', math.sinh(0), 0)
self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1)
self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0)
self.assertEqual(math.sinh(INF), INF)
self.assertEqual(math.sinh(NINF), NINF)
self.assertTrue(math.isnan(math.sinh(NAN)))
def testSqrt(self):
self.assertRaises(TypeError, math.sqrt)
self.ftest('sqrt(0)', math.sqrt(0), 0)
self.ftest('sqrt(1)', math.sqrt(1), 1)
self.ftest('sqrt(4)', math.sqrt(4), 2)
self.assertEqual(math.sqrt(INF), INF)
self.assertRaises(ValueError, math.sqrt, -1)
self.assertRaises(ValueError, math.sqrt, NINF)
self.assertTrue(math.isnan(math.sqrt(NAN)))
def testTan(self):
self.assertRaises(TypeError, math.tan)
self.ftest('tan(0)', math.tan(0), 0)
self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
try:
self.assertTrue(math.isnan(math.tan(INF)))
self.assertTrue(math.isnan(math.tan(NINF)))
except:
self.assertRaises(ValueError, math.tan, INF)
self.assertRaises(ValueError, math.tan, NINF)
self.assertTrue(math.isnan(math.tan(NAN)))
def testTanh(self):
self.assertRaises(TypeError, math.tanh)
self.ftest('tanh(0)', math.tanh(0), 0)
self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0,
abs_tol=ulp(1))
self.ftest('tanh(inf)', math.tanh(INF), 1)
self.ftest('tanh(-inf)', math.tanh(NINF), -1)
self.assertTrue(math.isnan(math.tanh(NAN)))
@requires_IEEE_754
@unittest.skipIf(sysconfig.get_config_var('TANH_PRESERVES_ZERO_SIGN') == 0,
"system tanh() function doesn't copy the sign")
def testTanhSign(self):
# check that tanh(-0.) == -0. on IEEE 754 systems
self.assertEqual(math.tanh(-0.), -0.)
self.assertEqual(math.copysign(1., math.tanh(-0.)),
math.copysign(1., -0.))
def test_trunc(self):
self.assertEqual(math.trunc(1), 1)
self.assertEqual(math.trunc(-1), -1)
self.assertEqual(type(math.trunc(1)), int)
self.assertEqual(type(math.trunc(1.5)), int)
self.assertEqual(math.trunc(1.5), 1)
self.assertEqual(math.trunc(-1.5), -1)
self.assertEqual(math.trunc(1.999999), 1)
self.assertEqual(math.trunc(-1.999999), -1)
self.assertEqual(math.trunc(-0.999999), -0)
self.assertEqual(math.trunc(-100.999), -100)
class TestTrunc(object):
def __trunc__(self):
return 23
class TestNoTrunc(object):
pass
self.assertEqual(math.trunc(TestTrunc()), 23)
self.assertRaises(TypeError, math.trunc)
self.assertRaises(TypeError, math.trunc, 1, 2)
self.assertRaises(TypeError, math.trunc, TestNoTrunc())
def testIsfinite(self):
self.assertTrue(math.isfinite(0.0))
self.assertTrue(math.isfinite(-0.0))
self.assertTrue(math.isfinite(1.0))
self.assertTrue(math.isfinite(-1.0))
self.assertFalse(math.isfinite(float("nan")))
self.assertFalse(math.isfinite(float("inf")))
self.assertFalse(math.isfinite(float("-inf")))
def testIsnan(self):
self.assertTrue(math.isnan(float("nan")))
self.assertTrue(math.isnan(float("-nan")))
self.assertTrue(math.isnan(float("inf") * 0.))
self.assertFalse(math.isnan(float("inf")))
self.assertFalse(math.isnan(0.))
self.assertFalse(math.isnan(1.))
def testIsinf(self):
self.assertTrue(math.isinf(float("inf")))
self.assertTrue(math.isinf(float("-inf")))
self.assertTrue(math.isinf(1E400))
self.assertTrue(math.isinf(-1E400))
self.assertFalse(math.isinf(float("nan")))
self.assertFalse(math.isinf(0.))
self.assertFalse(math.isinf(1.))
@requires_IEEE_754
def test_nan_constant(self):
self.assertTrue(math.isnan(math.nan))
@requires_IEEE_754
def test_inf_constant(self):
self.assertTrue(math.isinf(math.inf))
self.assertGreater(math.inf, 0.0)
self.assertEqual(math.inf, float("inf"))
self.assertEqual(-math.inf, float("-inf"))
# RED_FLAG 16-Oct-2000 Tim
# While 2.0 is more consistent about exceptions than previous releases, it
# still fails this part of the test on some platforms. For now, we only
# *run* test_exceptions() in verbose mode, so that this isn't normally
# tested.
@unittest.skipUnless(verbose, 'requires verbose mode')
def test_exceptions(self):
try:
x = math.exp(-1000000000)
except:
# mathmodule.c is failing to weed out underflows from libm, or
# we've got an fp format with huge dynamic range
self.fail("underflowing exp() should not have raised "
"an exception")
if x != 0:
self.fail("underflowing exp() should have returned 0")
# If this fails, probably using a strict IEEE-754 conforming libm, and x
# is +Inf afterwards. But Python wants overflows detected by default.
try:
x = math.exp(1000000000)
except OverflowError:
pass
else:
self.fail("overflowing exp() didn't trigger OverflowError")
# If this fails, it could be a puzzle. One odd possibility is that
# mathmodule.c's macros are getting confused while comparing
# Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE
# as a result (and so raising OverflowError instead).
try:
x = math.sqrt(-1.0)
except ValueError:
pass
else:
self.fail("sqrt(-1) didn't raise ValueError")
@requires_IEEE_754
def test_testfile(self):
# Some tests need to be skipped on ancient OS X versions.
# See issue #27953.
SKIP_ON_TIGER = {'tan0064'}
osx_version = None
if sys.platform == 'darwin':
version_txt = platform.mac_ver()[0]
try:
osx_version = tuple(map(int, version_txt.split('.')))
except ValueError:
pass
fail_fmt = "{}: {}({!r}): {}"
failures = []
for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
# Skip if either the input or result is complex
if ai != 0.0 or ei != 0.0:
continue
if fn in ['rect', 'polar']:
# no real versions of rect, polar
continue
# Skip certain tests on OS X 10.4.
if osx_version is not None and osx_version < (10, 5):
if id in SKIP_ON_TIGER:
continue
func = getattr(math, fn)
if 'invalid' in flags or 'divide-by-zero' in flags:
er = 'ValueError'
elif 'overflow' in flags:
er = 'OverflowError'
try:
result = func(ar)
except ValueError:
result = 'ValueError'
except OverflowError:
result = 'OverflowError'
# Default tolerances
ulp_tol, abs_tol = 5, 0.0
failure = result_check(er, result, ulp_tol, abs_tol)
if failure is None:
continue
msg = fail_fmt.format(id, fn, ar, failure)
failures.append(msg)
if failures:
self.fail('Failures in test_testfile:\n ' +
'\n '.join(failures))
@requires_IEEE_754
def test_mtestfile(self):
fail_fmt = "{}: {}({!r}): {}"
failures = []
for id, fn, arg, expected, flags in parse_mtestfile(math_testcases):
func = getattr(math, fn)
if 'invalid' in flags or 'divide-by-zero' in flags:
expected = 'ValueError'
elif 'overflow' in flags:
expected = 'OverflowError'
try:
got = func(arg)
except ValueError:
got = 'ValueError'
except OverflowError:
got = 'OverflowError'
# Default tolerances
ulp_tol, abs_tol = 5, 0.0
# Exceptions to the defaults
if fn == 'gamma':
# Experimental results on one platform gave
# an accuracy of <= 10 ulps across the entire float
# domain. We weaken that to require 20 ulp accuracy.
ulp_tol = 20
elif fn == 'lgamma':
# we use a weaker accuracy test for lgamma;
# lgamma only achieves an absolute error of
# a few multiples of the machine accuracy, in
# general.
abs_tol = 1e-15
elif fn == 'erfc' and arg >= 0.0:
# erfc has less-than-ideal accuracy for large
# arguments (x ~ 25 or so), mainly due to the
# error involved in computing exp(-x*x).
#
# Observed between CPython and mpmath at 25 dp:
# x < 0 : err <= 2 ulp
# 0 <= x < 1 : err <= 10 ulp
# 1 <= x < 10 : err <= 100 ulp
# 10 <= x < 20 : err <= 300 ulp
# 20 <= x : < 600 ulp
#
if arg < 1.0:
ulp_tol = 10
elif arg < 10.0:
ulp_tol = 100
else:
ulp_tol = 1000
failure = result_check(expected, got, ulp_tol, abs_tol)
if failure is None:
continue
msg = fail_fmt.format(id, fn, arg, failure)
failures.append(msg)
if failures:
self.fail('Failures in test_mtestfile:\n ' +
'\n '.join(failures))
class IsCloseTests(unittest.TestCase):
isclose = math.isclose # subclasses should override this
def assertIsClose(self, a, b, *args, **kwargs):
self.assertTrue(self.isclose(a, b, *args, **kwargs),
msg="%s and %s should be close!" % (a, b))
def assertIsNotClose(self, a, b, *args, **kwargs):
self.assertFalse(self.isclose(a, b, *args, **kwargs),
msg="%s and %s should not be close!" % (a, b))
def assertAllClose(self, examples, *args, **kwargs):
for a, b in examples:
self.assertIsClose(a, b, *args, **kwargs)
def assertAllNotClose(self, examples, *args, **kwargs):
for a, b in examples:
self.assertIsNotClose(a, b, *args, **kwargs)
def test_negative_tolerances(self):
# ValueError should be raised if either tolerance is less than zero
with self.assertRaises(ValueError):
self.assertIsClose(1, 1, rel_tol=-1e-100)
with self.assertRaises(ValueError):
self.assertIsClose(1, 1, rel_tol=1e-100, abs_tol=-1e10)
def test_identical(self):
# identical values must test as close
identical_examples = [(2.0, 2.0),
(0.1e200, 0.1e200),
(1.123e-300, 1.123e-300),
(12345, 12345.0),
(0.0, -0.0),
(345678, 345678)]
self.assertAllClose(identical_examples, rel_tol=0.0, abs_tol=0.0)
def test_eight_decimal_places(self):
# examples that are close to 1e-8, but not 1e-9
eight_decimal_places_examples = [(1e8, 1e8 + 1),
(-1e-8, -1.000000009e-8),
(1.12345678, 1.12345679)]
self.assertAllClose(eight_decimal_places_examples, rel_tol=1e-8)
self.assertAllNotClose(eight_decimal_places_examples, rel_tol=1e-9)
def test_near_zero(self):
# values close to zero
near_zero_examples = [(1e-9, 0.0),
(-1e-9, 0.0),
(-1e-150, 0.0)]
# these should not be close to any rel_tol
self.assertAllNotClose(near_zero_examples, rel_tol=0.9)
# these should be close to abs_tol=1e-8
self.assertAllClose(near_zero_examples, abs_tol=1e-8)
def test_identical_infinite(self):
# these are close regardless of tolerance -- i.e. they are equal
self.assertIsClose(INF, INF)
self.assertIsClose(INF, INF, abs_tol=0.0)
self.assertIsClose(NINF, NINF)
self.assertIsClose(NINF, NINF, abs_tol=0.0)
def test_inf_ninf_nan(self):
# these should never be close (following IEEE 754 rules for equality)
not_close_examples = [(NAN, NAN),
(NAN, 1e-100),
(1e-100, NAN),
(INF, NAN),
(NAN, INF),
(INF, NINF),
(INF, 1.0),
(1.0, INF),
(INF, 1e308),
(1e308, INF)]
# use largest reasonable tolerance
self.assertAllNotClose(not_close_examples, abs_tol=0.999999999999999)
def test_zero_tolerance(self):
# test with zero tolerance
zero_tolerance_close_examples = [(1.0, 1.0),
(-3.4, -3.4),
(-1e-300, -1e-300)]
self.assertAllClose(zero_tolerance_close_examples, rel_tol=0.0)
zero_tolerance_not_close_examples = [(1.0, 1.000000000000001),
(0.99999999999999, 1.0),
(1.0e200, .999999999999999e200)]
self.assertAllNotClose(zero_tolerance_not_close_examples, rel_tol=0.0)
def test_asymmetry(self):
# test the asymmetry example from PEP 485
self.assertAllClose([(9, 10), (10, 9)], rel_tol=0.1)
def test_integers(self):
# test with integer values
integer_examples = [(100000001, 100000000),
(123456789, 123456788)]
self.assertAllClose(integer_examples, rel_tol=1e-8)
self.assertAllNotClose(integer_examples, rel_tol=1e-9)
def test_decimals(self):
# test with Decimal values
from decimal import Decimal
decimal_examples = [(Decimal('1.00000001'), Decimal('1.0')),
(Decimal('1.00000001e-20'), Decimal('1.0e-20')),
(Decimal('1.00000001e-100'), Decimal('1.0e-100')),
(Decimal('1.00000001e20'), Decimal('1.0e20'))]
self.assertAllClose(decimal_examples, rel_tol=1e-8)
self.assertAllNotClose(decimal_examples, rel_tol=1e-9)
def test_fractions(self):
# test with Fraction values
from fractions import Fraction
fraction_examples = [
(Fraction(1, 100000000) + 1, Fraction(1)),
(Fraction(100000001), Fraction(100000000)),
(Fraction(10**8 + 1, 10**28), Fraction(1, 10**20))]
self.assertAllClose(fraction_examples, rel_tol=1e-8)
self.assertAllNotClose(fraction_examples, rel_tol=1e-9)
def test_main():
from doctest import DocFileSuite
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(MathTests))
suite.addTest(unittest.makeSuite(IsCloseTests))
suite.addTest(DocFileSuite("ieee754.txt"))
run_unittest(suite)
if __name__ == '__main__':
test_main()
| 58,806 | 1,417 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_xmlrpc.py | import base64
import datetime
import decimal
import sys
import time
import unittest
from unittest import mock
import xmlrpc.client as xmlrpclib
import xmlrpc.server
import http.client
import http, http.server
import socket
import re
import io
import contextlib
from test import support
from encodings import iso8559_15
try:
import gzip
except ImportError:
gzip = None
try:
import _thread
import threading
except ImportError:
threading = None
alist = [{'astring': '[email protected]',
'afloat': 7283.43,
'anint': 2**20,
'ashortlong': 2,
'anotherlist': ['.zyx.41'],
'abase64': xmlrpclib.Binary(b"my dog has fleas"),
'b64bytes': b"my dog has fleas",
'b64bytearray': bytearray(b"my dog has fleas"),
'boolean': False,
'unicode': '\u4000\u6000\u8000',
'ukey\u4000': 'regular value',
'datetime1': xmlrpclib.DateTime('20050210T11:41:23'),
'datetime2': xmlrpclib.DateTime(
(2005, 2, 10, 11, 41, 23, 0, 1, -1)),
'datetime3': xmlrpclib.DateTime(
datetime.datetime(2005, 2, 10, 11, 41, 23)),
}]
class XMLRPCTestCase(unittest.TestCase):
def test_dump_load(self):
dump = xmlrpclib.dumps((alist,))
load = xmlrpclib.loads(dump)
self.assertEqual(alist, load[0][0])
def test_dump_bare_datetime(self):
# This checks that an unwrapped datetime.date object can be handled
# by the marshalling code. This can't be done via test_dump_load()
# since with use_builtin_types set to 1 the unmarshaller would create
# datetime objects for the 'datetime[123]' keys as well
dt = datetime.datetime(2005, 2, 10, 11, 41, 23)
self.assertEqual(dt, xmlrpclib.DateTime('20050210T11:41:23'))
s = xmlrpclib.dumps((dt,))
result, m = xmlrpclib.loads(s, use_builtin_types=True)
(newdt,) = result
self.assertEqual(newdt, dt)
self.assertIs(type(newdt), datetime.datetime)
self.assertIsNone(m)
result, m = xmlrpclib.loads(s, use_builtin_types=False)
(newdt,) = result
self.assertEqual(newdt, dt)
self.assertIs(type(newdt), xmlrpclib.DateTime)
self.assertIsNone(m)
result, m = xmlrpclib.loads(s, use_datetime=True)
(newdt,) = result
self.assertEqual(newdt, dt)
self.assertIs(type(newdt), datetime.datetime)
self.assertIsNone(m)
result, m = xmlrpclib.loads(s, use_datetime=False)
(newdt,) = result
self.assertEqual(newdt, dt)
self.assertIs(type(newdt), xmlrpclib.DateTime)
self.assertIsNone(m)
def test_datetime_before_1900(self):
# same as before but with a date before 1900
dt = datetime.datetime(1, 2, 10, 11, 41, 23)
self.assertEqual(dt, xmlrpclib.DateTime('00010210T11:41:23'))
s = xmlrpclib.dumps((dt,))
result, m = xmlrpclib.loads(s, use_builtin_types=True)
(newdt,) = result
self.assertEqual(newdt, dt)
self.assertIs(type(newdt), datetime.datetime)
self.assertIsNone(m)
result, m = xmlrpclib.loads(s, use_builtin_types=False)
(newdt,) = result
self.assertEqual(newdt, dt)
self.assertIs(type(newdt), xmlrpclib.DateTime)
self.assertIsNone(m)
def test_bug_1164912 (self):
d = xmlrpclib.DateTime()
((new_d,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((d,),
methodresponse=True))
self.assertIsInstance(new_d.value, str)
# Check that the output of dumps() is still an 8-bit string
s = xmlrpclib.dumps((new_d,), methodresponse=True)
self.assertIsInstance(s, str)
def test_newstyle_class(self):
class T(object):
pass
t = T()
t.x = 100
t.y = "Hello"
((t2,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((t,)))
self.assertEqual(t2, t.__dict__)
def test_dump_big_long(self):
self.assertRaises(OverflowError, xmlrpclib.dumps, (2**99,))
def test_dump_bad_dict(self):
self.assertRaises(TypeError, xmlrpclib.dumps, ({(1,2,3): 1},))
def test_dump_recursive_seq(self):
l = [1,2,3]
t = [3,4,5,l]
l.append(t)
self.assertRaises(TypeError, xmlrpclib.dumps, (l,))
def test_dump_recursive_dict(self):
d = {'1':1, '2':1}
t = {'3':3, 'd':d}
d['t'] = t
self.assertRaises(TypeError, xmlrpclib.dumps, (d,))
def test_dump_big_int(self):
if sys.maxsize > 2**31-1:
self.assertRaises(OverflowError, xmlrpclib.dumps,
(int(2**34),))
xmlrpclib.dumps((xmlrpclib.MAXINT, xmlrpclib.MININT))
self.assertRaises(OverflowError, xmlrpclib.dumps,
(xmlrpclib.MAXINT+1,))
self.assertRaises(OverflowError, xmlrpclib.dumps,
(xmlrpclib.MININT-1,))
def dummy_write(s):
pass
m = xmlrpclib.Marshaller()
m.dump_int(xmlrpclib.MAXINT, dummy_write)
m.dump_int(xmlrpclib.MININT, dummy_write)
self.assertRaises(OverflowError, m.dump_int,
xmlrpclib.MAXINT+1, dummy_write)
self.assertRaises(OverflowError, m.dump_int,
xmlrpclib.MININT-1, dummy_write)
def test_dump_double(self):
xmlrpclib.dumps((float(2 ** 34),))
xmlrpclib.dumps((float(xmlrpclib.MAXINT),
float(xmlrpclib.MININT)))
xmlrpclib.dumps((float(xmlrpclib.MAXINT + 42),
float(xmlrpclib.MININT - 42)))
def dummy_write(s):
pass
m = xmlrpclib.Marshaller()
m.dump_double(xmlrpclib.MAXINT, dummy_write)
m.dump_double(xmlrpclib.MININT, dummy_write)
m.dump_double(xmlrpclib.MAXINT + 42, dummy_write)
m.dump_double(xmlrpclib.MININT - 42, dummy_write)
def test_dump_none(self):
value = alist + [None]
arg1 = (alist + [None],)
strg = xmlrpclib.dumps(arg1, allow_none=True)
self.assertEqual(value,
xmlrpclib.loads(strg)[0][0])
self.assertRaises(TypeError, xmlrpclib.dumps, (arg1,))
def test_dump_encoding(self):
return
value = {'key\u20ac\xa4':
'value\u20ac\xa4'}
strg = xmlrpclib.dumps((value,), encoding='iso-8859-15')
strg = "<?xml version='1.0' encoding='iso-8859-15'?>" + strg
self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
strg = strg.encode('iso-8859-15', 'xmlcharrefreplace')
self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
strg = xmlrpclib.dumps((value,), encoding='iso-8859-15',
methodresponse=True)
self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
strg = strg.encode('iso-8859-15', 'xmlcharrefreplace')
self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
methodname = 'method\u20ac\xa4'
strg = xmlrpclib.dumps((value,), encoding='iso-8859-15',
methodname=methodname)
self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
self.assertEqual(xmlrpclib.loads(strg)[1], methodname)
def test_dump_bytes(self):
sample = b"my dog has fleas"
self.assertEqual(sample, xmlrpclib.Binary(sample))
for type_ in bytes, bytearray, xmlrpclib.Binary:
value = type_(sample)
s = xmlrpclib.dumps((value,))
result, m = xmlrpclib.loads(s, use_builtin_types=True)
(newvalue,) = result
self.assertEqual(newvalue, sample)
self.assertIs(type(newvalue), bytes)
self.assertIsNone(m)
result, m = xmlrpclib.loads(s, use_builtin_types=False)
(newvalue,) = result
self.assertEqual(newvalue, sample)
self.assertIs(type(newvalue), xmlrpclib.Binary)
self.assertIsNone(m)
def test_loads_unsupported(self):
ResponseError = xmlrpclib.ResponseError
data = '<params><param><value><spam/></value></param></params>'
self.assertRaises(ResponseError, xmlrpclib.loads, data)
data = ('<params><param><value><array>'
'<value><spam/></value>'
'</array></value></param></params>')
self.assertRaises(ResponseError, xmlrpclib.loads, data)
data = ('<params><param><value><struct>'
'<member><name>a</name><value><spam/></value></member>'
'<member><name>b</name><value><spam/></value></member>'
'</struct></value></param></params>')
self.assertRaises(ResponseError, xmlrpclib.loads, data)
def check_loads(self, s, value, **kwargs):
dump = '<params><param><value>%s</value></param></params>' % s
result, m = xmlrpclib.loads(dump, **kwargs)
(newvalue,) = result
self.assertEqual(newvalue, value)
self.assertIs(type(newvalue), type(value))
self.assertIsNone(m)
def test_load_standard_types(self):
check = self.check_loads
check('string', 'string')
check('<string>string</string>', 'string')
check('<string>ðð«ð¦ð ð¬ð¡ð¢ string</string>', 'ðð«ð¦ð ð¬ð¡ð¢ string')
check('<int>2056183947</int>', 2056183947)
check('<int>-2056183947</int>', -2056183947)
check('<i4>2056183947</i4>', 2056183947)
check('<double>46093.78125</double>', 46093.78125)
check('<boolean>0</boolean>', False)
check('<base64>AGJ5dGUgc3RyaW5n/w==</base64>',
xmlrpclib.Binary(b'\x00byte string\xff'))
check('<base64>AGJ5dGUgc3RyaW5n/w==</base64>',
b'\x00byte string\xff', use_builtin_types=True)
check('<dateTime.iso8601>20050210T11:41:23</dateTime.iso8601>',
xmlrpclib.DateTime('20050210T11:41:23'))
check('<dateTime.iso8601>20050210T11:41:23</dateTime.iso8601>',
datetime.datetime(2005, 2, 10, 11, 41, 23),
use_builtin_types=True)
check('<array><data>'
'<value><int>1</int></value><value><int>2</int></value>'
'</data></array>', [1, 2])
check('<struct>'
'<member><name>b</name><value><int>2</int></value></member>'
'<member><name>a</name><value><int>1</int></value></member>'
'</struct>', {'a': 1, 'b': 2})
def test_load_extension_types(self):
check = self.check_loads
check('<nil/>', None)
check('<ex:nil/>', None)
check('<i1>205</i1>', 205)
check('<i2>20561</i2>', 20561)
check('<i8>9876543210</i8>', 9876543210)
check('<biginteger>98765432100123456789</biginteger>',
98765432100123456789)
check('<float>93.78125</float>', 93.78125)
check('<bigdecimal>9876543210.0123456789</bigdecimal>',
decimal.Decimal('9876543210.0123456789'))
def test_get_host_info(self):
# see bug #3613, this raised a TypeError
transp = xmlrpc.client.Transport()
self.assertEqual(transp.get_host_info("[email protected]"),
('host.tld',
[('Authorization', 'Basic dXNlcg==')], {}))
def test_ssl_presence(self):
try:
import ssl
except ImportError:
has_ssl = False
else:
has_ssl = True
try:
xmlrpc.client.ServerProxy('https://localhost:9999').bad_function()
except NotImplementedError:
self.assertFalse(has_ssl, "xmlrpc client's error with SSL support")
except OSError:
self.assertTrue(has_ssl)
@unittest.skipUnless(threading, "Threading required for this test.")
def test_keepalive_disconnect(self):
class RequestHandler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
handled = False
def do_POST(self):
length = int(self.headers.get("Content-Length"))
self.rfile.read(length)
if self.handled:
self.close_connection = True
return
response = xmlrpclib.dumps((5,), methodresponse=True)
response = response.encode()
self.send_response(http.HTTPStatus.OK)
self.send_header("Content-Length", len(response))
self.end_headers()
self.wfile.write(response)
self.handled = True
self.close_connection = False
def log_message(self, format, *args):
# don't clobber sys.stderr
pass
def run_server():
server.socket.settimeout(float(1)) # Don't hang if client fails
server.handle_request() # First request and attempt at second
server.handle_request() # Retried second request
server = http.server.HTTPServer((support.HOST, 0), RequestHandler)
self.addCleanup(server.server_close)
thread = threading.Thread(target=run_server)
thread.start()
self.addCleanup(thread.join)
url = "http://{}:{}/".format(*server.server_address)
with xmlrpclib.ServerProxy(url) as p:
self.assertEqual(p.method(), 5)
self.assertEqual(p.method(), 5)
class SimpleXMLRPCDispatcherTestCase(unittest.TestCase):
class DispatchExc(Exception):
"""Raised inside the dispatched functions when checking for
chained exceptions"""
def test_call_registered_func(self):
"""Calls explicitly registered function"""
# Makes sure any exception raised inside the function has no other
# exception chained to it
exp_params = 1, 2, 3
def dispatched_func(*params):
raise self.DispatchExc(params)
dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher()
dispatcher.register_function(dispatched_func)
with self.assertRaises(self.DispatchExc) as exc_ctx:
dispatcher._dispatch('dispatched_func', exp_params)
self.assertEqual(exc_ctx.exception.args, (exp_params,))
self.assertIsNone(exc_ctx.exception.__cause__)
self.assertIsNone(exc_ctx.exception.__context__)
def test_call_instance_func(self):
"""Calls a registered instance attribute as a function"""
# Makes sure any exception raised inside the function has no other
# exception chained to it
exp_params = 1, 2, 3
class DispatchedClass:
def dispatched_func(self, *params):
raise SimpleXMLRPCDispatcherTestCase.DispatchExc(params)
dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher()
dispatcher.register_instance(DispatchedClass())
with self.assertRaises(self.DispatchExc) as exc_ctx:
dispatcher._dispatch('dispatched_func', exp_params)
self.assertEqual(exc_ctx.exception.args, (exp_params,))
self.assertIsNone(exc_ctx.exception.__cause__)
self.assertIsNone(exc_ctx.exception.__context__)
def test_call_dispatch_func(self):
"""Calls the registered instance's `_dispatch` function"""
# Makes sure any exception raised inside the function has no other
# exception chained to it
exp_method = 'method'
exp_params = 1, 2, 3
class TestInstance:
def _dispatch(self, method, params):
raise SimpleXMLRPCDispatcherTestCase.DispatchExc(
method, params)
dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher()
dispatcher.register_instance(TestInstance())
with self.assertRaises(self.DispatchExc) as exc_ctx:
dispatcher._dispatch(exp_method, exp_params)
self.assertEqual(exc_ctx.exception.args, (exp_method, exp_params))
self.assertIsNone(exc_ctx.exception.__cause__)
self.assertIsNone(exc_ctx.exception.__context__)
def test_registered_func_is_none(self):
"""Calls explicitly registered function which is None"""
dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher()
dispatcher.register_function(None, name='method')
with self.assertRaisesRegex(Exception, 'method'):
dispatcher._dispatch('method', ('param',))
def test_instance_has_no_func(self):
"""Attempts to call nonexistent function on a registered instance"""
dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher()
dispatcher.register_instance(object())
with self.assertRaisesRegex(Exception, 'method'):
dispatcher._dispatch('method', ('param',))
def test_cannot_locate_func(self):
"""Calls a function that the dispatcher cannot locate"""
dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher()
with self.assertRaisesRegex(Exception, 'method'):
dispatcher._dispatch('method', ('param',))
class HelperTestCase(unittest.TestCase):
def test_escape(self):
self.assertEqual(xmlrpclib.escape("a&b"), "a&b")
self.assertEqual(xmlrpclib.escape("a<b"), "a<b")
self.assertEqual(xmlrpclib.escape("a>b"), "a>b")
class FaultTestCase(unittest.TestCase):
def test_repr(self):
f = xmlrpclib.Fault(42, 'Test Fault')
self.assertEqual(repr(f), "<Fault 42: 'Test Fault'>")
self.assertEqual(repr(f), str(f))
def test_dump_fault(self):
f = xmlrpclib.Fault(42, 'Test Fault')
s = xmlrpclib.dumps((f,))
(newf,), m = xmlrpclib.loads(s)
self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'})
self.assertEqual(m, None)
s = xmlrpclib.Marshaller().dumps(f)
self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s)
def test_dotted_attribute(self):
# this will raise AttributeError because code don't want us to use
# private methods
self.assertRaises(AttributeError,
xmlrpc.server.resolve_dotted_attribute, str, '__add')
self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title'))
class DateTimeTestCase(unittest.TestCase):
def test_default(self):
with mock.patch('time.localtime') as localtime_mock:
time_struct = time.struct_time(
[2013, 7, 15, 0, 24, 49, 0, 196, 0])
localtime_mock.return_value = time_struct
localtime = time.localtime()
t = xmlrpclib.DateTime()
self.assertEqual(str(t),
time.strftime("%Y%m%dT%H:%M:%S", localtime))
def test_time(self):
d = 1181399930.036952
t = xmlrpclib.DateTime(d)
self.assertEqual(str(t),
time.strftime("%Y%m%dT%H:%M:%S", time.localtime(d)))
def test_time_tuple(self):
d = (2007,6,9,10,38,50,5,160,0)
t = xmlrpclib.DateTime(d)
self.assertEqual(str(t), '20070609T10:38:50')
def test_time_struct(self):
d = time.localtime(1181399930.036952)
t = xmlrpclib.DateTime(d)
self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", d))
def test_datetime_datetime(self):
d = datetime.datetime(2007,1,2,3,4,5)
t = xmlrpclib.DateTime(d)
self.assertEqual(str(t), '20070102T03:04:05')
def test_repr(self):
d = datetime.datetime(2007,1,2,3,4,5)
t = xmlrpclib.DateTime(d)
val ="<DateTime '20070102T03:04:05' at %#x>" % id(t)
self.assertEqual(repr(t), val)
def test_decode(self):
d = ' 20070908T07:11:13 '
t1 = xmlrpclib.DateTime()
t1.decode(d)
tref = xmlrpclib.DateTime(datetime.datetime(2007,9,8,7,11,13))
self.assertEqual(t1, tref)
t2 = xmlrpclib._datetime(d)
self.assertEqual(t2, tref)
def test_comparison(self):
now = datetime.datetime.now()
dtime = xmlrpclib.DateTime(now.timetuple())
# datetime vs. DateTime
self.assertTrue(dtime == now)
self.assertTrue(now == dtime)
then = now + datetime.timedelta(seconds=4)
self.assertTrue(then >= dtime)
self.assertTrue(dtime < then)
# str vs. DateTime
dstr = now.strftime("%Y%m%dT%H:%M:%S")
self.assertTrue(dtime == dstr)
self.assertTrue(dstr == dtime)
dtime_then = xmlrpclib.DateTime(then.timetuple())
self.assertTrue(dtime_then >= dstr)
self.assertTrue(dstr < dtime_then)
# some other types
dbytes = dstr.encode('ascii')
dtuple = now.timetuple()
with self.assertRaises(TypeError):
dtime == 1970
with self.assertRaises(TypeError):
dtime != dbytes
with self.assertRaises(TypeError):
dtime == bytearray(dbytes)
with self.assertRaises(TypeError):
dtime != dtuple
with self.assertRaises(TypeError):
dtime < float(1970)
with self.assertRaises(TypeError):
dtime > dbytes
with self.assertRaises(TypeError):
dtime <= bytearray(dbytes)
with self.assertRaises(TypeError):
dtime >= dtuple
class BinaryTestCase(unittest.TestCase):
# XXX What should str(Binary(b"\xff")) return? I'm chosing "\xff"
# for now (i.e. interpreting the binary data as Latin-1-encoded
# text). But this feels very unsatisfactory. Perhaps we should
# only define repr(), and return r"Binary(b'\xff')" instead?
def test_default(self):
t = xmlrpclib.Binary()
self.assertEqual(str(t), '')
def test_string(self):
d = b'\x01\x02\x03abc123\xff\xfe'
t = xmlrpclib.Binary(d)
self.assertEqual(str(t), str(d, "latin-1"))
def test_decode(self):
d = b'\x01\x02\x03abc123\xff\xfe'
de = base64.encodebytes(d)
t1 = xmlrpclib.Binary()
t1.decode(de)
self.assertEqual(str(t1), str(d, "latin-1"))
t2 = xmlrpclib._binary(de)
self.assertEqual(str(t2), str(d, "latin-1"))
ADDR = PORT = URL = None
# The evt is set twice. First when the server is ready to serve.
# Second when the server has been shutdown. The user must clear
# the event after it has been set the first time to catch the second set.
def http_server(evt, numrequests, requestHandler=None, encoding=None):
class TestInstanceClass:
def div(self, x, y):
return x // y
def _methodHelp(self, name):
if name == 'div':
return 'This is the div function'
class Fixture:
@staticmethod
def getData():
return '42'
def my_function():
'''This is my function'''
return True
class MyXMLRPCServer(xmlrpc.server.SimpleXMLRPCServer):
def get_request(self):
# Ensure the socket is always non-blocking. On Linux, socket
# attributes are not inherited like they are on *BSD and Windows.
s, port = self.socket.accept()
s.setblocking(True)
return s, port
if not requestHandler:
requestHandler = xmlrpc.server.SimpleXMLRPCRequestHandler
serv = MyXMLRPCServer(("localhost", 0), requestHandler,
encoding=encoding,
logRequests=False, bind_and_activate=False)
try:
serv.server_bind()
global ADDR, PORT, URL
ADDR, PORT = serv.socket.getsockname()
#connect to IP address directly. This avoids socket.create_connection()
#trying to connect to "localhost" using all address families, which
#causes slowdown e.g. on vista which supports AF_INET6. The server listens
#on AF_INET only.
URL = "http://%s:%d"%(ADDR, PORT)
serv.server_activate()
serv.register_introspection_functions()
serv.register_multicall_functions()
serv.register_function(pow)
serv.register_function(lambda x,y: x+y, 'add')
serv.register_function(lambda x: x, 'têšt')
serv.register_function(my_function)
testInstance = TestInstanceClass()
serv.register_instance(testInstance, allow_dotted_names=True)
evt.set()
# handle up to 'numrequests' requests
while numrequests > 0:
serv.handle_request()
numrequests -= 1
except socket.timeout:
pass
finally:
serv.socket.close()
PORT = None
evt.set()
def http_multi_server(evt, numrequests, requestHandler=None):
class TestInstanceClass:
def div(self, x, y):
return x // y
def _methodHelp(self, name):
if name == 'div':
return 'This is the div function'
def my_function():
'''This is my function'''
return True
class MyXMLRPCServer(xmlrpc.server.MultiPathXMLRPCServer):
def get_request(self):
# Ensure the socket is always non-blocking. On Linux, socket
# attributes are not inherited like they are on *BSD and Windows.
s, port = self.socket.accept()
s.setblocking(True)
return s, port
if not requestHandler:
requestHandler = xmlrpc.server.SimpleXMLRPCRequestHandler
class MyRequestHandler(requestHandler):
rpc_paths = []
class BrokenDispatcher:
def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
raise RuntimeError("broken dispatcher")
serv = MyXMLRPCServer(("localhost", 0), MyRequestHandler,
logRequests=False, bind_and_activate=False)
serv.socket.settimeout(3)
serv.server_bind()
try:
global ADDR, PORT, URL
ADDR, PORT = serv.socket.getsockname()
#connect to IP address directly. This avoids socket.create_connection()
#trying to connect to "localhost" using all address families, which
#causes slowdown e.g. on vista which supports AF_INET6. The server listens
#on AF_INET only.
URL = "http://%s:%d"%(ADDR, PORT)
serv.server_activate()
paths = ["/foo", "/foo/bar"]
for path in paths:
d = serv.add_dispatcher(path, xmlrpc.server.SimpleXMLRPCDispatcher())
d.register_introspection_functions()
d.register_multicall_functions()
serv.get_dispatcher(paths[0]).register_function(pow)
serv.get_dispatcher(paths[1]).register_function(lambda x,y: x+y, 'add')
serv.add_dispatcher("/is/broken", BrokenDispatcher())
evt.set()
# handle up to 'numrequests' requests
while numrequests > 0:
serv.handle_request()
numrequests -= 1
except socket.timeout:
pass
finally:
serv.socket.close()
PORT = None
evt.set()
# This function prevents errors like:
# <ProtocolError for localhost:57527/RPC2: 500 Internal Server Error>
def is_unavailable_exception(e):
'''Returns True if the given ProtocolError is the product of a server-side
exception caused by the 'temporarily unavailable' response sometimes
given by operations on non-blocking sockets.'''
# sometimes we get a -1 error code and/or empty headers
try:
if e.errcode == -1 or e.headers is None:
return True
exc_mess = e.headers.get('X-exception')
except AttributeError:
# Ignore OSErrors here.
exc_mess = str(e)
if exc_mess and 'temporarily unavailable' in exc_mess.lower():
return True
def make_request_and_skipIf(condition, reason):
# If we skip the test, we have to make a request because
# the server created in setUp blocks expecting one to come in.
if not condition:
return lambda func: func
def decorator(func):
def make_request_and_skip(self):
try:
xmlrpclib.ServerProxy(URL).my_function()
except (xmlrpclib.ProtocolError, OSError) as e:
if not is_unavailable_exception(e):
raise
raise unittest.SkipTest(reason)
return make_request_and_skip
return decorator
@unittest.skipUnless(threading, 'Threading required for this test.')
class BaseServerTestCase(unittest.TestCase):
requestHandler = None
request_count = 1
threadFunc = staticmethod(http_server)
def setUp(self):
# enable traceback reporting
xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True
self.evt = threading.Event()
# start server thread to handle requests
serv_args = (self.evt, self.request_count, self.requestHandler)
thread = threading.Thread(target=self.threadFunc, args=serv_args)
thread.start()
self.addCleanup(thread.join)
# wait for the server to be ready
self.evt.wait()
self.evt.clear()
def tearDown(self):
# wait on the server thread to terminate
self.evt.wait()
# disable traceback reporting
xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = False
class SimpleServerTestCase(BaseServerTestCase):
def test_simple1(self):
try:
p = xmlrpclib.ServerProxy(URL)
self.assertEqual(p.pow(6,8), 6**8)
except (xmlrpclib.ProtocolError, OSError) as e:
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
def test_nonascii(self):
start_string = 'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t'
end_string = 'h\N{LATIN SMALL LETTER O WITH HORN}n'
try:
p = xmlrpclib.ServerProxy(URL)
self.assertEqual(p.add(start_string, end_string),
start_string + end_string)
except (xmlrpclib.ProtocolError, OSError) as e:
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
def test_client_encoding(self):
start_string = '\u20ac'
end_string = '\xa4'
try:
p = xmlrpclib.ServerProxy(URL, encoding='iso-8859-15')
self.assertEqual(p.add(start_string, end_string),
start_string + end_string)
except (xmlrpclib.ProtocolError, socket.error) as e:
# ignore failures due to non-blocking socket unavailable errors.
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
def test_nonascii_methodname(self):
try:
p = xmlrpclib.ServerProxy(URL, encoding='ascii')
self.assertEqual(p.têšt(42), 42)
except (xmlrpclib.ProtocolError, socket.error) as e:
# ignore failures due to non-blocking socket unavailable errors.
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
# [ch] The test 404 is causing lots of false alarms.
def XXXtest_404(self):
# send POST with http.client, it should return 404 header and
# 'Not Found' message.
conn = httplib.client.HTTPConnection(ADDR, PORT)
conn.request('POST', '/this-is-not-valid')
response = conn.getresponse()
conn.close()
self.assertEqual(response.status, 404)
self.assertEqual(response.reason, 'Not Found')
def test_introspection1(self):
expected_methods = set(['pow', 'div', 'my_function', 'add', 'têšt',
'system.listMethods', 'system.methodHelp',
'system.methodSignature', 'system.multicall',
'Fixture'])
try:
p = xmlrpclib.ServerProxy(URL)
meth = p.system.listMethods()
self.assertEqual(set(meth), expected_methods)
except (xmlrpclib.ProtocolError, OSError) as e:
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
def test_introspection2(self):
try:
# test _methodHelp()
p = xmlrpclib.ServerProxy(URL)
divhelp = p.system.methodHelp('div')
self.assertEqual(divhelp, 'This is the div function')
except (xmlrpclib.ProtocolError, OSError) as e:
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
@make_request_and_skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
def test_introspection3(self):
try:
# test native doc
p = xmlrpclib.ServerProxy(URL)
myfunction = p.system.methodHelp('my_function')
self.assertEqual(myfunction, 'This is my function')
except (xmlrpclib.ProtocolError, OSError) as e:
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
def test_introspection4(self):
# the SimpleXMLRPCServer doesn't support signatures, but
# at least check that we can try making the call
try:
p = xmlrpclib.ServerProxy(URL)
divsig = p.system.methodSignature('div')
self.assertEqual(divsig, 'signatures not supported')
except (xmlrpclib.ProtocolError, OSError) as e:
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
def test_multicall(self):
try:
p = xmlrpclib.ServerProxy(URL)
multicall = xmlrpclib.MultiCall(p)
multicall.add(2,3)
multicall.pow(6,8)
multicall.div(127,42)
add_result, pow_result, div_result = multicall()
self.assertEqual(add_result, 2+3)
self.assertEqual(pow_result, 6**8)
self.assertEqual(div_result, 127//42)
except (xmlrpclib.ProtocolError, OSError) as e:
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
def test_non_existing_multicall(self):
try:
p = xmlrpclib.ServerProxy(URL)
multicall = xmlrpclib.MultiCall(p)
multicall.this_is_not_exists()
result = multicall()
# result.results contains;
# [{'faultCode': 1, 'faultString': '<class \'exceptions.Exception\'>:'
# 'method "this_is_not_exists" is not supported'>}]
self.assertEqual(result.results[0]['faultCode'], 1)
self.assertEqual(result.results[0]['faultString'],
'<class \'Exception\'>:method "this_is_not_exists" '
'is not supported')
except (xmlrpclib.ProtocolError, OSError) as e:
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
def test_dotted_attribute(self):
# Raises an AttributeError because private methods are not allowed.
self.assertRaises(AttributeError,
xmlrpc.server.resolve_dotted_attribute, str, '__add')
self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title'))
# Get the test to run faster by sending a request with test_simple1.
# This avoids waiting for the socket timeout.
self.test_simple1()
def test_allow_dotted_names_true(self):
# XXX also need allow_dotted_names_false test.
server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT))
data = server.Fixture.getData()
self.assertEqual(data, '42')
def test_unicode_host(self):
server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT))
self.assertEqual(server.add("a", "\xe9"), "a\xe9")
def test_partial_post(self):
# Check that a partial POST doesn't make the server loop: issue #14001.
conn = http.client.HTTPConnection(ADDR, PORT)
conn.send('POST /RPC2 HTTP/1.0\r\n'
'Content-Length: 100\r\n\r\n'
'bye HTTP/1.1\r\n'
f'Host: {ADDR}:{PORT}\r\n'
'Accept-Encoding: identity\r\n'
'Content-Length: 0\r\n\r\n'.encode('ascii'))
conn.close()
def test_context_manager(self):
with xmlrpclib.ServerProxy(URL) as server:
server.add(2, 3)
self.assertNotEqual(server('transport')._connection,
(None, None))
self.assertEqual(server('transport')._connection,
(None, None))
def test_context_manager_method_error(self):
try:
with xmlrpclib.ServerProxy(URL) as server:
server.add(2, "a")
except xmlrpclib.Fault:
pass
self.assertEqual(server('transport')._connection,
(None, None))
class SimpleServerEncodingTestCase(BaseServerTestCase):
@staticmethod
def threadFunc(evt, numrequests, requestHandler=None, encoding=None):
http_server(evt, numrequests, requestHandler, 'iso-8859-15')
def test_server_encoding(self):
start_string = '\u20ac'
end_string = '\xa4'
try:
p = xmlrpclib.ServerProxy(URL)
self.assertEqual(p.add(start_string, end_string),
start_string + end_string)
except (xmlrpclib.ProtocolError, socket.error) as e:
# ignore failures due to non-blocking socket unavailable errors.
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
class MultiPathServerTestCase(BaseServerTestCase):
threadFunc = staticmethod(http_multi_server)
request_count = 2
def test_path1(self):
p = xmlrpclib.ServerProxy(URL+"/foo")
self.assertEqual(p.pow(6,8), 6**8)
self.assertRaises(xmlrpclib.Fault, p.add, 6, 8)
def test_path2(self):
p = xmlrpclib.ServerProxy(URL+"/foo/bar")
self.assertEqual(p.add(6,8), 6+8)
self.assertRaises(xmlrpclib.Fault, p.pow, 6, 8)
def test_path3(self):
p = xmlrpclib.ServerProxy(URL+"/is/broken")
self.assertRaises(xmlrpclib.Fault, p.add, 6, 8)
#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
#does indeed serve subsequent requests on the same connection
class BaseKeepaliveServerTestCase(BaseServerTestCase):
#a request handler that supports keep-alive and logs requests into a
#class variable
class RequestHandler(xmlrpc.server.SimpleXMLRPCRequestHandler):
parentClass = xmlrpc.server.SimpleXMLRPCRequestHandler
protocol_version = 'HTTP/1.1'
myRequests = []
def handle(self):
self.myRequests.append([])
self.reqidx = len(self.myRequests)-1
return self.parentClass.handle(self)
def handle_one_request(self):
result = self.parentClass.handle_one_request(self)
self.myRequests[self.reqidx].append(self.raw_requestline)
return result
requestHandler = RequestHandler
def setUp(self):
#clear request log
self.RequestHandler.myRequests = []
return BaseServerTestCase.setUp(self)
#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
#does indeed serve subsequent requests on the same connection
class KeepaliveServerTestCase1(BaseKeepaliveServerTestCase):
def test_two(self):
p = xmlrpclib.ServerProxy(URL)
#do three requests.
self.assertEqual(p.pow(6,8), 6**8)
self.assertEqual(p.pow(6,8), 6**8)
self.assertEqual(p.pow(6,8), 6**8)
p("close")()
#they should have all been handled by a single request handler
self.assertEqual(len(self.RequestHandler.myRequests), 1)
#check that we did at least two (the third may be pending append
#due to thread scheduling)
self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
#test special attribute access on the serverproxy, through the __call__
#function.
class KeepaliveServerTestCase2(BaseKeepaliveServerTestCase):
#ask for two keepalive requests to be handled.
request_count=2
def test_close(self):
p = xmlrpclib.ServerProxy(URL)
#do some requests with close.
self.assertEqual(p.pow(6,8), 6**8)
self.assertEqual(p.pow(6,8), 6**8)
self.assertEqual(p.pow(6,8), 6**8)
p("close")() #this should trigger a new keep-alive request
self.assertEqual(p.pow(6,8), 6**8)
self.assertEqual(p.pow(6,8), 6**8)
self.assertEqual(p.pow(6,8), 6**8)
p("close")()
#they should have all been two request handlers, each having logged at least
#two complete requests
self.assertEqual(len(self.RequestHandler.myRequests), 2)
self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
self.assertGreaterEqual(len(self.RequestHandler.myRequests[-2]), 2)
def test_transport(self):
p = xmlrpclib.ServerProxy(URL)
#do some requests with close.
self.assertEqual(p.pow(6,8), 6**8)
p("transport").close() #same as above, really.
self.assertEqual(p.pow(6,8), 6**8)
p("close")()
self.assertEqual(len(self.RequestHandler.myRequests), 2)
#A test case that verifies that gzip encoding works in both directions
#(for a request and the response)
@unittest.skipIf(gzip is None, 'requires gzip')
class GzipServerTestCase(BaseServerTestCase):
#a request handler that supports keep-alive and logs requests into a
#class variable
class RequestHandler(xmlrpc.server.SimpleXMLRPCRequestHandler):
parentClass = xmlrpc.server.SimpleXMLRPCRequestHandler
protocol_version = 'HTTP/1.1'
def do_POST(self):
#store content of last request in class
self.__class__.content_length = int(self.headers["content-length"])
return self.parentClass.do_POST(self)
requestHandler = RequestHandler
class Transport(xmlrpclib.Transport):
#custom transport, stores the response length for our perusal
fake_gzip = False
def parse_response(self, response):
self.response_length=int(response.getheader("content-length", 0))
return xmlrpclib.Transport.parse_response(self, response)
def send_content(self, connection, body):
if self.fake_gzip:
#add a lone gzip header to induce decode error remotely
connection.putheader("Content-Encoding", "gzip")
return xmlrpclib.Transport.send_content(self, connection, body)
def setUp(self):
BaseServerTestCase.setUp(self)
def test_gzip_request(self):
t = self.Transport()
t.encode_threshold = None
p = xmlrpclib.ServerProxy(URL, transport=t)
self.assertEqual(p.pow(6,8), 6**8)
a = self.RequestHandler.content_length
t.encode_threshold = 0 #turn on request encoding
self.assertEqual(p.pow(6,8), 6**8)
b = self.RequestHandler.content_length
self.assertTrue(a>b)
p("close")()
def test_bad_gzip_request(self):
t = self.Transport()
t.encode_threshold = None
t.fake_gzip = True
p = xmlrpclib.ServerProxy(URL, transport=t)
cm = self.assertRaisesRegex(xmlrpclib.ProtocolError,
re.compile(r"\b400\b"))
with cm:
p.pow(6, 8)
p("close")()
def test_gzip_response(self):
t = self.Transport()
p = xmlrpclib.ServerProxy(URL, transport=t)
old = self.requestHandler.encode_threshold
self.requestHandler.encode_threshold = None #no encoding
self.assertEqual(p.pow(6,8), 6**8)
a = t.response_length
self.requestHandler.encode_threshold = 0 #always encode
self.assertEqual(p.pow(6,8), 6**8)
p("close")()
b = t.response_length
self.requestHandler.encode_threshold = old
self.assertTrue(a>b)
@unittest.skipIf(gzip is None, 'requires gzip')
class GzipUtilTestCase(unittest.TestCase):
def test_gzip_decode_limit(self):
max_gzip_decode = 20 * 1024 * 1024
data = b'\0' * max_gzip_decode
encoded = xmlrpclib.gzip_encode(data)
decoded = xmlrpclib.gzip_decode(encoded)
self.assertEqual(len(decoded), max_gzip_decode)
data = b'\0' * (max_gzip_decode + 1)
encoded = xmlrpclib.gzip_encode(data)
with self.assertRaisesRegex(ValueError,
"max gzipped payload length exceeded"):
xmlrpclib.gzip_decode(encoded)
xmlrpclib.gzip_decode(encoded, max_decode=-1)
#Test special attributes of the ServerProxy object
class ServerProxyTestCase(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
# Actual value of the URL doesn't matter if it is a string in
# the correct format.
self.url = 'http://fake.localhost'
def test_close(self):
p = xmlrpclib.ServerProxy(self.url)
self.assertEqual(p('close')(), None)
def test_transport(self):
t = xmlrpclib.Transport()
p = xmlrpclib.ServerProxy(self.url, transport=t)
self.assertEqual(p('transport'), t)
# This is a contrived way to make a failure occur on the server side
# in order to test the _send_traceback_header flag on the server
class FailingMessageClass(http.client.HTTPMessage):
def get(self, key, failobj=None):
key = key.lower()
if key == 'content-length':
return 'I am broken'
return super().get(key, failobj)
@unittest.skipUnless(threading, 'Threading required for this test.')
class FailingServerTestCase(unittest.TestCase):
def setUp(self):
self.evt = threading.Event()
# start server thread to handle requests
serv_args = (self.evt, 1)
thread = threading.Thread(target=http_server, args=serv_args)
thread.start()
self.addCleanup(thread.join)
# wait for the server to be ready
self.evt.wait()
self.evt.clear()
def tearDown(self):
# wait on the server thread to terminate
self.evt.wait()
# reset flag
xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = False
# reset message class
default_class = http.client.HTTPMessage
xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = default_class
def test_basic(self):
# check that flag is false by default
flagval = xmlrpc.server.SimpleXMLRPCServer._send_traceback_header
self.assertEqual(flagval, False)
# enable traceback reporting
xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True
# test a call that shouldn't fail just as a smoke test
try:
p = xmlrpclib.ServerProxy(URL)
self.assertEqual(p.pow(6,8), 6**8)
except (xmlrpclib.ProtocolError, OSError) as e:
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
def test_fail_no_info(self):
# use the broken message class
xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass
try:
p = xmlrpclib.ServerProxy(URL)
p.pow(6,8)
except (xmlrpclib.ProtocolError, OSError) as e:
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e) and hasattr(e, "headers"):
# The two server-side error headers shouldn't be sent back in this case
self.assertTrue(e.headers.get("X-exception") is None)
self.assertTrue(e.headers.get("X-traceback") is None)
else:
self.fail('ProtocolError not raised')
def test_fail_with_info(self):
# use the broken message class
xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass
# Check that errors in the server send back exception/traceback
# info when flag is set
xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True
try:
p = xmlrpclib.ServerProxy(URL)
p.pow(6,8)
except (xmlrpclib.ProtocolError, OSError) as e:
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e) and hasattr(e, "headers"):
# We should get error info in the response
expected_err = "invalid literal for int() with base 10: 'I am broken'"
self.assertEqual(e.headers.get("X-exception"), expected_err)
self.assertTrue(e.headers.get("X-traceback") is not None)
else:
self.fail('ProtocolError not raised')
@contextlib.contextmanager
def captured_stdout(encoding='utf-8'):
"""A variation on support.captured_stdout() which gives a text stream
having a `buffer` attribute.
"""
orig_stdout = sys.stdout
sys.stdout = io.TextIOWrapper(io.BytesIO(), encoding=encoding)
try:
yield sys.stdout
finally:
sys.stdout = orig_stdout
class CGIHandlerTestCase(unittest.TestCase):
def setUp(self):
self.cgi = xmlrpc.server.CGIXMLRPCRequestHandler()
def tearDown(self):
self.cgi = None
def test_cgi_get(self):
with support.EnvironmentVarGuard() as env:
env['REQUEST_METHOD'] = 'GET'
# if the method is GET and no request_text is given, it runs handle_get
# get sysout output
with captured_stdout(encoding=self.cgi.encoding) as data_out:
self.cgi.handle_request()
# parse Status header
data_out.seek(0)
handle = data_out.read()
status = handle.split()[1]
message = ' '.join(handle.split()[2:4])
self.assertEqual(status, '400')
self.assertEqual(message, 'Bad Request')
def test_cgi_xmlrpc_response(self):
data = """<?xml version='1.0'?>
<methodCall>
<methodName>test_method</methodName>
<params>
<param>
<value><string>foo</string></value>
</param>
<param>
<value><string>bar</string></value>
</param>
</params>
</methodCall>
"""
with support.EnvironmentVarGuard() as env, \
captured_stdout(encoding=self.cgi.encoding) as data_out, \
support.captured_stdin() as data_in:
data_in.write(data)
data_in.seek(0)
env['CONTENT_LENGTH'] = str(len(data))
self.cgi.handle_request()
data_out.seek(0)
# will respond exception, if so, our goal is achieved ;)
handle = data_out.read()
# start with 44th char so as not to get http header, we just
# need only xml
self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, handle[44:])
# Also test the content-length returned by handle_request
# Using the same test method inorder to avoid all the datapassing
# boilerplate code.
# Test for bug: http://bugs.python.org/issue5040
content = handle[handle.find("<?xml"):]
self.assertEqual(
int(re.search(r'Content-Length: (\d+)', handle).group(1)),
len(content))
class UseBuiltinTypesTestCase(unittest.TestCase):
def test_use_builtin_types(self):
# SimpleXMLRPCDispatcher.__init__ accepts use_builtin_types, which
# makes all dispatch of binary data as bytes instances, and all
# dispatch of datetime argument as datetime.datetime instances.
self.log = []
expected_bytes = b"my dog has fleas"
expected_date = datetime.datetime(2008, 5, 26, 18, 25, 12)
marshaled = xmlrpclib.dumps((expected_bytes, expected_date), 'foobar')
def foobar(*args):
self.log.extend(args)
handler = xmlrpc.server.SimpleXMLRPCDispatcher(
allow_none=True, encoding=None, use_builtin_types=True)
handler.register_function(foobar)
handler._marshaled_dispatch(marshaled)
self.assertEqual(len(self.log), 2)
mybytes, mydate = self.log
self.assertEqual(self.log, [expected_bytes, expected_date])
self.assertIs(type(mydate), datetime.datetime)
self.assertIs(type(mybytes), bytes)
def test_cgihandler_has_use_builtin_types_flag(self):
handler = xmlrpc.server.CGIXMLRPCRequestHandler(use_builtin_types=True)
self.assertTrue(handler.use_builtin_types)
def test_xmlrpcserver_has_use_builtin_types_flag(self):
server = xmlrpc.server.SimpleXMLRPCServer(("localhost", 0),
use_builtin_types=True)
server.server_close()
self.assertTrue(server.use_builtin_types)
@support.reap_threads
def test_main():
support.run_unittest(XMLRPCTestCase, HelperTestCase, DateTimeTestCase,
BinaryTestCase, FaultTestCase, UseBuiltinTypesTestCase,
SimpleServerTestCase, SimpleServerEncodingTestCase,
KeepaliveServerTestCase1, KeepaliveServerTestCase2,
GzipServerTestCase, GzipUtilTestCase,
MultiPathServerTestCase, ServerProxyTestCase, FailingServerTestCase,
CGIHandlerTestCase, SimpleXMLRPCDispatcherTestCase)
if __name__ == "__main__":
test_main()
| 55,357 | 1,420 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_dict_version.py | """
Test implementation of the PEP 509: dictionary versionning.
"""
import unittest
from test import support
# PEP 509 is implemented in CPython but other Python implementations
# don't require to implement it
_testcapi = support.import_module('_testcapi')
class DictVersionTests(unittest.TestCase):
type2test = dict
def setUp(self):
self.seen_versions = set()
self.dict = None
def check_version_unique(self, mydict):
version = _testcapi.dict_get_version(mydict)
self.assertNotIn(version, self.seen_versions)
self.seen_versions.add(version)
def check_version_changed(self, mydict, method, *args, **kw):
result = method(*args, **kw)
self.check_version_unique(mydict)
return result
def check_version_dont_change(self, mydict, method, *args, **kw):
version1 = _testcapi.dict_get_version(mydict)
self.seen_versions.add(version1)
result = method(*args, **kw)
version2 = _testcapi.dict_get_version(mydict)
self.assertEqual(version2, version1, "version changed")
return result
def new_dict(self, *args, **kw):
d = self.type2test(*args, **kw)
self.check_version_unique(d)
return d
def test_constructor(self):
# new empty dictionaries must all have an unique version
empty1 = self.new_dict()
empty2 = self.new_dict()
empty3 = self.new_dict()
# non-empty dictionaries must also have an unique version
nonempty1 = self.new_dict(x='x')
nonempty2 = self.new_dict(x='x', y='y')
def test_copy(self):
d = self.new_dict(a=1, b=2)
d2 = self.check_version_dont_change(d, d.copy)
# dict.copy() must create a dictionary with a new unique version
self.check_version_unique(d2)
def test_setitem(self):
d = self.new_dict()
# creating new keys must change the version
self.check_version_changed(d, d.__setitem__, 'x', 'x')
self.check_version_changed(d, d.__setitem__, 'y', 'y')
# changing values must change the version
self.check_version_changed(d, d.__setitem__, 'x', 1)
self.check_version_changed(d, d.__setitem__, 'y', 2)
def test_setitem_same_value(self):
value = object()
d = self.new_dict()
# setting a key must change the version
self.check_version_changed(d, d.__setitem__, 'key', value)
# setting a key to the same value with dict.__setitem__
# must change the version
self.check_version_changed(d, d.__setitem__, 'key', value)
# setting a key to the same value with dict.update
# must change the version
self.check_version_changed(d, d.update, key=value)
d2 = self.new_dict(key=value)
self.check_version_changed(d, d.update, d2)
def test_setitem_equal(self):
class AlwaysEqual:
def __eq__(self, other):
return True
value1 = AlwaysEqual()
value2 = AlwaysEqual()
self.assertTrue(value1 == value2)
self.assertFalse(value1 != value2)
d = self.new_dict()
self.check_version_changed(d, d.__setitem__, 'key', value1)
# setting a key to a value equal to the current value
# with dict.__setitem__() must change the version
self.check_version_changed(d, d.__setitem__, 'key', value2)
# setting a key to a value equal to the current value
# with dict.update() must change the version
self.check_version_changed(d, d.update, key=value1)
d2 = self.new_dict(key=value2)
self.check_version_changed(d, d.update, d2)
def test_setdefault(self):
d = self.new_dict()
# setting a key with dict.setdefault() must change the version
self.check_version_changed(d, d.setdefault, 'key', 'value1')
# don't change the version if the key already exists
self.check_version_dont_change(d, d.setdefault, 'key', 'value2')
def test_delitem(self):
d = self.new_dict(key='value')
# deleting a key with dict.__delitem__() must change the version
self.check_version_changed(d, d.__delitem__, 'key')
# don't change the version if the key doesn't exist
self.check_version_dont_change(d, self.assertRaises, KeyError,
d.__delitem__, 'key')
def test_pop(self):
d = self.new_dict(key='value')
# pop() must change the version if the key exists
self.check_version_changed(d, d.pop, 'key')
# pop() must not change the version if the key does not exist
self.check_version_dont_change(d, self.assertRaises, KeyError,
d.pop, 'key')
def test_popitem(self):
d = self.new_dict(key='value')
# popitem() must change the version if the dict is not empty
self.check_version_changed(d, d.popitem)
# popitem() must not change the version if the dict is empty
self.check_version_dont_change(d, self.assertRaises, KeyError,
d.popitem)
def test_update(self):
d = self.new_dict(key='value')
# update() calling with no argument must not change the version
self.check_version_dont_change(d, d.update)
# update() must change the version
self.check_version_changed(d, d.update, key='new value')
d2 = self.new_dict(key='value 3')
self.check_version_changed(d, d.update, d2)
def test_clear(self):
d = self.new_dict(key='value')
# clear() must change the version if the dict is not empty
self.check_version_changed(d, d.clear)
# clear() must not change the version if the dict is empty
self.check_version_dont_change(d, d.clear)
class Dict(dict):
pass
class DictSubtypeVersionTests(DictVersionTests):
type2test = Dict
if __name__ == "__main__":
unittest.main()
| 6,010 | 187 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_urllib.py | """Regression tests for what was in Python 2's "urllib" module"""
import urllib.parse
import urllib.request
import urllib.error
import http.client
import email.message
import io
import unittest
from unittest.mock import patch
from test import support
import os
try:
import ssl
except ImportError:
ssl = None
import sys
import tempfile
import warnings
from nturl2path import url2pathname, pathname2url
from base64 import b64encode
import collections
def hexescape(char):
"""Escape char as RFC 2396 specifies"""
hex_repr = hex(ord(char))[2:].upper()
if len(hex_repr) == 1:
hex_repr = "0%s" % hex_repr
return "%" + hex_repr
# Shortcut for testing FancyURLopener
_urlopener = None
def urlopen(url, data=None, proxies=None):
"""urlopen(url [, data]) -> open file-like object"""
global _urlopener
if proxies is not None:
opener = urllib.request.FancyURLopener(proxies=proxies)
elif not _urlopener:
opener = FancyURLopener()
_urlopener = opener
else:
opener = _urlopener
if data is None:
return opener.open(url)
else:
return opener.open(url, data)
def FancyURLopener():
with support.check_warnings(
('FancyURLopener style of invoking requests is deprecated.',
DeprecationWarning)):
return urllib.request.FancyURLopener()
def fakehttp(fakedata):
class FakeSocket(io.BytesIO):
io_refs = 1
def sendall(self, data):
FakeHTTPConnection.buf = data
def makefile(self, *args, **kwds):
self.io_refs += 1
return self
def read(self, amt=None):
if self.closed:
return b""
return io.BytesIO.read(self, amt)
def readline(self, length=None):
if self.closed:
return b""
return io.BytesIO.readline(self, length)
def close(self):
self.io_refs -= 1
if self.io_refs == 0:
io.BytesIO.close(self)
class FakeHTTPConnection(http.client.HTTPConnection):
# buffer to store data for verification in urlopen tests.
buf = None
def connect(self):
self.sock = FakeSocket(self.fakedata)
type(self).fakesock = self.sock
FakeHTTPConnection.fakedata = fakedata
return FakeHTTPConnection
class FakeHTTPMixin(object):
def fakehttp(self, fakedata):
self._connection_class = http.client.HTTPConnection
http.client.HTTPConnection = fakehttp(fakedata)
def unfakehttp(self):
http.client.HTTPConnection = self._connection_class
class FakeFTPMixin(object):
def fakeftp(self):
class FakeFtpWrapper(object):
def __init__(self, user, passwd, host, port, dirs, timeout=None,
persistent=True):
pass
def retrfile(self, file, type):
return io.BytesIO(), 0
def close(self):
pass
self._ftpwrapper_class = urllib.request.ftpwrapper
urllib.request.ftpwrapper = FakeFtpWrapper
def unfakeftp(self):
urllib.request.ftpwrapper = self._ftpwrapper_class
class urlopen_FileTests(unittest.TestCase):
"""Test urlopen() opening a temporary file.
Try to test as much functionality as possible so as to cut down on reliance
on connecting to the Net for testing.
"""
def setUp(self):
# Create a temp file to use for testing
self.text = bytes("test_urllib: %s\n" % self.__class__.__name__,
"ascii")
f = open(support.TESTFN, 'wb')
try:
f.write(self.text)
finally:
f.close()
self.pathname = support.TESTFN
self.returned_obj = urlopen("file:%s" % self.pathname)
def tearDown(self):
"""Shut down the open object"""
self.returned_obj.close()
os.remove(support.TESTFN)
def test_interface(self):
# Make sure object returned by urlopen() has the specified methods
for attr in ("read", "readline", "readlines", "fileno",
"close", "info", "geturl", "getcode", "__iter__"):
self.assertTrue(hasattr(self.returned_obj, attr),
"object returned by urlopen() lacks %s attribute" %
attr)
def test_read(self):
self.assertEqual(self.text, self.returned_obj.read())
def test_readline(self):
self.assertEqual(self.text, self.returned_obj.readline())
self.assertEqual(b'', self.returned_obj.readline(),
"calling readline() after exhausting the file did not"
" return an empty string")
def test_readlines(self):
lines_list = self.returned_obj.readlines()
self.assertEqual(len(lines_list), 1,
"readlines() returned the wrong number of lines")
self.assertEqual(lines_list[0], self.text,
"readlines() returned improper text")
def test_fileno(self):
file_num = self.returned_obj.fileno()
self.assertIsInstance(file_num, int, "fileno() did not return an int")
self.assertEqual(os.read(file_num, len(self.text)), self.text,
"Reading on the file descriptor returned by fileno() "
"did not return the expected text")
def test_close(self):
# Test close() by calling it here and then having it be called again
# by the tearDown() method for the test
self.returned_obj.close()
def test_info(self):
self.assertIsInstance(self.returned_obj.info(), email.message.Message)
def test_geturl(self):
self.assertEqual(self.returned_obj.geturl(), self.pathname)
def test_getcode(self):
self.assertIsNone(self.returned_obj.getcode())
def test_iter(self):
# Test iterator
# Don't need to count number of iterations since test would fail the
# instant it returned anything beyond the first line from the
# comparison.
# Use the iterator in the usual implicit way to test for ticket #4608.
for line in self.returned_obj:
self.assertEqual(line, self.text)
def test_relativelocalfile(self):
self.assertRaises(ValueError,urllib.request.urlopen,'./' + self.pathname)
class ProxyTests(unittest.TestCase):
def setUp(self):
# Records changes to env vars
self.env = support.EnvironmentVarGuard()
# Delete all proxy related env vars
for k in list(os.environ):
if 'proxy' in k.lower():
self.env.unset(k)
def tearDown(self):
# Restore all proxy related env vars
self.env.__exit__()
del self.env
def test_getproxies_environment_keep_no_proxies(self):
self.env.set('NO_PROXY', 'localhost')
proxies = urllib.request.getproxies_environment()
# getproxies_environment use lowered case truncated (no '_proxy') keys
self.assertEqual('localhost', proxies['no'])
# List of no_proxies with space.
self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com:1234')
self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com'))
self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888'))
self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234'))
def test_proxy_cgi_ignore(self):
try:
self.env.set('HTTP_PROXY', 'http://somewhere:3128')
proxies = urllib.request.getproxies_environment()
self.assertEqual('http://somewhere:3128', proxies['http'])
self.env.set('REQUEST_METHOD', 'GET')
proxies = urllib.request.getproxies_environment()
self.assertNotIn('http', proxies)
finally:
self.env.unset('REQUEST_METHOD')
self.env.unset('HTTP_PROXY')
def test_proxy_bypass_environment_host_match(self):
bypass = urllib.request.proxy_bypass_environment
self.env.set('NO_PROXY',
'localhost, anotherdomain.com, newdomain.com:1234, .d.o.t')
self.assertTrue(bypass('localhost'))
self.assertTrue(bypass('LocalHost')) # MixedCase
self.assertTrue(bypass('LOCALHOST')) # UPPERCASE
self.assertTrue(bypass('newdomain.com:1234'))
self.assertTrue(bypass('foo.d.o.t')) # issue 29142
self.assertTrue(bypass('anotherdomain.com:8888'))
self.assertTrue(bypass('www.newdomain.com:1234'))
self.assertFalse(bypass('prelocalhost'))
self.assertFalse(bypass('newdomain.com')) # no port
self.assertFalse(bypass('newdomain.com:1235')) # wrong port
class ProxyTests_withOrderedEnv(unittest.TestCase):
def setUp(self):
# We need to test conditions, where variable order _is_ significant
self._saved_env = os.environ
# Monkey patch os.environ, start with empty fake environment
os.environ = collections.OrderedDict()
def tearDown(self):
os.environ = self._saved_env
def test_getproxies_environment_prefer_lowercase(self):
# Test lowercase preference with removal
os.environ['no_proxy'] = ''
os.environ['No_Proxy'] = 'localhost'
self.assertFalse(urllib.request.proxy_bypass_environment('localhost'))
self.assertFalse(urllib.request.proxy_bypass_environment('arbitrary'))
os.environ['http_proxy'] = ''
os.environ['HTTP_PROXY'] = 'http://somewhere:3128'
proxies = urllib.request.getproxies_environment()
self.assertEqual({}, proxies)
# Test lowercase preference of proxy bypass and correct matching including ports
os.environ['no_proxy'] = 'localhost, noproxy.com, my.proxy:1234'
os.environ['No_Proxy'] = 'xyz.com'
self.assertTrue(urllib.request.proxy_bypass_environment('localhost'))
self.assertTrue(urllib.request.proxy_bypass_environment('noproxy.com:5678'))
self.assertTrue(urllib.request.proxy_bypass_environment('my.proxy:1234'))
self.assertFalse(urllib.request.proxy_bypass_environment('my.proxy'))
self.assertFalse(urllib.request.proxy_bypass_environment('arbitrary'))
# Test lowercase preference with replacement
os.environ['http_proxy'] = 'http://somewhere:3128'
os.environ['Http_Proxy'] = 'http://somewhereelse:3128'
proxies = urllib.request.getproxies_environment()
self.assertEqual('http://somewhere:3128', proxies['http'])
class urlopen_HttpTests(unittest.TestCase, FakeHTTPMixin, FakeFTPMixin):
"""Test urlopen() opening a fake http connection."""
def check_read(self, ver):
self.fakehttp(b"HTTP/" + ver + b" 200 OK\r\n\r\nHello!")
try:
fp = urlopen("http://python.org/")
self.assertEqual(fp.readline(), b"Hello!")
self.assertEqual(fp.readline(), b"")
self.assertEqual(fp.geturl(), 'http://python.org/')
self.assertEqual(fp.getcode(), 200)
finally:
self.unfakehttp()
def test_url_fragment(self):
# Issue #11703: geturl() omits fragments in the original URL.
url = 'http://docs.python.org/library/urllib.html#OK'
self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello!")
try:
fp = urllib.request.urlopen(url)
self.assertEqual(fp.geturl(), url)
finally:
self.unfakehttp()
def test_willclose(self):
self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello!")
try:
resp = urlopen("http://www.python.org")
self.assertTrue(resp.fp.will_close)
finally:
self.unfakehttp()
@unittest.skipUnless(ssl, "ssl module required")
def test_url_path_with_control_char_rejected(self):
for char_no in list(range(0, 0x21)) + [0x7f]:
char = chr(char_no)
schemeless_url = f"//localhost:7777/test{char}/"
self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
try:
# We explicitly test urllib.request.urlopen() instead of the top
# level 'def urlopen()' function defined in this... (quite ugly)
# test suite. They use different url opening codepaths. Plain
# urlopen uses FancyURLOpener which goes via a codepath that
# calls urllib.parse.quote() on the URL which makes all of the
# above attempts at injection within the url _path_ safe.
escaped_char_repr = repr(char).replace('\\', r'\\')
InvalidURL = http.client.InvalidURL
with self.assertRaisesRegex(
InvalidURL, f"contain control.*{escaped_char_repr}"):
urllib.request.urlopen(f"http:{schemeless_url}")
with self.assertRaisesRegex(
InvalidURL, f"contain control.*{escaped_char_repr}"):
urllib.request.urlopen(f"https:{schemeless_url}")
# This code path quotes the URL so there is no injection.
resp = urlopen(f"http:{schemeless_url}")
self.assertNotIn(char, resp.geturl())
finally:
self.unfakehttp()
@unittest.skipUnless(ssl, "ssl module required")
def test_url_path_with_newline_header_injection_rejected(self):
self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: header\r\nTEST: 123"
schemeless_url = "//" + host + ":8080/test/?test=a"
try:
# We explicitly test urllib.request.urlopen() instead of the top
# level 'def urlopen()' function defined in this... (quite ugly)
# test suite. They use different url opening codepaths. Plain
# urlopen uses FancyURLOpener which goes via a codepath that
# calls urllib.parse.quote() on the URL which makes all of the
# above attempts at injection within the url _path_ safe.
InvalidURL = http.client.InvalidURL
with self.assertRaisesRegex(
InvalidURL, r"contain control.*\\r.*(found at least . .)"):
urllib.request.urlopen(f"http:{schemeless_url}")
with self.assertRaisesRegex(InvalidURL, r"contain control.*\\n"):
urllib.request.urlopen(f"https:{schemeless_url}")
# This code path quotes the URL so there is no injection.
resp = urlopen(f"http:{schemeless_url}")
self.assertNotIn(' ', resp.geturl())
self.assertNotIn('\r', resp.geturl())
self.assertNotIn('\n', resp.geturl())
finally:
self.unfakehttp()
@unittest.skipUnless(ssl, "ssl module required")
def test_url_host_with_control_char_rejected(self):
for char_no in list(range(0, 0x21)) + [0x7f]:
char = chr(char_no)
schemeless_url = f"//localhost{char}/test/"
self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
try:
escaped_char_repr = repr(char).replace('\\', r'\\')
InvalidURL = http.client.InvalidURL
with self.assertRaisesRegex(
InvalidURL, f"contain control.*{escaped_char_repr}"):
urlopen(f"http:{schemeless_url}")
with self.assertRaisesRegex(InvalidURL, f"contain control.*{escaped_char_repr}"):
urlopen(f"https:{schemeless_url}")
finally:
self.unfakehttp()
@unittest.skipUnless(ssl, "ssl module required")
def test_url_host_with_newline_header_injection_rejected(self):
self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
host = "localhost\r\nX-injected: header\r\n"
schemeless_url = "//" + host + ":8080/test/?test=a"
try:
InvalidURL = http.client.InvalidURL
with self.assertRaisesRegex(
InvalidURL, r"contain control.*\\r"):
urlopen(f"http:{schemeless_url}")
with self.assertRaisesRegex(InvalidURL, r"contain control.*\\n"):
urlopen(f"https:{schemeless_url}")
finally:
self.unfakehttp()
def test_read_0_9(self):
# "0.9" response accepted (but not "simple responses" without
# a status line)
self.check_read(b"0.9")
def test_read_1_0(self):
self.check_read(b"1.0")
def test_read_1_1(self):
self.check_read(b"1.1")
def test_read_bogus(self):
# urlopen() should raise OSError for many error codes.
self.fakehttp(b'''HTTP/1.1 401 Authentication Required
Date: Wed, 02 Jan 2008 03:03:54 GMT
Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
Connection: close
Content-Type: text/html; charset=iso-8859-1
''')
try:
self.assertRaises(OSError, urlopen, "http://python.org/")
finally:
self.unfakehttp()
def test_invalid_redirect(self):
# urlopen() should raise OSError for many error codes.
self.fakehttp(b'''HTTP/1.1 302 Found
Date: Wed, 02 Jan 2008 03:03:54 GMT
Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
Location: file://guidocomputer.athome.com:/python/license
Connection: close
Content-Type: text/html; charset=iso-8859-1
''')
try:
msg = "Redirection to url 'file:"
with self.assertRaisesRegex(urllib.error.HTTPError, msg):
urlopen("http://python.org/")
finally:
self.unfakehttp()
def test_redirect_limit_independent(self):
# Ticket #12923: make sure independent requests each use their
# own retry limit.
for i in range(FancyURLopener().maxtries):
self.fakehttp(b'''HTTP/1.1 302 Found
Location: file://guidocomputer.athome.com:/python/license
Connection: close
''')
try:
self.assertRaises(urllib.error.HTTPError, urlopen,
"http://something")
finally:
self.unfakehttp()
def test_empty_socket(self):
# urlopen() raises OSError if the underlying socket does not send any
# data. (#1680230)
self.fakehttp(b'')
try:
self.assertRaises(OSError, urlopen, "http://something")
finally:
self.unfakehttp()
def test_missing_localfile(self):
# Test for #10836
with self.assertRaises(urllib.error.URLError) as e:
urlopen('file://localhost/a/file/which/doesnot/exists.py')
self.assertTrue(e.exception.filename)
self.assertTrue(e.exception.reason)
def test_file_notexists(self):
fd, tmp_file = tempfile.mkstemp()
tmp_fileurl = 'file://localhost/' + tmp_file.replace(os.path.sep, '/')
try:
self.assertTrue(os.path.exists(tmp_file))
with urlopen(tmp_fileurl) as fobj:
self.assertTrue(fobj)
finally:
os.close(fd)
os.unlink(tmp_file)
self.assertFalse(os.path.exists(tmp_file))
with self.assertRaises(urllib.error.URLError):
urlopen(tmp_fileurl)
def test_ftp_nohost(self):
test_ftp_url = 'ftp:///path'
with self.assertRaises(urllib.error.URLError) as e:
urlopen(test_ftp_url)
self.assertFalse(e.exception.filename)
self.assertTrue(e.exception.reason)
def test_ftp_nonexisting(self):
with self.assertRaises(urllib.error.URLError) as e:
urlopen('ftp://localhost/a/file/which/doesnot/exists.py')
self.assertFalse(e.exception.filename)
self.assertTrue(e.exception.reason)
@patch.object(urllib.request, 'MAXFTPCACHE', 0)
def test_ftp_cache_pruning(self):
self.fakeftp()
try:
urllib.request.ftpcache['test'] = urllib.request.ftpwrapper('user', 'pass', 'localhost', 21, [])
urlopen('ftp://localhost')
finally:
self.unfakeftp()
def test_userpass_inurl(self):
self.fakehttp(b"HTTP/1.0 200 OK\r\n\r\nHello!")
try:
fp = urlopen("http://user:[email protected]/")
self.assertEqual(fp.readline(), b"Hello!")
self.assertEqual(fp.readline(), b"")
self.assertEqual(fp.geturl(), 'http://user:[email protected]/')
self.assertEqual(fp.getcode(), 200)
finally:
self.unfakehttp()
def test_userpass_inurl_w_spaces(self):
self.fakehttp(b"HTTP/1.0 200 OK\r\n\r\nHello!")
try:
userpass = "a b:c d"
url = "http://{}@python.org/".format(userpass)
fakehttp_wrapper = http.client.HTTPConnection
authorization = ("Authorization: Basic %s\r\n" %
b64encode(userpass.encode("ASCII")).decode("ASCII"))
fp = urlopen(url)
# The authorization header must be in place
self.assertIn(authorization, fakehttp_wrapper.buf.decode("UTF-8"))
self.assertEqual(fp.readline(), b"Hello!")
self.assertEqual(fp.readline(), b"")
# the spaces are quoted in URL so no match
self.assertNotEqual(fp.geturl(), url)
self.assertEqual(fp.getcode(), 200)
finally:
self.unfakehttp()
def test_URLopener_deprecation(self):
with support.check_warnings(('',DeprecationWarning)):
urllib.request.URLopener()
@unittest.skipUnless(ssl, "ssl module required")
def test_cafile_and_context(self):
context = ssl.create_default_context()
with support.check_warnings(('', DeprecationWarning)):
with self.assertRaises(ValueError):
urllib.request.urlopen(
"https://localhost", cafile="/nonexistent/path", context=context
)
class urlopen_DataTests(unittest.TestCase):
"""Test urlopen() opening a data URL."""
def setUp(self):
# text containing URL special- and unicode-characters
self.text = "test data URLs :;,%=& \u00f6 \u00c4 "
# 2x1 pixel RGB PNG image with one black and one white pixel
self.image = (
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x02\x00\x00\x00'
b'\x01\x08\x02\x00\x00\x00{@\xe8\xdd\x00\x00\x00\x01sRGB\x00\xae'
b'\xce\x1c\xe9\x00\x00\x00\x0fIDAT\x08\xd7c```\xf8\xff\xff?\x00'
b'\x06\x01\x02\xfe\no/\x1e\x00\x00\x00\x00IEND\xaeB`\x82')
self.text_url = (
"data:text/plain;charset=UTF-8,test%20data%20URLs%20%3A%3B%2C%25%3"
"D%26%20%C3%B6%20%C3%84%20")
self.text_url_base64 = (
"data:text/plain;charset=ISO-8859-1;base64,dGVzdCBkYXRhIFVSTHMgOjs"
"sJT0mIPYgxCA%3D")
# base64 encoded data URL that contains ignorable spaces,
# such as "\n", " ", "%0A", and "%20".
self.image_url = (
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7\n"
"QOjdAAAAAXNSR0IArs4c6QAAAA9JREFUCNdj%0AYGBg%2BP//PwAGAQL%2BCm8 "
"vHgAAAABJRU5ErkJggg%3D%3D%0A%20")
self.text_url_resp = urllib.request.urlopen(self.text_url)
self.text_url_base64_resp = urllib.request.urlopen(
self.text_url_base64)
self.image_url_resp = urllib.request.urlopen(self.image_url)
def test_interface(self):
# Make sure object returned by urlopen() has the specified methods
for attr in ("read", "readline", "readlines",
"close", "info", "geturl", "getcode", "__iter__"):
self.assertTrue(hasattr(self.text_url_resp, attr),
"object returned by urlopen() lacks %s attribute" %
attr)
def test_info(self):
self.assertIsInstance(self.text_url_resp.info(), email.message.Message)
self.assertEqual(self.text_url_base64_resp.info().get_params(),
[('text/plain', ''), ('charset', 'ISO-8859-1')])
self.assertEqual(self.image_url_resp.info()['content-length'],
str(len(self.image)))
self.assertEqual(urllib.request.urlopen("data:,").info().get_params(),
[('text/plain', ''), ('charset', 'US-ASCII')])
def test_geturl(self):
self.assertEqual(self.text_url_resp.geturl(), self.text_url)
self.assertEqual(self.text_url_base64_resp.geturl(),
self.text_url_base64)
self.assertEqual(self.image_url_resp.geturl(), self.image_url)
def test_read_text(self):
self.assertEqual(self.text_url_resp.read().decode(
dict(self.text_url_resp.info().get_params())['charset']), self.text)
def test_read_text_base64(self):
self.assertEqual(self.text_url_base64_resp.read().decode(
dict(self.text_url_base64_resp.info().get_params())['charset']),
self.text)
def test_read_image(self):
self.assertEqual(self.image_url_resp.read(), self.image)
def test_missing_comma(self):
self.assertRaises(ValueError,urllib.request.urlopen,'data:text/plain')
def test_invalid_base64_data(self):
# missing padding character
self.assertRaises(ValueError,urllib.request.urlopen,'data:;base64,Cg=')
class urlretrieve_FileTests(unittest.TestCase):
"""Test urllib.urlretrieve() on local files"""
def setUp(self):
# Create a list of temporary files. Each item in the list is a file
# name (absolute path or relative to the current working directory).
# All files in this list will be deleted in the tearDown method. Note,
# this only helps to makes sure temporary files get deleted, but it
# does nothing about trying to close files that may still be open. It
# is the responsibility of the developer to properly close files even
# when exceptional conditions occur.
self.tempFiles = []
# Create a temporary file.
self.registerFileForCleanUp(support.TESTFN)
self.text = b'testing urllib.urlretrieve'
try:
FILE = open(support.TESTFN, 'wb')
FILE.write(self.text)
FILE.close()
finally:
try: FILE.close()
except: pass
def tearDown(self):
# Delete the temporary files.
for each in self.tempFiles:
try: os.remove(each)
except: pass
def constructLocalFileUrl(self, filePath):
filePath = os.path.abspath(filePath)
try:
filePath.encode("utf-8")
except UnicodeEncodeError:
raise unittest.SkipTest("filePath is not encodable to utf8")
return "file://%s" % urllib.request.pathname2url(filePath)
def createNewTempFile(self, data=b""):
"""Creates a new temporary file containing the specified data,
registers the file for deletion during the test fixture tear down, and
returns the absolute path of the file."""
newFd, newFilePath = tempfile.mkstemp()
try:
self.registerFileForCleanUp(newFilePath)
newFile = os.fdopen(newFd, "wb")
newFile.write(data)
newFile.close()
finally:
try: newFile.close()
except: pass
return newFilePath
def registerFileForCleanUp(self, fileName):
self.tempFiles.append(fileName)
def test_basic(self):
# Make sure that a local file just gets its own location returned and
# a headers value is returned.
result = urllib.request.urlretrieve("file:%s" % support.TESTFN)
self.assertEqual(result[0], support.TESTFN)
self.assertIsInstance(result[1], email.message.Message,
"did not get an email.message.Message instance "
"as second returned value")
def test_copy(self):
# Test that setting the filename argument works.
second_temp = "%s.2" % support.TESTFN
self.registerFileForCleanUp(second_temp)
result = urllib.request.urlretrieve(self.constructLocalFileUrl(
support.TESTFN), second_temp)
self.assertEqual(second_temp, result[0])
self.assertTrue(os.path.exists(second_temp), "copy of the file was not "
"made")
FILE = open(second_temp, 'rb')
try:
text = FILE.read()
FILE.close()
finally:
try: FILE.close()
except: pass
self.assertEqual(self.text, text)
def test_reporthook(self):
# Make sure that the reporthook works.
def hooktester(block_count, block_read_size, file_size, count_holder=[0]):
self.assertIsInstance(block_count, int)
self.assertIsInstance(block_read_size, int)
self.assertIsInstance(file_size, int)
self.assertEqual(block_count, count_holder[0])
count_holder[0] = count_holder[0] + 1
second_temp = "%s.2" % support.TESTFN
self.registerFileForCleanUp(second_temp)
urllib.request.urlretrieve(
self.constructLocalFileUrl(support.TESTFN),
second_temp, hooktester)
def test_reporthook_0_bytes(self):
# Test on zero length file. Should call reporthook only 1 time.
report = []
def hooktester(block_count, block_read_size, file_size, _report=report):
_report.append((block_count, block_read_size, file_size))
srcFileName = self.createNewTempFile()
urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
support.TESTFN, hooktester)
self.assertEqual(len(report), 1)
self.assertEqual(report[0][2], 0)
def test_reporthook_5_bytes(self):
# Test on 5 byte file. Should call reporthook only 2 times (once when
# the "network connection" is established and once when the block is
# read).
report = []
def hooktester(block_count, block_read_size, file_size, _report=report):
_report.append((block_count, block_read_size, file_size))
srcFileName = self.createNewTempFile(b"x" * 5)
urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
support.TESTFN, hooktester)
self.assertEqual(len(report), 2)
self.assertEqual(report[0][2], 5)
self.assertEqual(report[1][2], 5)
def test_reporthook_8193_bytes(self):
# Test on 8193 byte file. Should call reporthook only 3 times (once
# when the "network connection" is established, once for the next 8192
# bytes, and once for the last byte).
report = []
def hooktester(block_count, block_read_size, file_size, _report=report):
_report.append((block_count, block_read_size, file_size))
srcFileName = self.createNewTempFile(b"x" * 8193)
urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
support.TESTFN, hooktester)
self.assertEqual(len(report), 3)
self.assertEqual(report[0][2], 8193)
self.assertEqual(report[0][1], 8192)
self.assertEqual(report[1][1], 8192)
self.assertEqual(report[2][1], 8192)
class urlretrieve_HttpTests(unittest.TestCase, FakeHTTPMixin):
"""Test urllib.urlretrieve() using fake http connections"""
def test_short_content_raises_ContentTooShortError(self):
self.fakehttp(b'''HTTP/1.1 200 OK
Date: Wed, 02 Jan 2008 03:03:54 GMT
Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
Connection: close
Content-Length: 100
Content-Type: text/html; charset=iso-8859-1
FF
''')
def _reporthook(par1, par2, par3):
pass
with self.assertRaises(urllib.error.ContentTooShortError):
try:
urllib.request.urlretrieve('http://example.com/',
reporthook=_reporthook)
finally:
self.unfakehttp()
def test_short_content_raises_ContentTooShortError_without_reporthook(self):
self.fakehttp(b'''HTTP/1.1 200 OK
Date: Wed, 02 Jan 2008 03:03:54 GMT
Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
Connection: close
Content-Length: 100
Content-Type: text/html; charset=iso-8859-1
FF
''')
with self.assertRaises(urllib.error.ContentTooShortError):
try:
urllib.request.urlretrieve('http://example.com/')
finally:
self.unfakehttp()
class QuotingTests(unittest.TestCase):
r"""Tests for urllib.quote() and urllib.quote_plus()
According to RFC 2396 (Uniform Resource Identifiers), to escape a
character you write it as '%' + <2 character US-ASCII hex value>.
The Python code of ``'%' + hex(ord(<character>))[2:]`` escapes a
character properly. Case does not matter on the hex letters.
The various character sets specified are:
Reserved characters : ";/?:@&=+$,"
Have special meaning in URIs and must be escaped if not being used for
their special meaning
Data characters : letters, digits, and "-_.!~*'()"
Unreserved and do not need to be escaped; can be, though, if desired
Control characters : 0x00 - 0x1F, 0x7F
Have no use in URIs so must be escaped
space : 0x20
Must be escaped
Delimiters : '<>#%"'
Must be escaped
Unwise : "{}|\^[]`"
Must be escaped
"""
def test_never_quote(self):
# Make sure quote() does not quote letters, digits, and "_,.-"
do_not_quote = '' .join(["ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz",
"0123456789",
"_.-"])
result = urllib.parse.quote(do_not_quote)
self.assertEqual(do_not_quote, result,
"using quote(): %r != %r" % (do_not_quote, result))
result = urllib.parse.quote_plus(do_not_quote)
self.assertEqual(do_not_quote, result,
"using quote_plus(): %r != %r" % (do_not_quote, result))
def test_default_safe(self):
# Test '/' is default value for 'safe' parameter
self.assertEqual(urllib.parse.quote.__defaults__[0], '/')
def test_safe(self):
# Test setting 'safe' parameter does what it should do
quote_by_default = "<>"
result = urllib.parse.quote(quote_by_default, safe=quote_by_default)
self.assertEqual(quote_by_default, result,
"using quote(): %r != %r" % (quote_by_default, result))
result = urllib.parse.quote_plus(quote_by_default,
safe=quote_by_default)
self.assertEqual(quote_by_default, result,
"using quote_plus(): %r != %r" %
(quote_by_default, result))
# Safe expressed as bytes rather than str
result = urllib.parse.quote(quote_by_default, safe=b"<>")
self.assertEqual(quote_by_default, result,
"using quote(): %r != %r" % (quote_by_default, result))
# "Safe" non-ASCII characters should have no effect
# (Since URIs are not allowed to have non-ASCII characters)
result = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="\xfc")
expect = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="")
self.assertEqual(expect, result,
"using quote(): %r != %r" %
(expect, result))
# Same as above, but using a bytes rather than str
result = urllib.parse.quote("a\xfcb", encoding="latin-1", safe=b"\xfc")
expect = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="")
self.assertEqual(expect, result,
"using quote(): %r != %r" %
(expect, result))
def test_default_quoting(self):
# Make sure all characters that should be quoted are by default sans
# space (separate test for that).
should_quote = [chr(num) for num in range(32)] # For 0x00 - 0x1F
should_quote.append(r'<>#%"{}|\^[]`')
should_quote.append(chr(127)) # For 0x7F
should_quote = ''.join(should_quote)
for char in should_quote:
result = urllib.parse.quote(char)
self.assertEqual(hexescape(char), result,
"using quote(): "
"%s should be escaped to %s, not %s" %
(char, hexescape(char), result))
result = urllib.parse.quote_plus(char)
self.assertEqual(hexescape(char), result,
"using quote_plus(): "
"%s should be escapes to %s, not %s" %
(char, hexescape(char), result))
del should_quote
partial_quote = "ab[]cd"
expected = "ab%5B%5Dcd"
result = urllib.parse.quote(partial_quote)
self.assertEqual(expected, result,
"using quote(): %r != %r" % (expected, result))
result = urllib.parse.quote_plus(partial_quote)
self.assertEqual(expected, result,
"using quote_plus(): %r != %r" % (expected, result))
def test_quoting_space(self):
# Make sure quote() and quote_plus() handle spaces as specified in
# their unique way
result = urllib.parse.quote(' ')
self.assertEqual(result, hexescape(' '),
"using quote(): %r != %r" % (result, hexescape(' ')))
result = urllib.parse.quote_plus(' ')
self.assertEqual(result, '+',
"using quote_plus(): %r != +" % result)
given = "a b cd e f"
expect = given.replace(' ', hexescape(' '))
result = urllib.parse.quote(given)
self.assertEqual(expect, result,
"using quote(): %r != %r" % (expect, result))
expect = given.replace(' ', '+')
result = urllib.parse.quote_plus(given)
self.assertEqual(expect, result,
"using quote_plus(): %r != %r" % (expect, result))
def test_quoting_plus(self):
self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma'),
'alpha%2Bbeta+gamma')
self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', '+'),
'alpha+beta+gamma')
# Test with bytes
self.assertEqual(urllib.parse.quote_plus(b'alpha+beta gamma'),
'alpha%2Bbeta+gamma')
# Test with safe bytes
self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', b'+'),
'alpha+beta+gamma')
def test_quote_bytes(self):
# Bytes should quote directly to percent-encoded values
given = b"\xa2\xd8ab\xff"
expect = "%A2%D8ab%FF"
result = urllib.parse.quote(given)
self.assertEqual(expect, result,
"using quote(): %r != %r" % (expect, result))
# Encoding argument should raise type error on bytes input
self.assertRaises(TypeError, urllib.parse.quote, given,
encoding="latin-1")
# quote_from_bytes should work the same
result = urllib.parse.quote_from_bytes(given)
self.assertEqual(expect, result,
"using quote_from_bytes(): %r != %r"
% (expect, result))
def test_quote_with_unicode(self):
# Characters in Latin-1 range, encoded by default in UTF-8
given = "\xa2\xd8ab\xff"
expect = "%C2%A2%C3%98ab%C3%BF"
result = urllib.parse.quote(given)
self.assertEqual(expect, result,
"using quote(): %r != %r" % (expect, result))
# Characters in Latin-1 range, encoded by with None (default)
result = urllib.parse.quote(given, encoding=None, errors=None)
self.assertEqual(expect, result,
"using quote(): %r != %r" % (expect, result))
# Characters in Latin-1 range, encoded with Latin-1
given = "\xa2\xd8ab\xff"
expect = "%A2%D8ab%FF"
result = urllib.parse.quote(given, encoding="latin-1")
self.assertEqual(expect, result,
"using quote(): %r != %r" % (expect, result))
# Characters in BMP, encoded by default in UTF-8
given = "\u6f22\u5b57" # "Kanji"
expect = "%E6%BC%A2%E5%AD%97"
result = urllib.parse.quote(given)
self.assertEqual(expect, result,
"using quote(): %r != %r" % (expect, result))
# Characters in BMP, encoded with Latin-1
given = "\u6f22\u5b57"
self.assertRaises(UnicodeEncodeError, urllib.parse.quote, given,
encoding="latin-1")
# Characters in BMP, encoded with Latin-1, with replace error handling
given = "\u6f22\u5b57"
expect = "%3F%3F" # "??"
result = urllib.parse.quote(given, encoding="latin-1",
errors="replace")
self.assertEqual(expect, result,
"using quote(): %r != %r" % (expect, result))
# Characters in BMP, Latin-1, with xmlcharref error handling
given = "\u6f22\u5b57"
expect = "%26%2328450%3B%26%2323383%3B" # "漢字"
result = urllib.parse.quote(given, encoding="latin-1",
errors="xmlcharrefreplace")
self.assertEqual(expect, result,
"using quote(): %r != %r" % (expect, result))
def test_quote_plus_with_unicode(self):
# Encoding (latin-1) test for quote_plus
given = "\xa2\xd8 \xff"
expect = "%A2%D8+%FF"
result = urllib.parse.quote_plus(given, encoding="latin-1")
self.assertEqual(expect, result,
"using quote_plus(): %r != %r" % (expect, result))
# Errors test for quote_plus
given = "ab\u6f22\u5b57 cd"
expect = "ab%3F%3F+cd"
result = urllib.parse.quote_plus(given, encoding="latin-1",
errors="replace")
self.assertEqual(expect, result,
"using quote_plus(): %r != %r" % (expect, result))
class UnquotingTests(unittest.TestCase):
"""Tests for unquote() and unquote_plus()
See the doc string for quoting_Tests for details on quoting and such.
"""
def test_unquoting(self):
# Make sure unquoting of all ASCII values works
escape_list = []
for num in range(128):
given = hexescape(chr(num))
expect = chr(num)
result = urllib.parse.unquote(given)
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
result = urllib.parse.unquote_plus(given)
self.assertEqual(expect, result,
"using unquote_plus(): %r != %r" %
(expect, result))
escape_list.append(given)
escape_string = ''.join(escape_list)
del escape_list
result = urllib.parse.unquote(escape_string)
self.assertEqual(result.count('%'), 1,
"using unquote(): not all characters escaped: "
"%s" % result)
self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, None)
self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, ())
with support.check_warnings(('', BytesWarning), quiet=True):
self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, b'')
def test_unquoting_badpercent(self):
# Test unquoting on bad percent-escapes
given = '%xab'
expect = given
result = urllib.parse.unquote(given)
self.assertEqual(expect, result, "using unquote(): %r != %r"
% (expect, result))
given = '%x'
expect = given
result = urllib.parse.unquote(given)
self.assertEqual(expect, result, "using unquote(): %r != %r"
% (expect, result))
given = '%'
expect = given
result = urllib.parse.unquote(given)
self.assertEqual(expect, result, "using unquote(): %r != %r"
% (expect, result))
# unquote_to_bytes
given = '%xab'
expect = bytes(given, 'ascii')
result = urllib.parse.unquote_to_bytes(given)
self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
% (expect, result))
given = '%x'
expect = bytes(given, 'ascii')
result = urllib.parse.unquote_to_bytes(given)
self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
% (expect, result))
given = '%'
expect = bytes(given, 'ascii')
result = urllib.parse.unquote_to_bytes(given)
self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
% (expect, result))
self.assertRaises((TypeError, AttributeError), urllib.parse.unquote_to_bytes, None)
self.assertRaises((TypeError, AttributeError), urllib.parse.unquote_to_bytes, ())
def test_unquoting_mixed_case(self):
# Test unquoting on mixed-case hex digits in the percent-escapes
given = '%Ab%eA'
expect = b'\xab\xea'
result = urllib.parse.unquote_to_bytes(given)
self.assertEqual(expect, result,
"using unquote_to_bytes(): %r != %r"
% (expect, result))
def test_unquoting_parts(self):
# Make sure unquoting works when have non-quoted characters
# interspersed
given = 'ab%sd' % hexescape('c')
expect = "abcd"
result = urllib.parse.unquote(given)
self.assertEqual(expect, result,
"using quote(): %r != %r" % (expect, result))
result = urllib.parse.unquote_plus(given)
self.assertEqual(expect, result,
"using unquote_plus(): %r != %r" % (expect, result))
def test_unquoting_plus(self):
# Test difference between unquote() and unquote_plus()
given = "are+there+spaces..."
expect = given
result = urllib.parse.unquote(given)
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
expect = given.replace('+', ' ')
result = urllib.parse.unquote_plus(given)
self.assertEqual(expect, result,
"using unquote_plus(): %r != %r" % (expect, result))
def test_unquote_to_bytes(self):
given = 'br%C3%BCckner_sapporo_20050930.doc'
expect = b'br\xc3\xbcckner_sapporo_20050930.doc'
result = urllib.parse.unquote_to_bytes(given)
self.assertEqual(expect, result,
"using unquote_to_bytes(): %r != %r"
% (expect, result))
# Test on a string with unescaped non-ASCII characters
# (Technically an invalid URI; expect those characters to be UTF-8
# encoded).
result = urllib.parse.unquote_to_bytes("\u6f22%C3%BC")
expect = b'\xe6\xbc\xa2\xc3\xbc' # UTF-8 for "\u6f22\u00fc"
self.assertEqual(expect, result,
"using unquote_to_bytes(): %r != %r"
% (expect, result))
# Test with a bytes as input
given = b'%A2%D8ab%FF'
expect = b'\xa2\xd8ab\xff'
result = urllib.parse.unquote_to_bytes(given)
self.assertEqual(expect, result,
"using unquote_to_bytes(): %r != %r"
% (expect, result))
# Test with a bytes as input, with unescaped non-ASCII bytes
# (Technically an invalid URI; expect those bytes to be preserved)
given = b'%A2\xd8ab%FF'
expect = b'\xa2\xd8ab\xff'
result = urllib.parse.unquote_to_bytes(given)
self.assertEqual(expect, result,
"using unquote_to_bytes(): %r != %r"
% (expect, result))
def test_unquote_with_unicode(self):
# Characters in the Latin-1 range, encoded with UTF-8
given = 'br%C3%BCckner_sapporo_20050930.doc'
expect = 'br\u00fcckner_sapporo_20050930.doc'
result = urllib.parse.unquote(given)
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# Characters in the Latin-1 range, encoded with None (default)
result = urllib.parse.unquote(given, encoding=None, errors=None)
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# Characters in the Latin-1 range, encoded with Latin-1
result = urllib.parse.unquote('br%FCckner_sapporo_20050930.doc',
encoding="latin-1")
expect = 'br\u00fcckner_sapporo_20050930.doc'
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# Characters in BMP, encoded with UTF-8
given = "%E6%BC%A2%E5%AD%97"
expect = "\u6f22\u5b57" # "Kanji"
result = urllib.parse.unquote(given)
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# Decode with UTF-8, invalid sequence
given = "%F3%B1"
expect = "\ufffd" # Replacement character
result = urllib.parse.unquote(given)
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# Decode with UTF-8, invalid sequence, replace errors
result = urllib.parse.unquote(given, errors="replace")
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# Decode with UTF-8, invalid sequence, ignoring errors
given = "%F3%B1"
expect = ""
result = urllib.parse.unquote(given, errors="ignore")
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# A mix of non-ASCII and percent-encoded characters, UTF-8
result = urllib.parse.unquote("\u6f22%C3%BC")
expect = '\u6f22\u00fc'
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# A mix of non-ASCII and percent-encoded characters, Latin-1
# (Note, the string contains non-Latin-1-representable characters)
result = urllib.parse.unquote("\u6f22%FC", encoding="latin-1")
expect = '\u6f22\u00fc'
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
class urlencode_Tests(unittest.TestCase):
"""Tests for urlencode()"""
def help_inputtype(self, given, test_type):
"""Helper method for testing different input types.
'given' must lead to only the pairs:
* 1st, 1
* 2nd, 2
* 3rd, 3
Test cannot assume anything about order. Docs make no guarantee and
have possible dictionary input.
"""
expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
result = urllib.parse.urlencode(given)
for expected in expect_somewhere:
self.assertIn(expected, result,
"testing %s: %s not found in %s" %
(test_type, expected, result))
self.assertEqual(result.count('&'), 2,
"testing %s: expected 2 '&'s; got %s" %
(test_type, result.count('&')))
amp_location = result.index('&')
on_amp_left = result[amp_location - 1]
on_amp_right = result[amp_location + 1]
self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(),
"testing %s: '&' not located in proper place in %s" %
(test_type, result))
self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps
"testing %s: "
"unexpected number of characters: %s != %s" %
(test_type, len(result), (5 * 3) + 2))
def test_using_mapping(self):
# Test passing in a mapping object as an argument.
self.help_inputtype({"1st":'1', "2nd":'2', "3rd":'3'},
"using dict as input type")
def test_using_sequence(self):
# Test passing in a sequence of two-item sequences as an argument.
self.help_inputtype([('1st', '1'), ('2nd', '2'), ('3rd', '3')],
"using sequence of two-item tuples as input")
def test_quoting(self):
# Make sure keys and values are quoted using quote_plus()
given = {"&":"="}
expect = "%s=%s" % (hexescape('&'), hexescape('='))
result = urllib.parse.urlencode(given)
self.assertEqual(expect, result)
given = {"key name":"A bunch of pluses"}
expect = "key+name=A+bunch+of+pluses"
result = urllib.parse.urlencode(given)
self.assertEqual(expect, result)
def test_doseq(self):
# Test that passing True for 'doseq' parameter works correctly
given = {'sequence':['1', '2', '3']}
expect = "sequence=%s" % urllib.parse.quote_plus(str(['1', '2', '3']))
result = urllib.parse.urlencode(given)
self.assertEqual(expect, result)
result = urllib.parse.urlencode(given, True)
for value in given["sequence"]:
expect = "sequence=%s" % value
self.assertIn(expect, result)
self.assertEqual(result.count('&'), 2,
"Expected 2 '&'s, got %s" % result.count('&'))
def test_empty_sequence(self):
self.assertEqual("", urllib.parse.urlencode({}))
self.assertEqual("", urllib.parse.urlencode([]))
def test_nonstring_values(self):
self.assertEqual("a=1", urllib.parse.urlencode({"a": 1}))
self.assertEqual("a=None", urllib.parse.urlencode({"a": None}))
def test_nonstring_seq_values(self):
self.assertEqual("a=1&a=2", urllib.parse.urlencode({"a": [1, 2]}, True))
self.assertEqual("a=None&a=a",
urllib.parse.urlencode({"a": [None, "a"]}, True))
data = collections.OrderedDict([("a", 1), ("b", 1)])
self.assertEqual("a=a&a=b",
urllib.parse.urlencode({"a": data}, True))
def test_urlencode_encoding(self):
# ASCII encoding. Expect %3F with errors="replace'
given = (('\u00a0', '\u00c1'),)
expect = '%3F=%3F'
result = urllib.parse.urlencode(given, encoding="ASCII", errors="replace")
self.assertEqual(expect, result)
# Default is UTF-8 encoding.
given = (('\u00a0', '\u00c1'),)
expect = '%C2%A0=%C3%81'
result = urllib.parse.urlencode(given)
self.assertEqual(expect, result)
# Latin-1 encoding.
given = (('\u00a0', '\u00c1'),)
expect = '%A0=%C1'
result = urllib.parse.urlencode(given, encoding="latin-1")
self.assertEqual(expect, result)
def test_urlencode_encoding_doseq(self):
# ASCII Encoding. Expect %3F with errors="replace'
given = (('\u00a0', '\u00c1'),)
expect = '%3F=%3F'
result = urllib.parse.urlencode(given, doseq=True,
encoding="ASCII", errors="replace")
self.assertEqual(expect, result)
# ASCII Encoding. On a sequence of values.
given = (("\u00a0", (1, "\u00c1")),)
expect = '%3F=1&%3F=%3F'
result = urllib.parse.urlencode(given, True,
encoding="ASCII", errors="replace")
self.assertEqual(expect, result)
# Utf-8
given = (("\u00a0", "\u00c1"),)
expect = '%C2%A0=%C3%81'
result = urllib.parse.urlencode(given, True)
self.assertEqual(expect, result)
given = (("\u00a0", (42, "\u00c1")),)
expect = '%C2%A0=42&%C2%A0=%C3%81'
result = urllib.parse.urlencode(given, True)
self.assertEqual(expect, result)
# latin-1
given = (("\u00a0", "\u00c1"),)
expect = '%A0=%C1'
result = urllib.parse.urlencode(given, True, encoding="latin-1")
self.assertEqual(expect, result)
given = (("\u00a0", (42, "\u00c1")),)
expect = '%A0=42&%A0=%C1'
result = urllib.parse.urlencode(given, True, encoding="latin-1")
self.assertEqual(expect, result)
def test_urlencode_bytes(self):
given = ((b'\xa0\x24', b'\xc1\x24'),)
expect = '%A0%24=%C1%24'
result = urllib.parse.urlencode(given)
self.assertEqual(expect, result)
result = urllib.parse.urlencode(given, True)
self.assertEqual(expect, result)
# Sequence of values
given = ((b'\xa0\x24', (42, b'\xc1\x24')),)
expect = '%A0%24=42&%A0%24=%C1%24'
result = urllib.parse.urlencode(given, True)
self.assertEqual(expect, result)
def test_urlencode_encoding_safe_parameter(self):
# Send '$' (\x24) as safe character
# Default utf-8 encoding
given = ((b'\xa0\x24', b'\xc1\x24'),)
result = urllib.parse.urlencode(given, safe=":$")
expect = '%A0$=%C1$'
self.assertEqual(expect, result)
given = ((b'\xa0\x24', b'\xc1\x24'),)
result = urllib.parse.urlencode(given, doseq=True, safe=":$")
expect = '%A0$=%C1$'
self.assertEqual(expect, result)
# Safe parameter in sequence
given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),)
expect = '%A0$=%C1$&%A0$=13&%A0$=42'
result = urllib.parse.urlencode(given, True, safe=":$")
self.assertEqual(expect, result)
# Test all above in latin-1 encoding
given = ((b'\xa0\x24', b'\xc1\x24'),)
result = urllib.parse.urlencode(given, safe=":$",
encoding="latin-1")
expect = '%A0$=%C1$'
self.assertEqual(expect, result)
given = ((b'\xa0\x24', b'\xc1\x24'),)
expect = '%A0$=%C1$'
result = urllib.parse.urlencode(given, doseq=True, safe=":$",
encoding="latin-1")
given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),)
expect = '%A0$=%C1$&%A0$=13&%A0$=42'
result = urllib.parse.urlencode(given, True, safe=":$",
encoding="latin-1")
self.assertEqual(expect, result)
class Pathname_Tests(unittest.TestCase):
"""Test pathname2url() and url2pathname()"""
def test_basic(self):
# Make sure simple tests pass
expected_path = os.path.join("parts", "of", "a", "path")
expected_url = "parts/of/a/path"
result = urllib.request.pathname2url(expected_path)
self.assertEqual(expected_url, result,
"pathname2url() failed; %s != %s" %
(result, expected_url))
result = urllib.request.url2pathname(expected_url)
self.assertEqual(expected_path, result,
"url2pathame() failed; %s != %s" %
(result, expected_path))
def test_quoting(self):
# Test automatic quoting and unquoting works for pathnam2url() and
# url2pathname() respectively
given = os.path.join("needs", "quot=ing", "here")
expect = "needs/%s/here" % urllib.parse.quote("quot=ing")
result = urllib.request.pathname2url(given)
self.assertEqual(expect, result,
"pathname2url() failed; %s != %s" %
(expect, result))
expect = given
result = urllib.request.url2pathname(result)
self.assertEqual(expect, result,
"url2pathname() failed; %s != %s" %
(expect, result))
given = os.path.join("make sure", "using_quote")
expect = "%s/using_quote" % urllib.parse.quote("make sure")
result = urllib.request.pathname2url(given)
self.assertEqual(expect, result,
"pathname2url() failed; %s != %s" %
(expect, result))
given = "make+sure/using_unquote"
expect = os.path.join("make+sure", "using_unquote")
result = urllib.request.url2pathname(given)
self.assertEqual(expect, result,
"url2pathname() failed; %s != %s" %
(expect, result))
@unittest.skipUnless(sys.platform == 'win32',
'test specific to the urllib.url2path function.')
def test_ntpath(self):
given = ('/C:/', '///C:/', '/C|//')
expect = 'C:\\'
for url in given:
result = urllib.request.url2pathname(url)
self.assertEqual(expect, result,
'urllib.request..url2pathname() failed; %s != %s' %
(expect, result))
given = '///C|/path'
expect = 'C:\\path'
result = urllib.request.url2pathname(given)
self.assertEqual(expect, result,
'urllib.request.url2pathname() failed; %s != %s' %
(expect, result))
class Utility_Tests(unittest.TestCase):
"""Testcase to test the various utility functions in the urllib."""
def test_thishost(self):
"""Test the urllib.request.thishost utility function returns a tuple"""
self.assertIsInstance(urllib.request.thishost(), tuple)
class URLopener_Tests(unittest.TestCase):
"""Testcase to test the open method of URLopener class."""
def test_quoted_open(self):
class DummyURLopener(urllib.request.URLopener):
def open_spam(self, url):
return url
with support.check_warnings(
('DummyURLopener style of invoking requests is deprecated.',
DeprecationWarning)):
self.assertEqual(DummyURLopener().open(
'spam://example/ /'),'//example/%20/')
# test the safe characters are not quoted by urlopen
self.assertEqual(DummyURLopener().open(
"spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"),
"//c:|windows%/:=&?~#+!$,;'@()*[]|/path/")
def test_local_file_open(self):
# bpo-35907, CVE-2019-9948: urllib must reject local_file:// scheme
class DummyURLopener(urllib.request.URLopener):
def open_local_file(self, url):
return url
with warnings.catch_warnings(record=True):
warnings.simplefilter("ignore", DeprecationWarning)
for url in ('local_file://example', 'local-file://example'):
self.assertRaises(OSError, urllib.request.urlopen, url)
self.assertRaises(OSError, urllib.request.URLopener().open, url)
self.assertRaises(OSError, urllib.request.URLopener().retrieve, url)
self.assertRaises(OSError, DummyURLopener().open, url)
self.assertRaises(OSError, DummyURLopener().retrieve, url)
# Just commented them out.
# Can't really tell why keep failing in windows and sparc.
# Everywhere else they work ok, but on those machines, sometimes
# fail in one of the tests, sometimes in other. I have a linux, and
# the tests go ok.
# If anybody has one of the problematic environments, please help!
# . Facundo
#
# def server(evt):
# import socket, time
# serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# serv.settimeout(3)
# serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# serv.bind(("", 9093))
# serv.listen()
# try:
# conn, addr = serv.accept()
# conn.send("1 Hola mundo\n")
# cantdata = 0
# while cantdata < 13:
# data = conn.recv(13-cantdata)
# cantdata += len(data)
# time.sleep(.3)
# conn.send("2 No more lines\n")
# conn.close()
# except socket.timeout:
# pass
# finally:
# serv.close()
# evt.set()
#
# class FTPWrapperTests(unittest.TestCase):
#
# def setUp(self):
# import ftplib, time, threading
# ftplib.FTP.port = 9093
# self.evt = threading.Event()
# threading.Thread(target=server, args=(self.evt,)).start()
# time.sleep(.1)
#
# def tearDown(self):
# self.evt.wait()
#
# def testBasic(self):
# # connects
# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
# ftp.close()
#
# def testTimeoutNone(self):
# # global default timeout is ignored
# import socket
# self.assertIsNone(socket.getdefaulttimeout())
# socket.setdefaulttimeout(30)
# try:
# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
# finally:
# socket.setdefaulttimeout(None)
# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
# ftp.close()
#
# def testTimeoutDefault(self):
# # global default timeout is used
# import socket
# self.assertIsNone(socket.getdefaulttimeout())
# socket.setdefaulttimeout(30)
# try:
# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
# finally:
# socket.setdefaulttimeout(None)
# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
# ftp.close()
#
# def testTimeoutValue(self):
# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [],
# timeout=30)
# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
# ftp.close()
class RequestTests(unittest.TestCase):
"""Unit tests for urllib.request.Request."""
def test_default_values(self):
Request = urllib.request.Request
request = Request("http://www.python.org")
self.assertEqual(request.get_method(), 'GET')
request = Request("http://www.python.org", {})
self.assertEqual(request.get_method(), 'POST')
def test_with_method_arg(self):
Request = urllib.request.Request
request = Request("http://www.python.org", method='HEAD')
self.assertEqual(request.method, 'HEAD')
self.assertEqual(request.get_method(), 'HEAD')
request = Request("http://www.python.org", {}, method='HEAD')
self.assertEqual(request.method, 'HEAD')
self.assertEqual(request.get_method(), 'HEAD')
request = Request("http://www.python.org", method='GET')
self.assertEqual(request.get_method(), 'GET')
request.method = 'HEAD'
self.assertEqual(request.get_method(), 'HEAD')
class URL2PathNameTests(unittest.TestCase):
def test_converting_drive_letter(self):
self.assertEqual(url2pathname("///C|"), 'C:')
self.assertEqual(url2pathname("///C:"), 'C:')
self.assertEqual(url2pathname("///C|/"), 'C:\\')
def test_converting_when_no_drive_letter(self):
# cannot end a raw string in \
self.assertEqual(url2pathname("///C/test/"), r'\\\C\test' '\\')
self.assertEqual(url2pathname("////C/test/"), r'\\C\test' '\\')
def test_simple_compare(self):
self.assertEqual(url2pathname("///C|/foo/bar/spam.foo"),
r'C:\foo\bar\spam.foo')
def test_non_ascii_drive_letter(self):
self.assertRaises(IOError, url2pathname, "///\u00e8|/")
def test_roundtrip_url2pathname(self):
list_of_paths = ['C:',
r'\\\C\test\\',
r'C:\foo\bar\spam.foo'
]
for path in list_of_paths:
self.assertEqual(url2pathname(pathname2url(path)), path)
class PathName2URLTests(unittest.TestCase):
def test_converting_drive_letter(self):
self.assertEqual(pathname2url("C:"), '///C:')
self.assertEqual(pathname2url("C:\\"), '///C:')
def test_converting_when_no_drive_letter(self):
self.assertEqual(pathname2url(r"\\\folder\test" "\\"),
'/////folder/test/')
self.assertEqual(pathname2url(r"\\folder\test" "\\"),
'////folder/test/')
self.assertEqual(pathname2url(r"\folder\test" "\\"),
'/folder/test/')
def test_simple_compare(self):
self.assertEqual(pathname2url(r'C:\foo\bar\spam.foo'),
"///C:/foo/bar/spam.foo" )
def test_long_drive_letter(self):
self.assertRaises(IOError, pathname2url, "XX:\\")
def test_roundtrip_pathname2url(self):
list_of_paths = ['///C:',
'/////folder/test/',
'///C:/foo/bar/spam.foo']
for path in list_of_paths:
self.assertEqual(pathname2url(url2pathname(path)), path)
if __name__ == '__main__':
unittest.main()
| 69,510 | 1,676 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_time.py | from test import support
import decimal
import enum
import locale
import math
import platform
import sys
import sysconfig
import time
import unittest
try:
import _thread
import threading
except ImportError:
threading = None
try:
import _testcapi
except ImportError:
_testcapi = None
# Max year is only limited by the size of C int.
SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
TIME_MINYEAR = -TIME_MAXYEAR - 1 + 1900
SEC_TO_US = 10 ** 6
US_TO_NS = 10 ** 3
MS_TO_NS = 10 ** 6
SEC_TO_NS = 10 ** 9
NS_TO_SEC = 10 ** 9
class _PyTime(enum.IntEnum):
# Round towards minus infinity (-inf)
ROUND_FLOOR = 0
# Round towards infinity (+inf)
ROUND_CEILING = 1
# Round to nearest with ties going to nearest even integer
ROUND_HALF_EVEN = 2
# Round away from zero
ROUND_UP = 3
# Rounding modes supported by PyTime
ROUNDING_MODES = (
# (PyTime rounding method, decimal rounding method)
(_PyTime.ROUND_FLOOR, decimal.ROUND_FLOOR),
(_PyTime.ROUND_CEILING, decimal.ROUND_CEILING),
(_PyTime.ROUND_HALF_EVEN, decimal.ROUND_HALF_EVEN),
(_PyTime.ROUND_UP, decimal.ROUND_UP),
)
class TimeTestCase(unittest.TestCase):
def setUp(self):
self.t = time.time()
def test_data_attributes(self):
time.altzone
time.daylight
time.timezone
time.tzname
def test_time(self):
time.time()
info = time.get_clock_info('time')
self.assertFalse(info.monotonic)
self.assertTrue(info.adjustable)
def test_clock(self):
time.clock()
info = time.get_clock_info('clock')
self.assertTrue(info.monotonic)
self.assertFalse(info.adjustable)
@unittest.skipUnless(hasattr(time, 'clock_gettime'),
'need time.clock_gettime()')
def test_clock_realtime(self):
time.clock_gettime(time.CLOCK_REALTIME)
@unittest.skipUnless(hasattr(time, 'clock_gettime'),
'need time.clock_gettime()')
@unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
'need time.CLOCK_MONOTONIC')
def test_clock_monotonic(self):
a = time.clock_gettime(time.CLOCK_MONOTONIC)
b = time.clock_gettime(time.CLOCK_MONOTONIC)
self.assertLessEqual(a, b)
@unittest.skipUnless(hasattr(time, 'clock_getres'),
'need time.clock_getres()')
def test_clock_getres(self):
res = time.clock_getres(time.CLOCK_REALTIME)
self.assertGreater(res, 0.0)
self.assertLessEqual(res, 1.0)
@unittest.skipUnless(hasattr(time, 'clock_settime'),
'need time.clock_settime()')
def test_clock_settime(self):
t = time.clock_gettime(time.CLOCK_REALTIME)
try:
time.clock_settime(time.CLOCK_REALTIME, t)
except PermissionError:
pass
if hasattr(time, 'CLOCK_MONOTONIC'):
self.assertRaises(OSError,
time.clock_settime, time.CLOCK_MONOTONIC, 0)
def test_conversions(self):
self.assertEqual(time.ctime(self.t),
time.asctime(time.localtime(self.t)))
self.assertEqual(int(time.mktime(time.localtime(self.t))),
int(self.t))
def test_sleep(self):
self.assertRaises(ValueError, time.sleep, -2)
self.assertRaises(ValueError, time.sleep, -1)
time.sleep(1.2)
def test_strftime(self):
tt = time.gmtime(self.t)
for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
'j', 'm', 'M', 'p', 'S',
'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
format = ' %' + directive
try:
time.strftime(format, tt)
except ValueError:
self.fail('conversion specifier: %r failed.' % format)
self.assertRaises(TypeError, time.strftime, b'%S', tt)
# embedded null character
self.assertRaises(ValueError, time.strftime, '%S\0', tt)
def _bounds_checking(self, func):
# Make sure that strftime() checks the bounds of the various parts
# of the time tuple (0 is valid for *all* values).
# The year field is tested by other test cases above
# Check month [1, 12] + zero support
func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
self.assertRaises(ValueError, func,
(1900, -1, 1, 0, 0, 0, 0, 1, -1))
self.assertRaises(ValueError, func,
(1900, 13, 1, 0, 0, 0, 0, 1, -1))
# Check day of month [1, 31] + zero support
func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
self.assertRaises(ValueError, func,
(1900, 1, -1, 0, 0, 0, 0, 1, -1))
self.assertRaises(ValueError, func,
(1900, 1, 32, 0, 0, 0, 0, 1, -1))
# Check hour [0, 23]
func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
self.assertRaises(ValueError, func,
(1900, 1, 1, -1, 0, 0, 0, 1, -1))
self.assertRaises(ValueError, func,
(1900, 1, 1, 24, 0, 0, 0, 1, -1))
# Check minute [0, 59]
func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
self.assertRaises(ValueError, func,
(1900, 1, 1, 0, -1, 0, 0, 1, -1))
self.assertRaises(ValueError, func,
(1900, 1, 1, 0, 60, 0, 0, 1, -1))
# Check second [0, 61]
self.assertRaises(ValueError, func,
(1900, 1, 1, 0, 0, -1, 0, 1, -1))
# C99 only requires allowing for one leap second, but Python's docs say
# allow two leap seconds (0..61)
func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
func((1900, 1, 1, 0, 0, 61, 0, 1, -1))
self.assertRaises(ValueError, func,
(1900, 1, 1, 0, 0, 62, 0, 1, -1))
# No check for upper-bound day of week;
# value forced into range by a ``% 7`` calculation.
# Start check at -2 since gettmarg() increments value before taking
# modulo.
self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
self.assertRaises(ValueError, func,
(1900, 1, 1, 0, 0, 0, -2, 1, -1))
# Check day of the year [1, 366] + zero support
func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
self.assertRaises(ValueError, func,
(1900, 1, 1, 0, 0, 0, 0, -1, -1))
self.assertRaises(ValueError, func,
(1900, 1, 1, 0, 0, 0, 0, 367, -1))
def test_strftime_bounding_check(self):
self._bounds_checking(lambda tup: time.strftime('', tup))
def test_strftime_format_check(self):
# Test that strftime does not crash on invalid format strings
# that may trigger a buffer overread. When not triggered,
# strftime may succeed or raise ValueError depending on
# the platform.
for x in [ '', 'A', '%A', '%AA' ]:
for y in range(0x0, 0x10):
for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]:
try:
time.strftime(x * y + z)
except ValueError:
pass
def test_default_values_for_zero(self):
# Make sure that using all zeros uses the proper default
# values. No test for daylight savings since strftime() does
# not change output based on its value and no test for year
# because systems vary in their support for year 0.
expected = "2000 01 01 00 00 00 1 001"
with support.check_warnings():
result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
self.assertEqual(expected, result)
def test_strptime(self):
# Should be able to go round-trip from strftime to strptime without
# raising an exception.
tt = time.gmtime(self.t)
for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
'j', 'm', 'M', 'p', 'S',
'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
format = '%' + directive
strf_output = time.strftime(format, tt)
try:
time.strptime(strf_output, format)
except ValueError:
self.fail("conversion specifier %r failed with '%s' input." %
(format, strf_output))
def test_strptime_bytes(self):
# Make sure only strings are accepted as arguments to strptime.
self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
def test_strptime_exception_context(self):
# check that this doesn't chain exceptions needlessly (see #17572)
with self.assertRaises(ValueError) as e:
time.strptime('', '%D')
self.assertIs(e.exception.__suppress_context__, True)
# additional check for IndexError branch (issue #19545)
with self.assertRaises(ValueError) as e:
time.strptime('19', '%Y %')
self.assertIs(e.exception.__suppress_context__, True)
def test_asctime(self):
time.asctime(time.gmtime(self.t))
# Max year is only limited by the size of C int.
for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
self.assertRaises(OverflowError, time.asctime,
(TIME_MAXYEAR + 1,) + (0,) * 8)
self.assertRaises(OverflowError, time.asctime,
(TIME_MINYEAR - 1,) + (0,) * 8)
self.assertRaises(TypeError, time.asctime, 0)
self.assertRaises(TypeError, time.asctime, ())
self.assertRaises(TypeError, time.asctime, (0,) * 10)
def test_asctime_bounding_check(self):
self._bounds_checking(time.asctime)
def test_ctime(self):
t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
for year in [-100, 100, 1000, 2000, 2050, 10000]:
try:
testval = time.mktime((year, 1, 10) + (0,)*6)
except (ValueError, OverflowError):
# If mktime fails, ctime will fail too. This may happen
# on some platforms.
pass
else:
self.assertEqual(time.ctime(testval)[20:], str(year))
@unittest.skipUnless(hasattr(time, "tzset"),
"time module has no attribute tzset")
def test_tzset(self):
from os import environ
# Epoch time of midnight Dec 25th 2002. Never DST in northern
# hemisphere.
xmas2002 = 1040774400.0
# These formats are correct for 2002, and possibly future years
# This format is the 'standard' as documented at:
# http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
# They are also documented in the tzset(3) man page on most Unix
# systems.
# eastern = 'EST+05EDT,M4.1.0,M10.5.0' # [jart] wut
# victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
# utc='UTC+0'
utc = 'UTC'
eastern = 'New_York'
victoria = 'Melbourne'
org_TZ = environ.get('TZ',None)
try:
# Make sure we can switch to UTC time and results are correct
# Note that unknown timezones default to UTC.
# Note that altzone is undefined in UTC, as there is no DST
environ['TZ'] = eastern
time.tzset()
environ['TZ'] = utc
time.tzset()
self.assertEqual(
time.gmtime(xmas2002), time.localtime(xmas2002)
)
self.assertEqual(time.daylight, 0)
self.assertEqual(time.timezone, 0)
self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
# Make sure we can switch to US/Eastern
environ['TZ'] = eastern
time.tzset()
self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
self.assertEqual(time.tzname, ('EST', 'EDT'))
self.assertEqual(len(time.tzname), 2)
self.assertEqual(time.daylight, 1)
self.assertEqual(time.timezone, 18000)
self.assertEqual(time.altzone, 14400)
self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
self.assertEqual(len(time.tzname), 2)
# Now go to the southern hemisphere.
environ['TZ'] = victoria
time.tzset()
self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
# Issue #11886: Australian Eastern Standard Time (UTC+10) is called
# "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
# (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
# on some operating systems (e.g. FreeBSD), which is wrong. See for
# example this bug:
# http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
self.assertEqual(len(time.tzname), 2)
self.assertEqual(time.daylight, 1)
self.assertEqual(time.timezone, -36000)
self.assertEqual(time.altzone, -39600)
self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
finally:
# Repair TZ environment variable in case any other tests
# rely on it.
if org_TZ is not None:
environ['TZ'] = org_TZ
elif 'TZ' in environ:
del environ['TZ']
time.tzset()
def test_insane_timestamps(self):
# It's possible that some platform maps time_t to double,
# and that this test will fail there. This test should
# exempt such platforms (provided they return reasonable
# results!).
for func in time.ctime, time.gmtime, time.localtime:
for unreasonable in -1e200, 1e200:
self.assertRaises(OverflowError, func, unreasonable)
def test_ctime_without_arg(self):
# Not sure how to check the values, since the clock could tick
# at any time. Make sure these are at least accepted and
# don't raise errors.
time.ctime()
time.ctime(None)
def test_gmtime_without_arg(self):
gt0 = time.gmtime()
gt1 = time.gmtime(None)
t0 = time.mktime(gt0)
t1 = time.mktime(gt1)
self.assertAlmostEqual(t1, t0, delta=0.2)
def test_localtime_without_arg(self):
lt0 = time.localtime()
lt1 = time.localtime(None)
t0 = time.mktime(lt0)
t1 = time.mktime(lt1)
self.assertAlmostEqual(t1, t0, delta=0.2)
def test_mktime(self):
# Issue #1726687
for t in (-2, -1, 0, 1):
if sys.platform.startswith('aix') and t == -1:
# Issue #11188, #19748: mktime() returns -1 on error. On Linux,
# the tm_wday field is used as a sentinel () to detect if -1 is
# really an error or a valid timestamp. On AIX, tm_wday is
# unchanged even on success and so cannot be used as a
# sentinel.
continue
try:
tt = time.localtime(t)
except (OverflowError, OSError):
pass
else:
self.assertEqual(time.mktime(tt), t)
# Issue #13309: passing extreme values to mktime() or localtime()
# borks the glibc's internal timezone data.
@unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
"disabled because of a bug in glibc. Issue #13309")
def test_mktime_error(self):
# It may not be possible to reliably make mktime return error
# on all platfom. This will make sure that no other exception
# than OverflowError is raised for an extreme value.
tt = time.gmtime(self.t)
tzname = time.strftime('%Z', tt)
self.assertNotEqual(tzname, 'LMT')
try:
time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
except OverflowError:
pass
self.assertEqual(time.strftime('%Z', tt), tzname)
@unittest.skipUnless(hasattr(time, 'monotonic'),
'need time.monotonic')
def test_monotonic(self):
# monotonic() should not go backward
times = [time.monotonic() for n in range(100)]
t1 = times[0]
for t2 in times[1:]:
self.assertGreaterEqual(t2, t1, "times=%s" % times)
t1 = t2
# monotonic() includes time elapsed during a sleep
t1 = time.monotonic()
time.sleep(0.5)
t2 = time.monotonic()
dt = t2 - t1
self.assertGreater(t2, t1)
# Issue #20101: On some Windows machines, dt may be slightly low
self.assertTrue(0.45 <= dt <= 1.0, dt)
# monotonic() is a monotonic but non adjustable clock
info = time.get_clock_info('monotonic')
self.assertTrue(info.monotonic)
self.assertFalse(info.adjustable)
def test_perf_counter(self):
time.perf_counter()
def test_process_time(self):
# process_time() should not include time spend during a sleep
start = time.process_time()
time.sleep(0.100)
stop = time.process_time()
# use 20 ms because process_time() has usually a resolution of 15 ms
# on Windows
self.assertLess(stop - start, 0.020)
info = time.get_clock_info('process_time')
self.assertTrue(info.monotonic)
self.assertFalse(info.adjustable)
@unittest.skipUnless(hasattr(time, 'monotonic'),
'need time.monotonic')
@unittest.skipUnless(hasattr(time, 'clock_settime'),
'need time.clock_settime')
def test_monotonic_settime(self):
t1 = time.monotonic()
realtime = time.clock_gettime(time.CLOCK_REALTIME)
# jump backward with an offset of 1 hour
try:
time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
except PermissionError as err:
self.skipTest(err)
t2 = time.monotonic()
time.clock_settime(time.CLOCK_REALTIME, realtime)
# monotonic must not be affected by system clock updates
self.assertGreaterEqual(t2, t1)
def test_localtime_failure(self):
# Issue #13847: check for localtime() failure
invalid_time_t = None
for time_t in (-1, 2**30, 2**33, 2**60):
try:
time.localtime(time_t)
except OverflowError:
self.skipTest("need 64-bit time_t")
except OSError:
invalid_time_t = time_t
break
if invalid_time_t is None:
self.skipTest("unable to find an invalid time_t value")
self.assertRaises(OSError, time.localtime, invalid_time_t)
self.assertRaises(OSError, time.ctime, invalid_time_t)
# Issue #26669: check for localtime() failure
self.assertRaises(ValueError, time.localtime, float("nan"))
self.assertRaises(ValueError, time.ctime, float("nan"))
def test_get_clock_info(self):
clocks = ['clock', 'perf_counter', 'process_time', 'time']
if hasattr(time, 'monotonic'):
clocks.append('monotonic')
for name in clocks:
info = time.get_clock_info(name)
#self.assertIsInstance(info, dict)
self.assertIsInstance(info.implementation, str)
self.assertNotEqual(info.implementation, '')
self.assertIsInstance(info.monotonic, bool)
self.assertIsInstance(info.resolution, float)
# 0.0 < resolution <= 1.0
self.assertGreater(info.resolution, 0.0)
self.assertLessEqual(info.resolution, 1.0)
self.assertIsInstance(info.adjustable, bool)
self.assertRaises(ValueError, time.get_clock_info, 'xxx')
class TestLocale(unittest.TestCase):
def setUp(self):
self.oldloc = locale.setlocale(locale.LC_ALL)
def tearDown(self):
locale.setlocale(locale.LC_ALL, self.oldloc)
def test_bug_3061(self):
try:
tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
except locale.Error:
self.skipTest('could not set locale.LC_ALL to fr_FR')
# This should not cause an exception
time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
class _TestAsctimeYear:
_format = '%d'
def yearstr(self, y):
return time.asctime((y,) + (0,) * 8).split()[-1]
def test_large_year(self):
# Check that it doesn't crash for year > 9999
self.assertEqual(self.yearstr(12345), '12345')
self.assertEqual(self.yearstr(123456789), '123456789')
class _TestStrftimeYear:
# Issue 13305: For years < 1000, the value is not always
# padded to 4 digits across platforms. The C standard
# assumes year >= 1900, so it does not specify the number
# of digits.
if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
_format = '%04d'
else:
_format = '%d'
def yearstr(self, y):
return time.strftime('%Y', (y,) + (0,) * 8)
def test_4dyear(self):
# Check that we can return the zero padded value.
if self._format == '%04d':
self.test_year('%04d')
else:
def year4d(y):
return time.strftime('%4Y', (y,) + (0,) * 8)
self.test_year('%04d', func=year4d)
def skip_if_not_supported(y):
msg = "strftime() is limited to [1; 9999] with Visual Studio"
# Check that it doesn't crash for year > 9999
try:
time.strftime('%Y', (y,) + (0,) * 8)
except ValueError:
cond = False
else:
cond = True
return unittest.skipUnless(cond, msg)
@skip_if_not_supported(10000)
def test_large_year(self):
return super().test_large_year()
@skip_if_not_supported(0)
def test_negative(self):
return super().test_negative()
del skip_if_not_supported
class _Test4dYear:
_format = '%d'
def test_year(self, fmt=None, func=None):
fmt = fmt or self._format
func = func or self.yearstr
self.assertEqual(func(1), fmt % 1)
self.assertEqual(func(68), fmt % 68)
self.assertEqual(func(69), fmt % 69)
self.assertEqual(func(99), fmt % 99)
self.assertEqual(func(999), fmt % 999)
self.assertEqual(func(9999), fmt % 9999)
def test_large_year(self):
self.assertEqual(self.yearstr(12345).lstrip('+'), '12345')
self.assertEqual(self.yearstr(123456789).lstrip('+'), '123456789')
self.assertEqual(self.yearstr(TIME_MAXYEAR).lstrip('+'), str(TIME_MAXYEAR))
self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
def test_negative(self):
self.assertEqual(self.yearstr(-1), self._format % -1)
self.assertEqual(self.yearstr(-1234), '-1234')
self.assertEqual(self.yearstr(-123456), '-123456')
self.assertEqual(self.yearstr(-123456789), str(-123456789))
self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
# Modules/timemodule.c checks for underflow
self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
with self.assertRaises(OverflowError):
self.yearstr(-TIME_MAXYEAR - 1)
class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
pass
class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
pass
class TestPytime(unittest.TestCase):
@unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
def test_localtime_timezone(self):
# Get the localtime and examine it for the offset and zone.
lt = time.localtime()
self.assertTrue(hasattr(lt, "tm_gmtoff"))
self.assertTrue(hasattr(lt, "tm_zone"))
# See if the offset and zone are similar to the module
# attributes.
if lt.tm_gmtoff is None:
self.assertTrue(not hasattr(time, "timezone"))
else:
self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
if lt.tm_zone is None:
self.assertTrue(not hasattr(time, "tzname"))
else:
self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
# Try and make UNIX times from the localtime and a 9-tuple
# created from the localtime. Test to see that the times are
# the same.
t = time.mktime(lt); t9 = time.mktime(lt[:9])
self.assertEqual(t, t9)
# Make localtimes from the UNIX times and compare them to
# the original localtime, thus making a round trip.
new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
self.assertEqual(new_lt, lt)
self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
self.assertEqual(new_lt.tm_zone, lt.tm_zone)
self.assertEqual(new_lt9, lt)
self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
@unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
def test_strptime_timezone(self):
t = time.strptime("UTC", "%Z")
self.assertEqual(t.tm_zone, 'UTC')
t = time.strptime("+0500", "%z")
self.assertEqual(t.tm_gmtoff, 5 * 3600)
@unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
def test_short_times(self):
import pickle
# Load a short time structure using pickle.
st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
lt = pickle.loads(st)
self.assertIs(lt.tm_gmtoff, None)
self.assertIs(lt.tm_zone, None)
@unittest.skipIf(_testcapi is None, 'need the _testcapi module')
class CPyTimeTestCase:
"""
Base class to test the C _PyTime_t API.
"""
OVERFLOW_SECONDS = None
def setUp(self):
from _testcapi import SIZEOF_TIME_T
bits = SIZEOF_TIME_T * 8 - 1
self.time_t_min = -2 ** bits
self.time_t_max = 2 ** bits - 1
def time_t_filter(self, seconds):
return (self.time_t_min <= seconds <= self.time_t_max)
def _rounding_values(self, use_float):
"Build timestamps used to test rounding."
units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS]
if use_float:
# picoseconds are only tested to pytime_converter accepting floats
units.append(1e-3)
values = (
# small values
1, 2, 5, 7, 123, 456, 1234,
# 10^k - 1
9,
99,
999,
9999,
99999,
999999,
# test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5
499, 500, 501,
1499, 1500, 1501,
2500,
3500,
4500,
)
ns_timestamps = [0]
for unit in units:
for value in values:
ns = value * unit
ns_timestamps.extend((-ns, ns))
for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33):
ns = (2 ** pow2) * SEC_TO_NS
ns_timestamps.extend((
-ns-1, -ns, -ns+1,
ns-1, ns, ns+1
))
for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX):
ns_timestamps.append(seconds * SEC_TO_NS)
if use_float:
# numbers with an exact representation in IEEE 754 (base 2)
for pow2 in (3, 7, 10, 15):
ns = 2.0 ** (-pow2)
ns_timestamps.extend((-ns, ns))
# seconds close to _PyTime_t type limit
ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS
ns_timestamps.extend((-ns, ns))
return ns_timestamps
def _check_rounding(self, pytime_converter, expected_func,
use_float, unit_to_sec, value_filter=None):
def convert_values(ns_timestamps):
if use_float:
unit_to_ns = SEC_TO_NS / float(unit_to_sec)
values = [ns / unit_to_ns for ns in ns_timestamps]
else:
unit_to_ns = SEC_TO_NS // unit_to_sec
values = [ns // unit_to_ns for ns in ns_timestamps]
if value_filter:
values = filter(value_filter, values)
# remove duplicates and sort
return sorted(set(values))
# test rounding
ns_timestamps = self._rounding_values(use_float)
valid_values = convert_values(ns_timestamps)
for time_rnd, decimal_rnd in ROUNDING_MODES :
with decimal.localcontext() as context:
context.rounding = decimal_rnd
for value in valid_values:
debug_info = {'value': value, 'rounding': decimal_rnd}
try:
result = pytime_converter(value, time_rnd)
expected = expected_func(value)
except Exception as exc:
self.fail("Error on timestamp conversion: %s" % debug_info)
self.assertEqual(result,
expected,
debug_info)
# test overflow
ns = self.OVERFLOW_SECONDS * SEC_TO_NS
ns_timestamps = (-ns, ns)
overflow_values = convert_values(ns_timestamps)
for time_rnd, _ in ROUNDING_MODES :
for value in overflow_values:
debug_info = {'value': value, 'rounding': time_rnd}
with self.assertRaises(OverflowError, msg=debug_info):
pytime_converter(value, time_rnd)
def check_int_rounding(self, pytime_converter, expected_func,
unit_to_sec=1, value_filter=None):
self._check_rounding(pytime_converter, expected_func,
False, unit_to_sec, value_filter)
def check_float_rounding(self, pytime_converter, expected_func,
unit_to_sec=1, value_filter=None):
self._check_rounding(pytime_converter, expected_func,
True, unit_to_sec, value_filter)
def decimal_round(self, x):
d = decimal.Decimal(x)
d = d.quantize(1)
return int(d)
class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
"""
Test the C _PyTime_t API.
"""
# _PyTime_t is a 64-bit signed integer
OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS)
def test_FromSeconds(self):
from _testcapi import PyTime_FromSeconds
# PyTime_FromSeconds() expects a C int, reject values out of range
def c_int_filter(secs):
return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX)
self.check_int_rounding(lambda secs, rnd: PyTime_FromSeconds(secs),
lambda secs: secs * SEC_TO_NS,
value_filter=c_int_filter)
# test nan
for time_rnd, _ in ROUNDING_MODES:
with self.assertRaises(TypeError):
PyTime_FromSeconds(float('nan'))
def test_FromSecondsObject(self):
from _testcapi import PyTime_FromSecondsObject
self.check_int_rounding(
PyTime_FromSecondsObject,
lambda secs: secs * SEC_TO_NS)
self.check_float_rounding(
PyTime_FromSecondsObject,
lambda ns: self.decimal_round(ns * SEC_TO_NS))
# test nan
for time_rnd, _ in ROUNDING_MODES:
with self.assertRaises(ValueError):
PyTime_FromSecondsObject(float('nan'), time_rnd)
def test_AsSecondsDouble(self):
from _testcapi import PyTime_AsSecondsDouble
def float_converter(ns):
if abs(ns) % SEC_TO_NS == 0:
return float(ns // SEC_TO_NS)
else:
return float(ns) / SEC_TO_NS
self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns),
float_converter,
NS_TO_SEC)
# test nan
for time_rnd, _ in ROUNDING_MODES:
with self.assertRaises(TypeError):
PyTime_AsSecondsDouble(float('nan'))
def create_decimal_converter(self, denominator):
denom = decimal.Decimal(denominator)
def converter(value):
d = decimal.Decimal(value) / denom
return self.decimal_round(d)
return converter
def test_AsTimeval(self):
from _testcapi import PyTime_AsTimeval
us_converter = self.create_decimal_converter(US_TO_NS)
def timeval_converter(ns):
us = us_converter(ns)
return divmod(us, SEC_TO_US)
if sys.platform == 'win32':
from _testcapi import LONG_MIN, LONG_MAX
# On Windows, timeval.tv_sec type is a C long
def seconds_filter(secs):
return LONG_MIN <= secs <= LONG_MAX
else:
seconds_filter = self.time_t_filter
self.check_int_rounding(PyTime_AsTimeval,
timeval_converter,
NS_TO_SEC,
value_filter=seconds_filter)
@unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
'need _testcapi.PyTime_AsTimespec')
def test_AsTimespec(self):
from _testcapi import PyTime_AsTimespec
def timespec_converter(ns):
return divmod(ns, SEC_TO_NS)
self.check_int_rounding(lambda ns, rnd: PyTime_AsTimespec(ns),
timespec_converter,
NS_TO_SEC,
value_filter=self.time_t_filter)
def test_AsMilliseconds(self):
from _testcapi import PyTime_AsMilliseconds
self.check_int_rounding(PyTime_AsMilliseconds,
self.create_decimal_converter(MS_TO_NS),
NS_TO_SEC)
def test_AsMicroseconds(self):
from _testcapi import PyTime_AsMicroseconds
self.check_int_rounding(PyTime_AsMicroseconds,
self.create_decimal_converter(US_TO_NS),
NS_TO_SEC)
class TestOldPyTime(CPyTimeTestCase, unittest.TestCase):
"""
Test the old C _PyTime_t API: _PyTime_ObjectToXXX() functions.
"""
# time_t is a 32-bit or 64-bit signed integer
OVERFLOW_SECONDS = 2 ** 64
def test_object_to_time_t(self):
from _testcapi import pytime_object_to_time_t
self.check_int_rounding(pytime_object_to_time_t,
lambda secs: secs,
value_filter=self.time_t_filter)
self.check_float_rounding(pytime_object_to_time_t,
self.decimal_round,
value_filter=self.time_t_filter)
def create_converter(self, sec_to_unit):
def converter(secs):
floatpart, intpart = math.modf(secs)
intpart = int(intpart)
floatpart *= sec_to_unit
floatpart = self.decimal_round(floatpart)
if floatpart < 0:
floatpart += sec_to_unit
intpart -= 1
elif floatpart >= sec_to_unit:
floatpart -= sec_to_unit
intpart += 1
return (intpart, floatpart)
return converter
def test_object_to_timeval(self):
from _testcapi import pytime_object_to_timeval
self.check_int_rounding(pytime_object_to_timeval,
lambda secs: (secs, 0),
value_filter=self.time_t_filter)
self.check_float_rounding(pytime_object_to_timeval,
self.create_converter(SEC_TO_US),
value_filter=self.time_t_filter)
# test nan
for time_rnd, _ in ROUNDING_MODES:
with self.assertRaises(ValueError):
pytime_object_to_timeval(float('nan'), time_rnd)
def test_object_to_timespec(self):
from _testcapi import pytime_object_to_timespec
self.check_int_rounding(pytime_object_to_timespec,
lambda secs: (secs, 0),
value_filter=self.time_t_filter)
self.check_float_rounding(pytime_object_to_timespec,
self.create_converter(SEC_TO_NS),
value_filter=self.time_t_filter)
# test nan
for time_rnd, _ in ROUNDING_MODES:
with self.assertRaises(ValueError):
pytime_object_to_timespec(float('nan'), time_rnd)
if __name__ == "__main__":
unittest.main()
| 37,703 | 1,005 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/zip_cp437_header.zip | PK Ãi=n*´ filename_with_o.txtsõwãå PK Ãi=n*´ filename_without.txtsõwãå PK Ãi=n*´ filename_with_o.txtPK Ãi=n*´ : filename_without.txtPK
s | 270 | 1 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_curses.py | #
# Test script for the curses module
#
# This script doesn't actually display anything very coherent. but it
# does call (nearly) every method and function.
#
# Functions not tested: {def,reset}_{shell,prog}_mode, getch(), getstr(),
# init_color()
# Only called, not tested: getmouse(), ungetmouse()
#
import os
import string
import sys
import tempfile
import unittest
from test.support import requires, import_module, verbose, SaveSignals
# Optionally test curses module. This currently requires that the
# 'curses' resource be given on the regrtest command line using the -u
# option. If not available, nothing after this line will be executed.
import inspect
requires('curses')
# If either of these don't exist, skip the tests.
curses = import_module('curses')
import_module('curses.ascii')
import_module('curses.textpad')
try:
import curses.panel
except ImportError:
pass
def requires_curses_func(name):
return unittest.skipUnless(hasattr(curses, name),
'requires curses.%s' % name)
term = os.environ.get('TERM')
# If newterm was supported we could use it instead of initscr and not exit
@unittest.skipIf(not term or term == 'unknown',
"$TERM=%r, calling initscr() may cause exit" % term)
@unittest.skipIf(sys.platform == "cygwin",
"cygwin's curses mostly just hangs")
class TestCurses(unittest.TestCase):
@classmethod
def setUpClass(cls):
if not sys.__stdout__.isatty():
# Temporary skip tests on non-tty
raise unittest.SkipTest('sys.__stdout__ is not a tty')
cls.tmp = tempfile.TemporaryFile()
fd = cls.tmp.fileno()
else:
cls.tmp = None
fd = sys.__stdout__.fileno()
# testing setupterm() inside initscr/endwin
# causes terminal breakage
curses.setupterm(fd=fd)
@classmethod
def tearDownClass(cls):
if cls.tmp:
cls.tmp.close()
del cls.tmp
def setUp(self):
self.save_signals = SaveSignals()
self.save_signals.save()
if verbose:
# just to make the test output a little more readable
print()
self.stdscr = curses.initscr()
curses.savetty()
def tearDown(self):
curses.resetty()
curses.endwin()
self.save_signals.restore()
def test_window_funcs(self):
"Test the methods of windows"
stdscr = self.stdscr
win = curses.newwin(10,10)
win = curses.newwin(5,5, 5,5)
win2 = curses.newwin(15,15, 5,5)
for meth in [stdscr.addch, stdscr.addstr]:
for args in [('a',), ('a', curses.A_BOLD),
(4,4, 'a'), (5,5, 'a', curses.A_BOLD)]:
with self.subTest(meth=meth.__qualname__, args=args):
meth(*args)
for meth in [stdscr.clear, stdscr.clrtobot,
stdscr.clrtoeol, stdscr.cursyncup, stdscr.delch,
stdscr.deleteln, stdscr.erase, stdscr.getbegyx,
stdscr.getbkgd, stdscr.getkey, stdscr.getmaxyx,
stdscr.getparyx, stdscr.getyx, stdscr.inch,
stdscr.insertln, stdscr.instr, stdscr.is_wintouched,
win.noutrefresh, stdscr.redrawwin, stdscr.refresh,
stdscr.standout, stdscr.standend, stdscr.syncdown,
stdscr.syncup, stdscr.touchwin, stdscr.untouchwin]:
with self.subTest(meth=meth.__qualname__):
meth()
stdscr.addnstr('1234', 3)
stdscr.addnstr('1234', 3, curses.A_BOLD)
stdscr.addnstr(4,4, '1234', 3)
stdscr.addnstr(5,5, '1234', 3, curses.A_BOLD)
stdscr.attron(curses.A_BOLD)
stdscr.attroff(curses.A_BOLD)
stdscr.attrset(curses.A_BOLD)
stdscr.bkgd(' ')
stdscr.bkgd(' ', curses.A_REVERSE)
stdscr.bkgdset(' ')
stdscr.bkgdset(' ', curses.A_REVERSE)
win.border(65, 66, 67, 68,
69, 70, 71, 72)
win.border('|', '!', '-', '_',
'+', '\\', '#', '/')
with self.assertRaises(TypeError,
msg="Expected win.border() to raise TypeError"):
win.border(65, 66, 67, 68,
69, [], 71, 72)
win.box(65, 67)
win.box('!', '_')
win.box(b':', b'~')
self.assertRaises(TypeError, win.box, 65, 66, 67)
self.assertRaises(TypeError, win.box, 65)
win.box()
stdscr.clearok(1)
win4 = stdscr.derwin(2,2)
win4 = stdscr.derwin(1,1, 5,5)
win4.mvderwin(9,9)
stdscr.echochar('a')
stdscr.echochar('a', curses.A_BOLD)
stdscr.hline('-', 5)
stdscr.hline('-', 5, curses.A_BOLD)
stdscr.hline(1,1,'-', 5)
stdscr.hline(1,1,'-', 5, curses.A_BOLD)
stdscr.idcok(1)
stdscr.idlok(1)
if hasattr(stdscr, 'immedok'):
stdscr.immedok(1)
stdscr.immedok(0)
stdscr.insch('c')
stdscr.insdelln(1)
stdscr.insnstr('abc', 3)
stdscr.insnstr('abc', 3, curses.A_BOLD)
stdscr.insnstr(5, 5, 'abc', 3)
stdscr.insnstr(5, 5, 'abc', 3, curses.A_BOLD)
stdscr.insstr('def')
stdscr.insstr('def', curses.A_BOLD)
stdscr.insstr(5, 5, 'def')
stdscr.insstr(5, 5, 'def', curses.A_BOLD)
stdscr.is_linetouched(0)
stdscr.keypad(1)
stdscr.leaveok(1)
stdscr.move(3,3)
win.mvwin(2,2)
stdscr.nodelay(1)
stdscr.notimeout(1)
win2.overlay(win)
win2.overwrite(win)
win2.overlay(win, 1, 2, 2, 1, 3, 3)
win2.overwrite(win, 1, 2, 2, 1, 3, 3)
stdscr.redrawln(1,2)
stdscr.scrollok(1)
stdscr.scroll()
stdscr.scroll(2)
stdscr.scroll(-3)
stdscr.move(12, 2)
stdscr.setscrreg(10,15)
win3 = stdscr.subwin(10,10)
win3 = stdscr.subwin(10,10, 5,5)
if hasattr(stdscr, 'syncok') and not sys.platform.startswith("sunos"):
stdscr.syncok(1)
stdscr.timeout(5)
stdscr.touchline(5,5)
stdscr.touchline(5,5,0)
stdscr.vline('a', 3)
stdscr.vline('a', 3, curses.A_STANDOUT)
if hasattr(stdscr, 'chgat'):
stdscr.chgat(5, 2, 3, curses.A_BLINK)
stdscr.chgat(3, curses.A_BOLD)
stdscr.chgat(5, 8, curses.A_UNDERLINE)
stdscr.chgat(curses.A_BLINK)
stdscr.refresh()
stdscr.vline(1,1, 'a', 3)
stdscr.vline(1,1, 'a', 3, curses.A_STANDOUT)
if hasattr(stdscr, 'resize'):
stdscr.resize(25, 80)
if hasattr(stdscr, 'enclose'):
stdscr.enclose(10, 10)
self.assertRaises(ValueError, stdscr.getstr, -400)
self.assertRaises(ValueError, stdscr.getstr, 2, 3, -400)
self.assertRaises(ValueError, stdscr.instr, -2)
self.assertRaises(ValueError, stdscr.instr, 2, 3, -2)
def test_embedded_null_chars(self):
# reject embedded null bytes and characters
stdscr = self.stdscr
for arg in ['a', b'a']:
with self.subTest(arg=arg):
self.assertRaises(ValueError, stdscr.addstr, 'a\0')
self.assertRaises(ValueError, stdscr.addnstr, 'a\0', 1)
self.assertRaises(ValueError, stdscr.insstr, 'a\0')
self.assertRaises(ValueError, stdscr.insnstr, 'a\0', 1)
def test_module_funcs(self):
"Test module-level functions"
for func in [curses.baudrate, curses.beep, curses.can_change_color,
curses.cbreak, curses.def_prog_mode, curses.doupdate,
curses.flash, curses.flushinp,
curses.has_colors, curses.has_ic, curses.has_il,
curses.isendwin, curses.killchar, curses.longname,
curses.nocbreak, curses.noecho, curses.nonl,
curses.noqiflush, curses.noraw,
curses.reset_prog_mode, curses.termattrs,
curses.termname, curses.erasechar]:
with self.subTest(func=func.__qualname__):
func()
if hasattr(curses, 'filter'):
curses.filter()
if hasattr(curses, 'getsyx'):
curses.getsyx()
# Functions that actually need arguments
if curses.tigetstr("cnorm"):
curses.curs_set(1)
curses.delay_output(1)
curses.echo() ; curses.echo(1)
with tempfile.TemporaryFile() as f:
self.stdscr.putwin(f)
f.seek(0)
curses.getwin(f)
curses.halfdelay(1)
curses.intrflush(1)
curses.meta(1)
curses.napms(100)
curses.newpad(50,50)
win = curses.newwin(5,5)
win = curses.newwin(5,5, 1,1)
curses.nl() ; curses.nl(1)
curses.putp(b'abc')
curses.qiflush()
curses.raw() ; curses.raw(1)
if hasattr(curses, 'setsyx'):
curses.setsyx(5,5)
curses.tigetflag('hc')
curses.tigetnum('co')
curses.tigetstr('cr')
curses.tparm(b'cr')
if hasattr(curses, 'typeahead'):
curses.typeahead(sys.__stdin__.fileno())
curses.unctrl('a')
curses.ungetch('a')
if hasattr(curses, 'use_env'):
curses.use_env(1)
# Functions only available on a few platforms
def test_colors_funcs(self):
if not curses.has_colors():
self.skipTest('requires colors support')
curses.start_color()
curses.init_pair(2, 1,1)
curses.color_content(1)
curses.color_pair(2)
curses.pair_content(curses.COLOR_PAIRS - 1)
curses.pair_number(0)
if hasattr(curses, 'use_default_colors'):
curses.use_default_colors()
@requires_curses_func('keyname')
def test_keyname(self):
curses.keyname(13)
@requires_curses_func('has_key')
def test_has_key(self):
curses.has_key(13)
@requires_curses_func('getmouse')
def test_getmouse(self):
(availmask, oldmask) = curses.mousemask(curses.BUTTON1_PRESSED)
if availmask == 0:
self.skipTest('mouse stuff not available')
curses.mouseinterval(10)
# just verify these don't cause errors
curses.ungetmouse(0, 0, 0, 0, curses.BUTTON1_PRESSED)
m = curses.getmouse()
@requires_curses_func('panel')
def test_userptr_without_set(self):
w = curses.newwin(10, 10)
p = curses.panel.new_panel(w)
# try to access userptr() before calling set_userptr() -- segfaults
with self.assertRaises(curses.panel.error,
msg='userptr should fail since not set'):
p.userptr()
@requires_curses_func('panel')
def test_userptr_memory_leak(self):
w = curses.newwin(10, 10)
p = curses.panel.new_panel(w)
obj = object()
nrefs = sys.getrefcount(obj)
for i in range(100):
p.set_userptr(obj)
p.set_userptr(None)
self.assertEqual(sys.getrefcount(obj), nrefs,
"set_userptr leaked references")
@requires_curses_func('panel')
def test_userptr_segfault(self):
w = curses.newwin(10, 10)
panel = curses.panel.new_panel(w)
class A:
def __del__(self):
panel.set_userptr(None)
panel.set_userptr(A())
panel.set_userptr(None)
@requires_curses_func('panel')
def test_new_curses_panel(self):
w = curses.newwin(10, 10)
panel = curses.panel.new_panel(w)
self.assertRaises(TypeError, type(panel))
@requires_curses_func('is_term_resized')
def test_is_term_resized(self):
curses.is_term_resized(*self.stdscr.getmaxyx())
@requires_curses_func('resize_term')
def test_resize_term(self):
curses.resize_term(*self.stdscr.getmaxyx())
@requires_curses_func('resizeterm')
def test_resizeterm(self):
stdscr = self.stdscr
lines, cols = curses.LINES, curses.COLS
new_lines = lines - 1
new_cols = cols + 1
curses.resizeterm(new_lines, new_cols)
self.assertEqual(curses.LINES, new_lines)
self.assertEqual(curses.COLS, new_cols)
def test_issue6243(self):
curses.ungetch(1025)
self.stdscr.getkey()
@requires_curses_func('unget_wch')
# XXX Remove the decorator when ncurses on OpenBSD be updated
@unittest.skipIf(sys.platform.startswith("openbsd"),
"OpenBSD's curses (v.5.7) has bugs")
def test_unget_wch(self):
stdscr = self.stdscr
encoding = stdscr.encoding
for ch in ('a', '\xe9', '\u20ac', '\U0010FFFF'):
try:
ch.encode(encoding)
except UnicodeEncodeError:
continue
try:
curses.unget_wch(ch)
except Exception as err:
self.fail("unget_wch(%a) failed with encoding %s: %s"
% (ch, stdscr.encoding, err))
read = stdscr.get_wch()
self.assertEqual(read, ch)
code = ord(ch)
curses.unget_wch(code)
read = stdscr.get_wch()
self.assertEqual(read, ch)
def test_issue10570(self):
b = curses.tparm(curses.tigetstr("cup"), 5, 3)
self.assertIs(type(b), bytes)
def test_encoding(self):
stdscr = self.stdscr
import codecs
encoding = stdscr.encoding
codecs.lookup(encoding)
with self.assertRaises(TypeError):
stdscr.encoding = 10
stdscr.encoding = encoding
with self.assertRaises(TypeError):
del stdscr.encoding
def test_issue21088(self):
stdscr = self.stdscr
#
# http://bugs.python.org/issue21088
#
# the bug:
# when converting curses.window.addch to Argument Clinic
# the first two parameters were switched.
# if someday we can represent the signature of addch
# we will need to rewrite this test.
try:
signature = inspect.signature(stdscr.addch)
self.assertFalse(signature)
except ValueError:
# not generating a signature is fine.
pass
# So. No signature for addch.
# But Argument Clinic gave us a human-readable equivalent
# as the first line of the docstring. So we parse that,
# and ensure that the parameters appear in the correct order.
# Since this is parsing output from Argument Clinic, we can
# be reasonably certain the generated parsing code will be
# correct too.
human_readable_signature = stdscr.addch.__doc__.split("\n")[0]
self.assertIn("[y, x,]", human_readable_signature)
def test_issue13051(self):
stdscr = self.stdscr
if not hasattr(stdscr, 'resize'):
raise unittest.SkipTest('requires curses.window.resize')
box = curses.textpad.Textbox(stdscr, insert_mode=True)
lines, cols = stdscr.getmaxyx()
stdscr.resize(lines-2, cols-2)
# this may cause infinite recursion, leading to a RuntimeError
box._insert_printable_char('a')
class MiscTests(unittest.TestCase):
@requires_curses_func('update_lines_cols')
def test_update_lines_cols(self):
# this doesn't actually test that LINES and COLS are updated,
# because we can't automate changing them. See Issue #4254 for
# a manual test script. We can only test that the function
# can be called.
curses.update_lines_cols()
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)
for i in (-2, -1, 256, sys.maxunicode, sys.maxunicode+1):
self.assertFalse(curses.ascii.isalnum(i))
self.assertFalse(curses.ascii.isalpha(i))
self.assertFalse(curses.ascii.isdigit(i))
self.assertFalse(curses.ascii.islower(i))
self.assertFalse(curses.ascii.isspace(i))
self.assertFalse(curses.ascii.isupper(i))
self.assertFalse(curses.ascii.isascii(i))
self.assertFalse(curses.ascii.isctrl(i))
self.assertFalse(curses.ascii.iscntrl(i))
self.assertFalse(curses.ascii.isblank(i))
self.assertFalse(curses.ascii.isgraph(i))
self.assertFalse(curses.ascii.isprint(i))
self.assertFalse(curses.ascii.ispunct(i))
self.assertFalse(curses.ascii.isxdigit(i))
self.assertFalse(curses.ascii.ismeta(-1))
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')
self.assertEqual(unctrl('A'), 'A')
self.assertEqual(unctrl(';'), ';')
self.assertEqual(unctrl(' '), ' ')
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__':
unittest.main()
| 19,302 | 550 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_unicodedata.py | """ Test script for the unicodedata module.
Written by Marc-Andre Lemburg ([email protected]).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""
import sys
import cosmo
import unittest
import hashlib
import unicodedata
from test.support import script_helper
encoding = 'utf-8'
errors = 'surrogatepass'
### Run tests
class UnicodeMethodsTest(unittest.TestCase):
# update this, if the database changes
if unicodedata.unidata_version == '9.0.0':
expectedchecksum = 'c1fa98674a683aa8a8d8dee0c84494f8d36346e6'
else:
expectedchecksum = '963069fe950f9ece86a4bf04ae3d0e705d9a5d12'
def test_method_checksum(self):
h = hashlib.sha1()
for i in range(0x10000):
char = chr(i)
data = [
# Predicates (single char)
"01"[char.isalnum()],
"01"[char.isalpha()],
"01"[char.isdecimal()],
"01"[char.isdigit()],
"01"[char.islower()],
"01"[char.isnumeric()],
"01"[char.isspace()],
"01"[char.istitle()],
"01"[char.isupper()],
# Predicates (multiple chars)
"01"[(char + 'abc').isalnum()],
"01"[(char + 'abc').isalpha()],
"01"[(char + '123').isdecimal()],
"01"[(char + '123').isdigit()],
"01"[(char + 'abc').islower()],
"01"[(char + '123').isnumeric()],
"01"[(char + ' \t').isspace()],
"01"[(char + 'abc').istitle()],
"01"[(char + 'ABC').isupper()],
# Mappings (single char)
char.lower(),
char.upper(),
char.title(),
# Mappings (multiple chars)
(char + 'abc').lower(),
(char + 'ABC').upper(),
(char + 'abc').title(),
(char + 'ABC').title(),
]
h.update(''.join(data).encode(encoding, errors))
result = h.hexdigest()
self.assertEqual(result, self.expectedchecksum)
class UnicodeDatabaseTest(unittest.TestCase):
def setUp(self):
# In case unicodedata is not available, this will raise an ImportError,
# but the other test cases will still be run
import unicodedata
self.db = unicodedata
def tearDown(self):
del self.db
class UnicodeFunctionsTest(UnicodeDatabaseTest):
# Update this if the database changes. Make sure to do a full rebuild
# (e.g. 'make distclean && make') to get the correct checksum.
if unicodedata.unidata_version == '9.0.0':
expectedchecksum = 'f891b1e6430c712531b9bc935a38e22d78ba1bf3'
else:
expectedchecksum = '7d4726cea1a3eb811af289489beea66f225cc251'
def test_function_checksum(self):
data = []
h = hashlib.sha1()
for i in range(0x10000):
char = chr(i)
data = [
# Properties
format(self.db.digit(char, -1), '.12g'),
format(self.db.numeric(char, -1), '.12g'),
format(self.db.decimal(char, -1), '.12g'),
self.db.category(char),
self.db.bidirectional(char),
self.db.decomposition(char),
str(self.db.mirrored(char)),
str(self.db.combining(char)),
]
h.update(''.join(data).encode("ascii"))
result = h.hexdigest()
self.assertEqual(result, self.expectedchecksum)
def test_digit(self):
self.assertEqual(self.db.digit('A', None), None)
self.assertEqual(self.db.digit('9'), 9)
self.assertEqual(self.db.digit('\u215b', None), None)
self.assertEqual(self.db.digit('\u2468'), 9)
self.assertEqual(self.db.digit('\U00020000', None), None)
self.assertEqual(self.db.digit('\U0001D7FD'), 7)
self.assertRaises(TypeError, self.db.digit)
self.assertRaises(TypeError, self.db.digit, 'xx')
self.assertRaises(ValueError, self.db.digit, 'x')
def test_numeric(self):
self.assertEqual(self.db.numeric('A',None), None)
self.assertEqual(self.db.numeric('9'), 9)
self.assertEqual(self.db.numeric('\u215b'), 0.125)
self.assertEqual(self.db.numeric('\u2468'), 9.0)
self.assertEqual(self.db.numeric('\ua627'), 7.0)
self.assertRaises(TypeError, self.db.numeric)
self.assertRaises(TypeError, self.db.numeric, 'xx')
self.assertRaises(ValueError, self.db.numeric, 'x')
@unittest.skipIf(cosmo.MODE.startswith('tiny'), 'astral planes arent tiny')
def test_numeric_astral(self):
self.assertEqual(self.db.numeric('\U00020000', None), None)
self.assertEqual(self.db.numeric('\U0001012A'), 9000)
def test_decimal(self):
self.assertEqual(self.db.decimal('A',None), None)
self.assertEqual(self.db.decimal('9'), 9)
self.assertEqual(self.db.decimal('\u215b', None), None)
self.assertEqual(self.db.decimal('\u2468', None), None)
self.assertEqual(self.db.decimal('\U00020000', None), None)
self.assertEqual(self.db.decimal('\U0001D7FD'), 7)
self.assertRaises(TypeError, self.db.decimal)
self.assertRaises(TypeError, self.db.decimal, 'xx')
self.assertRaises(ValueError, self.db.decimal, 'x')
def test_category(self):
self.assertEqual(self.db.category('\uFFFE'), 'Cn')
self.assertEqual(self.db.category('a'), 'Ll')
self.assertEqual(self.db.category('A'), 'Lu')
self.assertEqual(self.db.category('\U00020000'), 'Lo')
self.assertEqual(self.db.category('\U0001012A'), 'No')
self.assertRaises(TypeError, self.db.category)
self.assertRaises(TypeError, self.db.category, 'xx')
def test_bidirectional(self):
self.assertEqual(self.db.bidirectional('\uFFFE'), '')
self.assertEqual(self.db.bidirectional(' '), 'WS')
self.assertEqual(self.db.bidirectional('A'), 'L')
self.assertEqual(self.db.bidirectional('\U00020000'), 'L')
self.assertRaises(TypeError, self.db.bidirectional)
self.assertRaises(TypeError, self.db.bidirectional, 'xx')
def test_decomposition(self):
self.assertEqual(self.db.decomposition('\uFFFE'),'')
self.assertEqual(self.db.decomposition('\u00bc'), '<fraction> 0031 2044 0034')
self.assertRaises(TypeError, self.db.decomposition)
self.assertRaises(TypeError, self.db.decomposition, 'xx')
def test_mirrored(self):
self.assertEqual(self.db.mirrored('\uFFFE'), 0)
self.assertEqual(self.db.mirrored('a'), 0)
self.assertEqual(self.db.mirrored('\u2201'), 1)
self.assertEqual(self.db.mirrored('\U00020000'), 0)
self.assertRaises(TypeError, self.db.mirrored)
self.assertRaises(TypeError, self.db.mirrored, 'xx')
def test_combining(self):
self.assertEqual(self.db.combining('\uFFFE'), 0)
self.assertEqual(self.db.combining('a'), 0)
self.assertEqual(self.db.combining('\u20e1'), 230)
self.assertEqual(self.db.combining('\U00020000'), 0)
self.assertRaises(TypeError, self.db.combining)
self.assertRaises(TypeError, self.db.combining, 'xx')
def test_normalize(self):
self.assertRaises(TypeError, self.db.normalize)
self.assertRaises(ValueError, self.db.normalize, 'unknown', 'xx')
self.assertEqual(self.db.normalize('NFKC', ''), '')
# The rest can be found in test_normalization.py
# which requires an external file.
def test_pr29(self):
# http://www.unicode.org/review/pr-29.html
# See issues #1054943 and #10254.
composed = ("\u0b47\u0300\u0b3e", "\u1100\u0300\u1161",
'Li\u030dt-s\u1e73\u0301',
'\u092e\u093e\u0930\u094d\u0915 \u091c\u093c'
+ '\u0941\u0915\u0947\u0930\u092c\u0930\u094d\u0917',
'\u0915\u093f\u0930\u094d\u0917\u093f\u091c\u093c'
+ '\u0938\u094d\u0924\u093e\u0928')
for text in composed:
self.assertEqual(self.db.normalize('NFC', text), text)
def test_issue10254(self):
# Crash reported in #10254
a = 'C\u0338' * 20 + 'C\u0327'
b = 'C\u0338' * 20 + '\xC7'
self.assertEqual(self.db.normalize('NFC', a), b)
def test_issue29456(self):
# Fix #29456
u1176_str_a = '\u1100\u1176\u11a8'
u1176_str_b = '\u1100\u1176\u11a8'
u11a7_str_a = '\u1100\u1175\u11a7'
u11a7_str_b = '\uae30\u11a7'
u11c3_str_a = '\u1100\u1175\u11c3'
u11c3_str_b = '\uae30\u11c3'
self.assertEqual(self.db.normalize('NFC', u1176_str_a), u1176_str_b)
self.assertEqual(self.db.normalize('NFC', u11a7_str_a), u11a7_str_b)
self.assertEqual(self.db.normalize('NFC', u11c3_str_a), u11c3_str_b)
def test_east_asian_width(self):
eaw = self.db.east_asian_width
self.assertRaises(TypeError, eaw, b'a')
self.assertRaises(TypeError, eaw, bytearray())
self.assertRaises(TypeError, eaw, '')
self.assertRaises(TypeError, eaw, 'ra')
self.assertEqual(eaw('\x1e'), 'N')
self.assertEqual(eaw('\x20'), 'Na')
self.assertEqual(eaw('\uC894'), 'W')
self.assertEqual(eaw('\uFF66'), 'H')
self.assertEqual(eaw('\uFF1F'), 'F')
self.assertEqual(eaw('\u2010'), 'A')
self.assertEqual(eaw('\U00020000'), 'W')
def test_east_asian_width_9_0_changes(self):
self.assertEqual(self.db.ucd_3_2_0.east_asian_width('\u231a'), 'N')
self.assertEqual(self.db.east_asian_width('\u231a'), 'W')
class UnicodeMiscTest(UnicodeDatabaseTest):
def test_decimal_numeric_consistent(self):
# Test that decimal and numeric are consistent,
# i.e. if a character has a decimal value,
# its numeric value should be the same.
count = 0
for i in range(0x10000):
c = chr(i)
dec = self.db.decimal(c, -1)
if dec != -1:
self.assertEqual(dec, self.db.numeric(c))
count += 1
self.assertTrue(count >= 10) # should have tested at least the ASCII digits
def test_digit_numeric_consistent(self):
# Test that digit and numeric are consistent,
# i.e. if a character has a digit value,
# its numeric value should be the same.
count = 0
for i in range(0x10000):
c = chr(i)
dec = self.db.digit(c, -1)
if dec != -1:
self.assertEqual(dec, self.db.numeric(c))
count += 1
self.assertTrue(count >= 10) # should have tested at least the ASCII digits
def test_bug_1704793(self):
self.assertEqual(self.db.lookup("GOTHIC LETTER FAIHU"), '\U00010346')
def test_ucd_510(self):
import unicodedata
# In UCD 5.1.0, a mirrored property changed wrt. UCD 3.2.0
self.assertTrue(unicodedata.mirrored("\u0f3a"))
self.assertTrue(not unicodedata.ucd_3_2_0.mirrored("\u0f3a"))
# Also, we now have two ways of representing
# the upper-case mapping: as delta, or as absolute value
self.assertTrue("a".upper()=='A')
self.assertTrue("\u1d79".upper()=='\ua77d')
self.assertTrue(".".upper()=='.')
def test_bug_5828(self):
self.assertEqual("\u1d79".lower(), "\u1d79")
# Only U+0000 should have U+0000 as its upper/lower/titlecase variant
self.assertEqual(
[
c for c in range(sys.maxunicode+1)
if "\x00" in chr(c).lower()+chr(c).upper()+chr(c).title()
],
[0]
)
def test_bug_4971(self):
# LETTER DZ WITH CARON: DZ, Dz, dz
self.assertEqual("\u01c4".title(), "\u01c5")
self.assertEqual("\u01c5".title(), "\u01c5")
self.assertEqual("\u01c6".title(), "\u01c5")
def test_linebreak_7643(self):
for i in range(0x10000):
lines = (chr(i) + 'A').splitlines()
if i in (0x0a, 0x0b, 0x0c, 0x0d, 0x85,
0x1c, 0x1d, 0x1e, 0x2028, 0x2029):
self.assertEqual(len(lines), 2,
r"\u%.4x should be a linebreak" % i)
else:
self.assertEqual(len(lines), 1,
r"\u%.4x should not be a linebreak" % i)
if __name__ == "__main__":
unittest.main()
| 12,556 | 323 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_codecencodings_kr.py | #
# test_codecencodings_kr.py
# Codec encoding tests for ROK encodings.
#
from test import multibytecodec_support
import unittest
class Test_CP949(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'cp949'
tstring = multibytecodec_support.load_teststring('cp949')
codectests = (
# invalid bytes
(b"abc\x80\x80\xc1\xc4", "strict", None),
(b"abc\xc8", "strict", None),
(b"abc\x80\x80\xc1\xc4", "replace", "abc\ufffd\ufffd\uc894"),
(b"abc\x80\x80\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\uc894\ufffd"),
(b"abc\x80\x80\xc1\xc4", "ignore", "abc\uc894"),
)
class Test_EUCKR(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'euc_kr'
tstring = multibytecodec_support.load_teststring('euc_kr')
codectests = (
# invalid bytes
(b"abc\x80\x80\xc1\xc4", "strict", None),
(b"abc\xc8", "strict", None),
(b"abc\x80\x80\xc1\xc4", "replace", 'abc\ufffd\ufffd\uc894'),
(b"abc\x80\x80\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\uc894\ufffd"),
(b"abc\x80\x80\xc1\xc4", "ignore", "abc\uc894"),
# composed make-up sequence errors
(b"\xa4\xd4", "strict", None),
(b"\xa4\xd4\xa4", "strict", None),
(b"\xa4\xd4\xa4\xb6", "strict", None),
(b"\xa4\xd4\xa4\xb6\xa4", "strict", None),
(b"\xa4\xd4\xa4\xb6\xa4\xd0", "strict", None),
(b"\xa4\xd4\xa4\xb6\xa4\xd0\xa4", "strict", None),
(b"\xa4\xd4\xa4\xb6\xa4\xd0\xa4\xd4", "strict", "\uc4d4"),
(b"\xa4\xd4\xa4\xb6\xa4\xd0\xa4\xd4x", "strict", "\uc4d4x"),
(b"a\xa4\xd4\xa4\xb6\xa4", "replace", 'a\ufffd'),
(b"\xa4\xd4\xa3\xb6\xa4\xd0\xa4\xd4", "strict", None),
(b"\xa4\xd4\xa4\xb6\xa3\xd0\xa4\xd4", "strict", None),
(b"\xa4\xd4\xa4\xb6\xa4\xd0\xa3\xd4", "strict", None),
(b"\xa4\xd4\xa4\xff\xa4\xd0\xa4\xd4", "replace", '\ufffd\u6e21\ufffd\u3160\ufffd'),
(b"\xa4\xd4\xa4\xb6\xa4\xff\xa4\xd4", "replace", '\ufffd\u6e21\ub544\ufffd\ufffd'),
(b"\xa4\xd4\xa4\xb6\xa4\xd0\xa4\xff", "replace", '\ufffd\u6e21\ub544\u572d\ufffd'),
(b"\xa4\xd4\xff\xa4\xd4\xa4\xb6\xa4\xd0\xa4\xd4", "replace", '\ufffd\ufffd\ufffd\uc4d4'),
(b"\xc1\xc4", "strict", "\uc894"),
)
class Test_JOHAB(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'johab'
tstring = multibytecodec_support.load_teststring('johab')
codectests = (
# invalid bytes
(b"abc\x80\x80\xc1\xc4", "strict", None),
(b"abc\xc8", "strict", None),
(b"abc\x80\x80\xc1\xc4", "replace", "abc\ufffd\ufffd\ucd27"),
(b"abc\x80\x80\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\ucd27\ufffd"),
(b"abc\x80\x80\xc1\xc4", "ignore", "abc\ucd27"),
(b"\xD8abc", "replace", "\uFFFDabc"),
(b"\xD8\xFFabc", "replace", "\uFFFD\uFFFDabc"),
(b"\x84bxy", "replace", "\uFFFDbxy"),
(b"\x8CBxy", "replace", "\uFFFDBxy"),
)
if __name__ == "__main__":
unittest.main()
| 3,028 | 70 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_richcmp.py | # Tests for rich comparisons
import unittest
import cosmo
from test import support
import operator
class Number:
def __init__(self, x):
self.x = x
def __lt__(self, other):
return self.x < other
def __le__(self, other):
return self.x <= other
def __eq__(self, other):
return self.x == other
def __ne__(self, other):
return self.x != other
def __gt__(self, other):
return self.x > other
def __ge__(self, other):
return self.x >= other
def __cmp__(self, other):
raise support.TestFailed("Number.__cmp__() should not be called")
def __repr__(self):
return "Number(%r)" % (self.x, )
class Vector:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, i):
return self.data[i]
def __setitem__(self, i, v):
self.data[i] = v
__hash__ = None # Vectors cannot be hashed
def __bool__(self):
raise TypeError("Vectors cannot be used in Boolean contexts")
def __cmp__(self, other):
raise support.TestFailed("Vector.__cmp__() should not be called")
def __repr__(self):
return "Vector(%r)" % (self.data, )
def __lt__(self, other):
return Vector([a < b for a, b in zip(self.data, self.__cast(other))])
def __le__(self, other):
return Vector([a <= b for a, b in zip(self.data, self.__cast(other))])
def __eq__(self, other):
return Vector([a == b for a, b in zip(self.data, self.__cast(other))])
def __ne__(self, other):
return Vector([a != b for a, b in zip(self.data, self.__cast(other))])
def __gt__(self, other):
return Vector([a > b for a, b in zip(self.data, self.__cast(other))])
def __ge__(self, other):
return Vector([a >= b for a, b in zip(self.data, self.__cast(other))])
def __cast(self, other):
if isinstance(other, Vector):
other = other.data
if len(self.data) != len(other):
raise ValueError("Cannot compare vectors of different length")
return other
opmap = {
"lt": (lambda a,b: a< b, operator.lt, operator.__lt__),
"le": (lambda a,b: a<=b, operator.le, operator.__le__),
"eq": (lambda a,b: a==b, operator.eq, operator.__eq__),
"ne": (lambda a,b: a!=b, operator.ne, operator.__ne__),
"gt": (lambda a,b: a> b, operator.gt, operator.__gt__),
"ge": (lambda a,b: a>=b, operator.ge, operator.__ge__)
}
class VectorTest(unittest.TestCase):
def checkfail(self, error, opname, *args):
for op in opmap[opname]:
self.assertRaises(error, op, *args)
def checkequal(self, opname, a, b, expres):
for op in opmap[opname]:
realres = op(a, b)
# can't use assertEqual(realres, expres) here
self.assertEqual(len(realres), len(expres))
for i in range(len(realres)):
# results are bool, so we can use "is" here
self.assertTrue(realres[i] is expres[i])
def test_mixed(self):
# check that comparisons involving Vector objects
# which return rich results (i.e. Vectors with itemwise
# comparison results) work
a = Vector(range(2))
b = Vector(range(3))
# all comparisons should fail for different length
for opname in opmap:
self.checkfail(ValueError, opname, a, b)
a = list(range(5))
b = 5 * [2]
# try mixed arguments (but not (a, b) as that won't return a bool vector)
args = [(a, Vector(b)), (Vector(a), b), (Vector(a), Vector(b))]
for (a, b) in args:
self.checkequal("lt", a, b, [True, True, False, False, False])
self.checkequal("le", a, b, [True, True, True, False, False])
self.checkequal("eq", a, b, [False, False, True, False, False])
self.checkequal("ne", a, b, [True, True, False, True, True ])
self.checkequal("gt", a, b, [False, False, False, True, True ])
self.checkequal("ge", a, b, [False, False, True, True, True ])
for ops in opmap.values():
for op in ops:
# calls __bool__, which should fail
self.assertRaises(TypeError, bool, op(a, b))
class NumberTest(unittest.TestCase):
def test_basic(self):
# Check that comparisons involving Number objects
# give the same results give as comparing the
# corresponding ints
for a in range(3):
for b in range(3):
for typea in (int, Number):
for typeb in (int, Number):
if typea==typeb==int:
continue # the combination int, int is useless
ta = typea(a)
tb = typeb(b)
for ops in opmap.values():
for op in ops:
realoutcome = op(a, b)
testoutcome = op(ta, tb)
self.assertEqual(realoutcome, testoutcome)
def checkvalue(self, opname, a, b, expres):
for typea in (int, Number):
for typeb in (int, Number):
ta = typea(a)
tb = typeb(b)
for op in opmap[opname]:
realres = op(ta, tb)
realres = getattr(realres, "x", realres)
self.assertTrue(realres is expres)
def test_values(self):
# check all operators and all comparison results
self.checkvalue("lt", 0, 0, False)
self.checkvalue("le", 0, 0, True )
self.checkvalue("eq", 0, 0, True )
self.checkvalue("ne", 0, 0, False)
self.checkvalue("gt", 0, 0, False)
self.checkvalue("ge", 0, 0, True )
self.checkvalue("lt", 0, 1, True )
self.checkvalue("le", 0, 1, True )
self.checkvalue("eq", 0, 1, False)
self.checkvalue("ne", 0, 1, True )
self.checkvalue("gt", 0, 1, False)
self.checkvalue("ge", 0, 1, False)
self.checkvalue("lt", 1, 0, False)
self.checkvalue("le", 1, 0, False)
self.checkvalue("eq", 1, 0, False)
self.checkvalue("ne", 1, 0, True )
self.checkvalue("gt", 1, 0, True )
self.checkvalue("ge", 1, 0, True )
class MiscTest(unittest.TestCase):
def test_misbehavin(self):
class Misb:
def __lt__(self_, other): return 0
def __gt__(self_, other): return 0
def __eq__(self_, other): return 0
def __le__(self_, other): self.fail("This shouldn't happen")
def __ge__(self_, other): self.fail("This shouldn't happen")
def __ne__(self_, other): self.fail("This shouldn't happen")
a = Misb()
b = Misb()
self.assertEqual(a<b, 0)
self.assertEqual(a==b, 0)
self.assertEqual(a>b, 0)
def test_not(self):
# Check that exceptions in __bool__ are properly
# propagated by the not operator
import operator
class Exc(Exception):
pass
class Bad:
def __bool__(self):
raise Exc
def do(bad):
not bad
for func in (do, operator.not_):
self.assertRaises(Exc, func, Bad())
@unittest.skipUnless(cosmo.MODE == "dbg", "TODO: disabled recursion checking")
@support.no_tracing
def test_recursion(self):
# Check that comparison for recursive objects fails gracefully
from collections import UserList
a = UserList()
b = UserList()
a.append(b)
b.append(a)
self.assertRaises(RecursionError, operator.eq, a, b)
self.assertRaises(RecursionError, operator.ne, a, b)
self.assertRaises(RecursionError, operator.lt, a, b)
self.assertRaises(RecursionError, operator.le, a, b)
self.assertRaises(RecursionError, operator.gt, a, b)
self.assertRaises(RecursionError, operator.ge, a, b)
b.append(17)
# Even recursive lists of different lengths are different,
# but they cannot be ordered
self.assertTrue(not (a == b))
self.assertTrue(a != b)
self.assertRaises(RecursionError, operator.lt, a, b)
self.assertRaises(RecursionError, operator.le, a, b)
self.assertRaises(RecursionError, operator.gt, a, b)
self.assertRaises(RecursionError, operator.ge, a, b)
a.append(17)
self.assertRaises(RecursionError, operator.eq, a, b)
self.assertRaises(RecursionError, operator.ne, a, b)
a.insert(0, 11)
b.insert(0, 12)
self.assertTrue(not (a == b))
self.assertTrue(a != b)
self.assertTrue(a < b)
def test_exception_message(self):
class Spam:
pass
tests = [
(lambda: 42 < None, r"'<' .* of 'int' and 'NoneType'"),
(lambda: None < 42, r"'<' .* of 'NoneType' and 'int'"),
(lambda: 42 > None, r"'>' .* of 'int' and 'NoneType'"),
(lambda: "foo" < None, r"'<' .* of 'str' and 'NoneType'"),
(lambda: "foo" >= 666, r"'>=' .* of 'str' and 'int'"),
(lambda: 42 <= None, r"'<=' .* of 'int' and 'NoneType'"),
(lambda: 42 >= None, r"'>=' .* of 'int' and 'NoneType'"),
(lambda: 42 < [], r"'<' .* of 'int' and 'list'"),
(lambda: () > [], r"'>' .* of 'tuple' and 'list'"),
(lambda: None >= None, r"'>=' .* of 'NoneType' and 'NoneType'"),
(lambda: Spam() < 42, r"'<' .* of 'Spam' and 'int'"),
(lambda: 42 < Spam(), r"'<' .* of 'int' and 'Spam'"),
(lambda: Spam() <= Spam(), r"'<=' .* of 'Spam' and 'Spam'"),
]
for i, test in enumerate(tests):
with self.subTest(test=i):
with self.assertRaisesRegex(TypeError, test[1]):
test[0]()
class DictTest(unittest.TestCase):
def test_dicts(self):
# Verify that __eq__ and __ne__ work for dicts even if the keys and
# values don't support anything other than __eq__ and __ne__ (and
# __hash__). Complex numbers are a fine example of that.
import random
imag1a = {}
for i in range(50):
imag1a[random.randrange(100)*1j] = random.randrange(100)*1j
items = list(imag1a.items())
random.shuffle(items)
imag1b = {}
for k, v in items:
imag1b[k] = v
imag2 = imag1b.copy()
imag2[k] = v + 1.0
self.assertEqual(imag1a, imag1a)
self.assertEqual(imag1a, imag1b)
self.assertEqual(imag2, imag2)
self.assertTrue(imag1a != imag2)
for opname in ("lt", "le", "gt", "ge"):
for op in opmap[opname]:
self.assertRaises(TypeError, op, imag1a, imag2)
class ListTest(unittest.TestCase):
def test_coverage(self):
# exercise all comparisons for lists
x = [42]
self.assertIs(x<x, False)
self.assertIs(x<=x, True)
self.assertIs(x==x, True)
self.assertIs(x!=x, False)
self.assertIs(x>x, False)
self.assertIs(x>=x, True)
y = [42, 42]
self.assertIs(x<y, True)
self.assertIs(x<=y, True)
self.assertIs(x==y, False)
self.assertIs(x!=y, True)
self.assertIs(x>y, False)
self.assertIs(x>=y, False)
def test_badentry(self):
# make sure that exceptions for item comparison are properly
# propagated in list comparisons
class Exc(Exception):
pass
class Bad:
def __eq__(self, other):
raise Exc
x = [Bad()]
y = [Bad()]
for op in opmap["eq"]:
self.assertRaises(Exc, op, x, y)
def test_goodentry(self):
# This test exercises the final call to PyObject_RichCompare()
# in Objects/listobject.c::list_richcompare()
class Good:
def __lt__(self, other):
return True
x = [Good()]
y = [Good()]
for op in opmap["lt"]:
self.assertIs(op(x, y), True)
if __name__ == "__main__":
unittest.main()
| 12,292 | 358 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_pdb.py | # A test suite for pdb; not very comprehensive at the moment.
import doctest
import os
import pdb
import sys
import types
import unittest
import subprocess
import textwrap
from test import support
# This little helper class is essential for testing pdb under doctest.
from test.test_doctest import _FakeInput
class PdbTestInput(object):
"""Context manager that makes testing Pdb in doctests easier."""
def __init__(self, input):
self.input = input
def __enter__(self):
self.real_stdin = sys.stdin
sys.stdin = _FakeInput(self.input)
self.orig_trace = sys.gettrace() if hasattr(sys, 'gettrace') else None
def __exit__(self, *exc):
sys.stdin = self.real_stdin
if self.orig_trace:
sys.settrace(self.orig_trace)
def test_pdb_displayhook():
"""This tests the custom displayhook for pdb.
>>> def test_function(foo, bar):
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... pass
>>> with PdbTestInput([
... 'foo',
... 'bar',
... 'for i in range(5): print(i)',
... 'continue',
... ]):
... test_function(1, None)
> <doctest test.test_pdb.test_pdb_displayhook[0]>(3)test_function()
-> pass
(Pdb) foo
1
(Pdb) bar
(Pdb) for i in range(5): print(i)
0
1
2
3
4
(Pdb) continue
"""
def test_pdb_basic_commands():
"""Test the basic commands of pdb.
>>> def test_function_2(foo, bar='default'):
... print(foo)
... for i in range(5):
... print(i)
... print(bar)
... for i in range(10):
... never_executed
... print('after for')
... print('...')
... return foo.upper()
>>> def test_function():
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... ret = test_function_2('baz')
... print(ret)
>>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
... 'step', # entering the function call
... 'args', # display function args
... 'list', # list function source
... 'bt', # display backtrace
... 'up', # step up to test_function()
... 'down', # step down to test_function_2() again
... 'next', # stepping to print(foo)
... 'next', # stepping to the for loop
... 'step', # stepping into the for loop
... 'until', # continuing until out of the for loop
... 'next', # executing the print(bar)
... 'jump 8', # jump over second for loop
... 'return', # return out of function
... 'retval', # display return value
... 'continue',
... ]):
... test_function()
> <doctest test.test_pdb.test_pdb_basic_commands[1]>(3)test_function()
-> ret = test_function_2('baz')
(Pdb) step
--Call--
> <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
-> def test_function_2(foo, bar='default'):
(Pdb) args
foo = 'baz'
bar = 'default'
(Pdb) list
1 -> def test_function_2(foo, bar='default'):
2 print(foo)
3 for i in range(5):
4 print(i)
5 print(bar)
6 for i in range(10):
7 never_executed
8 print('after for')
9 print('...')
10 return foo.upper()
[EOF]
(Pdb) bt
...
<doctest test.test_pdb.test_pdb_basic_commands[2]>(18)<module>()
-> test_function()
<doctest test.test_pdb.test_pdb_basic_commands[1]>(3)test_function()
-> ret = test_function_2('baz')
> <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
-> def test_function_2(foo, bar='default'):
(Pdb) up
> <doctest test.test_pdb.test_pdb_basic_commands[1]>(3)test_function()
-> ret = test_function_2('baz')
(Pdb) down
> <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
-> def test_function_2(foo, bar='default'):
(Pdb) next
> <doctest test.test_pdb.test_pdb_basic_commands[0]>(2)test_function_2()
-> print(foo)
(Pdb) next
baz
> <doctest test.test_pdb.test_pdb_basic_commands[0]>(3)test_function_2()
-> for i in range(5):
(Pdb) step
> <doctest test.test_pdb.test_pdb_basic_commands[0]>(4)test_function_2()
-> print(i)
(Pdb) until
0
1
2
3
4
> <doctest test.test_pdb.test_pdb_basic_commands[0]>(5)test_function_2()
-> print(bar)
(Pdb) next
default
> <doctest test.test_pdb.test_pdb_basic_commands[0]>(6)test_function_2()
-> for i in range(10):
(Pdb) jump 8
> <doctest test.test_pdb.test_pdb_basic_commands[0]>(8)test_function_2()
-> print('after for')
(Pdb) return
after for
...
--Return--
> <doctest test.test_pdb.test_pdb_basic_commands[0]>(10)test_function_2()->'BAZ'
-> return foo.upper()
(Pdb) retval
'BAZ'
(Pdb) continue
BAZ
"""
def test_pdb_breakpoint_commands():
"""Test basic commands related to breakpoints.
>>> def test_function():
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... print(1)
... print(2)
... print(3)
... print(4)
First, need to clear bdb state that might be left over from previous tests.
Otherwise, the new breakpoints might get assigned different numbers.
>>> from bdb import Breakpoint
>>> Breakpoint.next = 1
>>> Breakpoint.bplist = {}
>>> Breakpoint.bpbynumber = [None]
Now test the breakpoint commands. NORMALIZE_WHITESPACE is needed because
the breakpoint list outputs a tab for the "stop only" and "ignore next"
lines, which we don't want to put in here.
>>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
... 'break 3',
... 'disable 1',
... 'ignore 1 10',
... 'condition 1 1 < 2',
... 'break 4',
... 'break 4',
... 'break',
... 'clear 3',
... 'break',
... 'condition 1',
... 'enable 1',
... 'clear 1',
... 'commands 2',
... 'p "42"',
... 'print("42", 7*6)', # Issue 18764 (not about breakpoints)
... 'end',
... 'continue', # will stop at breakpoint 2 (line 4)
... 'clear', # clear all!
... 'y',
... 'tbreak 5',
... 'continue', # will stop at temporary breakpoint
... 'break', # make sure breakpoint is gone
... 'continue',
... ]):
... test_function()
> <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(3)test_function()
-> print(1)
(Pdb) break 3
Breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
(Pdb) disable 1
Disabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
(Pdb) ignore 1 10
Will ignore next 10 crossings of breakpoint 1.
(Pdb) condition 1 1 < 2
New condition set for breakpoint 1.
(Pdb) break 4
Breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
(Pdb) break 4
Breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
(Pdb) break
Num Type Disp Enb Where
1 breakpoint keep no at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
stop only if 1 < 2
ignore next 10 hits
2 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
3 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
(Pdb) clear 3
Deleted breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
(Pdb) break
Num Type Disp Enb Where
1 breakpoint keep no at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
stop only if 1 < 2
ignore next 10 hits
2 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
(Pdb) condition 1
Breakpoint 1 is now unconditional.
(Pdb) enable 1
Enabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
(Pdb) clear 1
Deleted breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
(Pdb) commands 2
(com) p "42"
(com) print("42", 7*6)
(com) end
(Pdb) continue
1
'42'
42 42
> <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(4)test_function()
-> print(2)
(Pdb) clear
Clear all breaks? y
Deleted breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
(Pdb) tbreak 5
Breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
(Pdb) continue
2
Deleted breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
> <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(5)test_function()
-> print(3)
(Pdb) break
(Pdb) continue
3
4
"""
def do_nothing():
pass
def do_something():
print(42)
def test_list_commands():
"""Test the list and source commands of pdb.
>>> def test_function_2(foo):
... import test.test_pdb
... test.test_pdb.do_nothing()
... 'some...'
... 'more...'
... 'code...'
... 'to...'
... 'make...'
... 'a...'
... 'long...'
... 'listing...'
... 'useful...'
... '...'
... '...'
... return foo
>>> def test_function():
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... ret = test_function_2('baz')
>>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
... 'list', # list first function
... 'step', # step into second function
... 'list', # list second function
... 'list', # continue listing to EOF
... 'list 1,3', # list specific lines
... 'list x', # invalid argument
... 'next', # step to import
... 'next', # step over import
... 'step', # step into do_nothing
... 'longlist', # list all lines
... 'source do_something', # list all lines of function
... 'source fooxxx', # something that doesn't exit
... 'continue',
... ]):
... test_function()
> <doctest test.test_pdb.test_list_commands[1]>(3)test_function()
-> ret = test_function_2('baz')
(Pdb) list
1 def test_function():
2 import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
3 -> ret = test_function_2('baz')
[EOF]
(Pdb) step
--Call--
> <doctest test.test_pdb.test_list_commands[0]>(1)test_function_2()
-> def test_function_2(foo):
(Pdb) list
1 -> def test_function_2(foo):
2 import test.test_pdb
3 test.test_pdb.do_nothing()
4 'some...'
5 'more...'
6 'code...'
7 'to...'
8 'make...'
9 'a...'
10 'long...'
11 'listing...'
(Pdb) list
12 'useful...'
13 '...'
14 '...'
15 return foo
[EOF]
(Pdb) list 1,3
1 -> def test_function_2(foo):
2 import test.test_pdb
3 test.test_pdb.do_nothing()
(Pdb) list x
*** ...
(Pdb) next
> <doctest test.test_pdb.test_list_commands[0]>(2)test_function_2()
-> import test.test_pdb
(Pdb) next
> <doctest test.test_pdb.test_list_commands[0]>(3)test_function_2()
-> test.test_pdb.do_nothing()
(Pdb) step
--Call--
> ...test_pdb.py(...)do_nothing()
-> def do_nothing():
(Pdb) longlist
... -> def do_nothing():
... pass
(Pdb) source do_something
... def do_something():
... print(42)
(Pdb) source fooxxx
*** ...
(Pdb) continue
"""
def test_post_mortem():
"""Test post mortem traceback debugging.
>>> def test_function_2():
... try:
... 1/0
... finally:
... print('Exception!')
>>> def test_function():
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... test_function_2()
... print('Not reached.')
>>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
... 'next', # step over exception-raising call
... 'bt', # get a backtrace
... 'list', # list code of test_function()
... 'down', # step into test_function_2()
... 'list', # list code of test_function_2()
... 'continue',
... ]):
... try:
... test_function()
... except ZeroDivisionError:
... print('Correctly reraised.')
> <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
-> test_function_2()
(Pdb) next
Exception!
ZeroDivisionError: division by zero
> <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
-> test_function_2()
(Pdb) bt
...
<doctest test.test_pdb.test_post_mortem[2]>(10)<module>()
-> test_function()
> <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
-> test_function_2()
<doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
-> 1/0
(Pdb) list
1 def test_function():
2 import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
3 -> test_function_2()
4 print('Not reached.')
[EOF]
(Pdb) down
> <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
-> 1/0
(Pdb) list
1 def test_function_2():
2 try:
3 >> 1/0
4 finally:
5 -> print('Exception!')
[EOF]
(Pdb) continue
Correctly reraised.
"""
def test_pdb_skip_modules():
"""This illustrates the simple case of module skipping.
>>> def skip_module():
... import string
... import pdb; pdb.Pdb(skip=['stri*'], nosigint=True, readrc=False).set_trace()
... string.capwords('FOO')
>>> with PdbTestInput([
... 'step',
... 'continue',
... ]):
... skip_module()
> <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module()
-> string.capwords('FOO')
(Pdb) step
--Return--
> <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module()->None
-> string.capwords('FOO')
(Pdb) continue
"""
# Module for testing skipping of module that makes a callback
mod = types.ModuleType('module_to_skip')
exec('def foo_pony(callback): x = 1; callback(); return None', mod.__dict__)
def test_pdb_skip_modules_with_callback():
"""This illustrates skipping of modules that call into other code.
>>> def skip_module():
... def callback():
... return None
... import pdb; pdb.Pdb(skip=['module_to_skip*'], nosigint=True, readrc=False).set_trace()
... mod.foo_pony(callback)
>>> with PdbTestInput([
... 'step',
... 'step',
... 'step',
... 'step',
... 'step',
... 'continue',
... ]):
... skip_module()
... pass # provides something to "step" to
> <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module()
-> mod.foo_pony(callback)
(Pdb) step
--Call--
> <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(2)callback()
-> def callback():
(Pdb) step
> <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback()
-> return None
(Pdb) step
--Return--
> <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback()->None
-> return None
(Pdb) step
--Return--
> <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module()->None
-> mod.foo_pony(callback)
(Pdb) step
> <doctest test.test_pdb.test_pdb_skip_modules_with_callback[1]>(10)<module>()
-> pass # provides something to "step" to
(Pdb) continue
"""
def test_pdb_continue_in_bottomframe():
"""Test that "continue" and "next" work properly in bottom frame (issue #5294).
>>> def test_function():
... import pdb, sys; inst = pdb.Pdb(nosigint=True, readrc=False)
... inst.set_trace()
... inst.botframe = sys._getframe() # hackery to get the right botframe
... print(1)
... print(2)
... print(3)
... print(4)
>>> with PdbTestInput([ # doctest: +ELLIPSIS
... 'next',
... 'break 7',
... 'continue',
... 'next',
... 'continue',
... 'continue',
... ]):
... test_function()
> <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(4)test_function()
-> inst.botframe = sys._getframe() # hackery to get the right botframe
(Pdb) next
> <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(5)test_function()
-> print(1)
(Pdb) break 7
Breakpoint ... at <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>:7
(Pdb) continue
1
2
> <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(7)test_function()
-> print(3)
(Pdb) next
3
> <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(8)test_function()
-> print(4)
(Pdb) continue
4
"""
def pdb_invoke(method, arg):
"""Run pdb.method(arg)."""
getattr(pdb.Pdb(nosigint=True, readrc=False), method)(arg)
def test_pdb_run_with_incorrect_argument():
"""Testing run and runeval with incorrect first argument.
>>> pti = PdbTestInput(['continue',])
>>> with pti:
... pdb_invoke('run', lambda x: x)
Traceback (most recent call last):
TypeError: exec() arg 1 must be a string, bytes or code object
>>> with pti:
... pdb_invoke('runeval', lambda x: x)
Traceback (most recent call last):
TypeError: eval() arg 1 must be a string, bytes or code object
"""
def test_pdb_run_with_code_object():
"""Testing run and runeval with code object as a first argument.
>>> with PdbTestInput(['step','x', 'continue']): # doctest: +ELLIPSIS
... pdb_invoke('run', compile('x=1', '<string>', 'exec'))
> <string>(1)<module>()...
(Pdb) step
--Return--
> <string>(1)<module>()->None
(Pdb) x
1
(Pdb) continue
>>> with PdbTestInput(['x', 'continue']):
... x=0
... pdb_invoke('runeval', compile('x+1', '<string>', 'eval'))
> <string>(1)<module>()->None
(Pdb) x
1
(Pdb) continue
"""
def test_next_until_return_at_return_event():
"""Test that pdb stops after a next/until/return issued at a return debug event.
>>> def test_function_2():
... x = 1
... x = 2
>>> def test_function():
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... test_function_2()
... test_function_2()
... test_function_2()
... end = 1
>>> from bdb import Breakpoint
>>> Breakpoint.next = 1
>>> with PdbTestInput(['break test_function_2',
... 'continue',
... 'return',
... 'next',
... 'continue',
... 'return',
... 'until',
... 'continue',
... 'return',
... 'return',
... 'continue']):
... test_function()
> <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(3)test_function()
-> test_function_2()
(Pdb) break test_function_2
Breakpoint 1 at <doctest test.test_pdb.test_next_until_return_at_return_event[0]>:1
(Pdb) continue
> <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
-> x = 1
(Pdb) return
--Return--
> <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
-> x = 2
(Pdb) next
> <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(4)test_function()
-> test_function_2()
(Pdb) continue
> <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
-> x = 1
(Pdb) return
--Return--
> <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
-> x = 2
(Pdb) until
> <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(5)test_function()
-> test_function_2()
(Pdb) continue
> <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2()
-> x = 1
(Pdb) return
--Return--
> <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None
-> x = 2
(Pdb) return
> <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(6)test_function()
-> end = 1
(Pdb) continue
"""
def test_pdb_next_command_for_generator():
"""Testing skip unwindng stack on yield for generators for "next" command
>>> def test_gen():
... yield 0
... return 1
... yield 2
>>> def test_function():
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... it = test_gen()
... try:
... if next(it) != 0:
... raise AssertionError
... next(it)
... except StopIteration as ex:
... if ex.value != 1:
... raise AssertionError
... print("finished")
>>> with PdbTestInput(['step',
... 'step',
... 'step',
... 'next',
... 'next',
... 'step',
... 'step',
... 'continue']):
... test_function()
> <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(3)test_function()
-> it = test_gen()
(Pdb) step
> <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(4)test_function()
-> try:
(Pdb) step
> <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(5)test_function()
-> if next(it) != 0:
(Pdb) step
--Call--
> <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(1)test_gen()
-> def test_gen():
(Pdb) next
> <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(2)test_gen()
-> yield 0
(Pdb) next
> <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()
-> return 1
(Pdb) step
--Return--
> <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()->1
-> return 1
(Pdb) step
StopIteration: 1
> <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(7)test_function()
-> next(it)
(Pdb) continue
finished
"""
if False:
def test_pdb_next_command_for_coroutine():
"""Testing skip unwindng stack on yield for coroutines for "next" command
>>> import asyncio
>>> async def test_coro():
... await asyncio.sleep(0)
... await asyncio.sleep(0)
... await asyncio.sleep(0)
>>> async def test_main():
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... await test_coro()
>>> def test_function():
... loop = asyncio.new_event_loop()
... loop.run_until_complete(test_main())
... loop.close()
... print("finished")
>>> with PdbTestInput(['step',
... 'step',
... 'next',
... 'next',
... 'next',
... 'step',
... 'continue']):
... test_function()
> <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()
-> await test_coro()
(Pdb) step
--Call--
> <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(1)test_coro()
-> async def test_coro():
(Pdb) step
> <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(2)test_coro()
-> await asyncio.sleep(0)
(Pdb) next
> <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(3)test_coro()
-> await asyncio.sleep(0)
(Pdb) next
> <doctest test.test_pdb.test_pdb_next_command_for_coroutine[1]>(4)test_coro()
-> await asyncio.sleep(0)
(Pdb) next
Internal StopIteration
> <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()
-> await test_coro()
(Pdb) step
--Return--
> <doctest test.test_pdb.test_pdb_next_command_for_coroutine[2]>(3)test_main()->None
-> await test_coro()
(Pdb) continue
finished
"""
def test_pdb_next_command_for_asyncgen():
"""Testing skip unwindng stack on yield for coroutines for "next" command
>>> import asyncio
>>> async def agen():
... yield 1
... await asyncio.sleep(0)
... yield 2
>>> async def test_coro():
... async for x in agen():
... print(x)
>>> async def test_main():
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... await test_coro()
>>> def test_function():
... loop = asyncio.new_event_loop()
... loop.run_until_complete(test_main())
... loop.close()
... print("finished")
>>> with PdbTestInput(['step',
... 'step',
... 'next',
... 'next',
... 'step',
... 'next',
... 'continue']):
... test_function()
> <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[3]>(3)test_main()
-> await test_coro()
(Pdb) step
--Call--
> <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(1)test_coro()
-> async def test_coro():
(Pdb) step
> <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(2)test_coro()
-> async for x in agen():
(Pdb) next
> <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(3)test_coro()
-> print(x)
(Pdb) next
1
> <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[2]>(2)test_coro()
-> async for x in agen():
(Pdb) step
--Call--
> <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[1]>(2)agen()
-> yield 1
(Pdb) next
> <doctest test.test_pdb.test_pdb_next_command_for_asyncgen[1]>(3)agen()
-> await asyncio.sleep(0)
(Pdb) continue
2
finished
"""
def test_pdb_return_command_for_coroutine():
"""Testing no unwindng stack on yield for coroutines for "return" command
>>> import asyncio
>>> async def test_coro():
... await asyncio.sleep(0)
... await asyncio.sleep(0)
... await asyncio.sleep(0)
>>> async def test_main():
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... await test_coro()
>>> def test_function():
... loop = asyncio.new_event_loop()
... loop.run_until_complete(test_main())
... loop.close()
... print("finished")
>>> with PdbTestInput(['step',
... 'step',
... 'next',
... 'continue']):
... test_function()
> <doctest test.test_pdb.test_pdb_return_command_for_coroutine[2]>(3)test_main()
-> await test_coro()
(Pdb) step
--Call--
> <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(1)test_coro()
-> async def test_coro():
(Pdb) step
> <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(2)test_coro()
-> await asyncio.sleep(0)
(Pdb) next
> <doctest test.test_pdb.test_pdb_return_command_for_coroutine[1]>(3)test_coro()
-> await asyncio.sleep(0)
(Pdb) continue
finished
"""
def test_pdb_until_command_for_coroutine():
"""Testing no unwindng stack for coroutines
for "until" command if target breakpoing is not reached
>>> import asyncio
>>> async def test_coro():
... print(0)
... await asyncio.sleep(0)
... print(1)
... await asyncio.sleep(0)
... print(2)
... await asyncio.sleep(0)
... print(3)
>>> async def test_main():
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... await test_coro()
>>> def test_function():
... loop = asyncio.new_event_loop()
... loop.run_until_complete(test_main())
... loop.close()
... print("finished")
>>> with PdbTestInput(['step',
... 'until 8',
... 'continue']):
... test_function()
> <doctest test.test_pdb.test_pdb_until_command_for_coroutine[2]>(3)test_main()
-> await test_coro()
(Pdb) step
--Call--
> <doctest test.test_pdb.test_pdb_until_command_for_coroutine[1]>(1)test_coro()
-> async def test_coro():
(Pdb) until 8
0
1
2
> <doctest test.test_pdb.test_pdb_until_command_for_coroutine[1]>(8)test_coro()
-> print(3)
(Pdb) continue
3
finished
"""
def test_pdb_return_command_for_generator():
"""Testing no unwindng stack on yield for generators
for "return" command
>>> def test_gen():
... yield 0
... return 1
... yield 2
>>> def test_function():
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... it = test_gen()
... try:
... if next(it) != 0:
... raise AssertionError
... next(it)
... except StopIteration as ex:
... if ex.value != 1:
... raise AssertionError
... print("finished")
>>> with PdbTestInput(['step',
... 'step',
... 'step',
... 'return',
... 'step',
... 'step',
... 'continue']):
... test_function()
> <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(3)test_function()
-> it = test_gen()
(Pdb) step
> <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(4)test_function()
-> try:
(Pdb) step
> <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(5)test_function()
-> if next(it) != 0:
(Pdb) step
--Call--
> <doctest test.test_pdb.test_pdb_return_command_for_generator[0]>(1)test_gen()
-> def test_gen():
(Pdb) return
StopIteration: 1
> <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(7)test_function()
-> next(it)
(Pdb) step
> <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(8)test_function()
-> except StopIteration as ex:
(Pdb) step
> <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(9)test_function()
-> if ex.value != 1:
(Pdb) continue
finished
"""
def test_pdb_until_command_for_generator():
"""Testing no unwindng stack on yield for generators
for "until" command if target breakpoing is not reached
>>> def test_gen():
... yield 0
... yield 1
... yield 2
>>> def test_function():
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... for i in test_gen():
... print(i)
... print("finished")
>>> with PdbTestInput(['step',
... 'until 4',
... 'step',
... 'step',
... 'continue']):
... test_function()
> <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(3)test_function()
-> for i in test_gen():
(Pdb) step
--Call--
> <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(1)test_gen()
-> def test_gen():
(Pdb) until 4
0
1
> <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen()
-> yield 2
(Pdb) step
--Return--
> <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen()->2
-> yield 2
(Pdb) step
> <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(4)test_function()
-> print(i)
(Pdb) continue
2
finished
"""
def test_pdb_next_command_in_generator_for_loop():
"""The next command on returning from a generator controlled by a for loop.
>>> def test_gen():
... yield 0
... return 1
>>> def test_function():
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... for i in test_gen():
... print('value', i)
... x = 123
>>> with PdbTestInput(['break test_gen',
... 'continue',
... 'next',
... 'next',
... 'next',
... 'continue']):
... test_function()
> <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function()
-> for i in test_gen():
(Pdb) break test_gen
Breakpoint 6 at <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>:1
(Pdb) continue
> <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(2)test_gen()
-> yield 0
(Pdb) next
value 0
> <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(3)test_gen()
-> return 1
(Pdb) next
Internal StopIteration: 1
> <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function()
-> for i in test_gen():
(Pdb) next
> <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(5)test_function()
-> x = 123
(Pdb) continue
"""
def test_pdb_next_command_subiterator():
"""The next command in a generator with a subiterator.
>>> def test_subgenerator():
... yield 0
... return 1
>>> def test_gen():
... x = yield from test_subgenerator()
... return x
>>> def test_function():
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... for i in test_gen():
... print('value', i)
... x = 123
>>> with PdbTestInput(['step',
... 'step',
... 'next',
... 'next',
... 'next',
... 'continue']):
... test_function()
> <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
-> for i in test_gen():
(Pdb) step
--Call--
> <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(1)test_gen()
-> def test_gen():
(Pdb) step
> <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(2)test_gen()
-> x = yield from test_subgenerator()
(Pdb) next
value 0
> <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(3)test_gen()
-> return x
(Pdb) next
Internal StopIteration: 1
> <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function()
-> for i in test_gen():
(Pdb) next
> <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(5)test_function()
-> x = 123
(Pdb) continue
"""
def test_pdb_issue_20766():
"""Test for reference leaks when the SIGINT handler is set.
>>> def test_function():
... i = 1
... while i <= 2:
... sess = pdb.Pdb()
... sess.set_trace(sys._getframe())
... print('pdb %d: %s' % (i, sess._previous_sigint_handler))
... i += 1
>>> with PdbTestInput(['continue',
... 'continue']):
... test_function()
> <doctest test.test_pdb.test_pdb_issue_20766[0]>(6)test_function()
-> print('pdb %d: %s' % (i, sess._previous_sigint_handler))
(Pdb) continue
pdb 1: <built-in function default_int_handler>
> <doctest test.test_pdb.test_pdb_issue_20766[0]>(5)test_function()
-> sess.set_trace(sys._getframe())
(Pdb) continue
pdb 2: <built-in function default_int_handler>
"""
class PdbTestCase(unittest.TestCase):
def run_pdb(self, script, commands):
"""Run 'script' lines with pdb and the pdb 'commands'."""
filename = 'main.py'
with open(filename, 'w') as f:
f.write(textwrap.dedent(script))
self.addCleanup(support.unlink, filename)
self.addCleanup(support.rmtree, '__pycache__')
cmd = [sys.executable, '-m', 'pdb', filename]
stdout = stderr = None
with subprocess.Popen(cmd, stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.STDOUT,
) as proc:
stdout, stderr = proc.communicate(str.encode(commands))
stdout = stdout and bytes.decode(stdout)
stderr = stderr and bytes.decode(stderr)
return stdout, stderr
def _assert_find_function(self, file_content, func_name, expected):
file_content = textwrap.dedent(file_content)
with open(support.TESTFN, 'w') as f:
f.write(file_content)
expected = None if not expected else (
expected[0], support.TESTFN, expected[1])
self.assertEqual(
expected, pdb.find_function(func_name, support.TESTFN))
def test_find_function_empty_file(self):
self._assert_find_function('', 'foo', None)
def test_find_function_found(self):
self._assert_find_function(
"""\
def foo():
pass
def bar():
pass
def quux():
pass
""",
'bar',
('bar', 4),
)
def test_issue7964(self):
# open the file as binary so we can force \r\n newline
with open(support.TESTFN, 'wb') as f:
f.write(b'print("testing my pdb")\r\n')
cmd = [sys.executable, '-m', 'pdb', support.TESTFN]
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
self.addCleanup(proc.stdout.close)
stdout, stderr = proc.communicate(b'quit\n')
self.assertNotIn(b'SyntaxError', stdout,
"Got a syntax error running test script under PDB")
def test_issue13183(self):
script = """
from bar import bar
def foo():
bar()
def nope():
pass
def foobar():
foo()
nope()
foobar()
"""
commands = """
from bar import bar
break bar
continue
step
step
quit
"""
bar = """
def bar():
pass
"""
with open('bar.py', 'w') as f:
f.write(textwrap.dedent(bar))
self.addCleanup(support.unlink, 'bar.py')
stdout, stderr = self.run_pdb(script, commands)
self.assertTrue(
any('main.py(5)foo()->None' in l for l in stdout.splitlines()),
'Fail to step into the caller after a return')
def test_issue13210(self):
# invoking "continue" on a non-main thread triggered an exception
# inside signal.signal
# raises SkipTest if python was built without threads
support.import_module('threading')
with open(support.TESTFN, 'wb') as f:
f.write(textwrap.dedent("""
import threading
import pdb
def start_pdb():
pdb.Pdb(readrc=False).set_trace()
x = 1
y = 1
t = threading.Thread(target=start_pdb)
t.start()""").encode('ascii'))
cmd = [sys.executable, '-u', support.TESTFN]
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
self.addCleanup(proc.stdout.close)
stdout, stderr = proc.communicate(b'cont\n')
self.assertNotIn('Error', stdout.decode(),
"Got an error running test script under PDB")
def test_issue16180(self):
# A syntax error in the debuggee.
script = "def f: pass\n"
commands = ''
expected = "SyntaxError:"
stdout, stderr = self.run_pdb(script, commands)
self.assertIn(expected, stdout,
'\n\nExpected:\n{}\nGot:\n{}\n'
'Fail to handle a syntax error in the debuggee.'
.format(expected, stdout))
def test_readrc_kwarg(self):
script = textwrap.dedent("""
import pdb; pdb.Pdb(readrc=False).set_trace()
print('hello')
""")
save_home = os.environ.pop('HOME', None)
try:
with support.temp_cwd():
with open('.pdbrc', 'w') as f:
f.write("invalid\n")
with open('main.py', 'w') as f:
f.write(script)
cmd = [sys.executable, 'main.py']
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
)
with proc:
stdout, stderr = proc.communicate(b'q\n')
self.assertNotIn("NameError: name 'invalid' is not defined",
stdout.decode())
finally:
if save_home is not None:
os.environ['HOME'] = save_home
def tearDown(self):
support.unlink(support.TESTFN)
def load_tests(*args):
from test import test_pdb
suites = [unittest.makeSuite(PdbTestCase), doctest.DocTestSuite(test_pdb)]
return unittest.TestSuite(suites)
if __name__ == '__main__':
unittest.main()
| 43,058 | 1,330 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_weakset.py | import unittest
from weakref import WeakSet
import string
from collections import UserString as ustr
import gc
import contextlib
class Foo:
pass
class RefCycle:
def __init__(self):
self.cycle = self
class TestWeakSet(unittest.TestCase):
def setUp(self):
# need to keep references to them
self.items = [ustr(c) for c in ('a', 'b', 'c')]
self.items2 = [ustr(c) for c in ('x', 'y', 'z')]
self.ab_items = [ustr(c) for c in 'ab']
self.abcde_items = [ustr(c) for c in 'abcde']
self.def_items = [ustr(c) for c in 'def']
self.ab_weakset = WeakSet(self.ab_items)
self.abcde_weakset = WeakSet(self.abcde_items)
self.def_weakset = WeakSet(self.def_items)
self.letters = [ustr(c) for c in string.ascii_letters]
self.s = WeakSet(self.items)
self.d = dict.fromkeys(self.items)
self.obj = ustr('F')
self.fs = WeakSet([self.obj])
def test_methods(self):
weaksetmethods = dir(WeakSet)
for method in dir(set):
if method == 'test_c_api' or method.startswith('_'):
continue
self.assertIn(method, weaksetmethods,
"WeakSet missing method " + method)
def test_new_or_init(self):
self.assertRaises(TypeError, WeakSet, [], 2)
def test_len(self):
self.assertEqual(len(self.s), len(self.d))
self.assertEqual(len(self.fs), 1)
del self.obj
self.assertEqual(len(self.fs), 0)
def test_contains(self):
for c in self.letters:
self.assertEqual(c in self.s, c in self.d)
# 1 is not weakref'able, but that TypeError is caught by __contains__
self.assertNotIn(1, self.s)
self.assertIn(self.obj, self.fs)
del self.obj
self.assertNotIn(ustr('F'), self.fs)
def test_union(self):
u = self.s.union(self.items2)
for c in self.letters:
self.assertEqual(c in u, c in self.d or c in self.items2)
self.assertEqual(self.s, WeakSet(self.items))
self.assertEqual(type(u), WeakSet)
self.assertRaises(TypeError, self.s.union, [[]])
for C in set, frozenset, dict.fromkeys, list, tuple:
x = WeakSet(self.items + self.items2)
c = C(self.items2)
self.assertEqual(self.s.union(c), x)
del c
self.assertEqual(len(u), len(self.items) + len(self.items2))
self.items2.pop()
gc.collect()
self.assertEqual(len(u), len(self.items) + len(self.items2))
def test_or(self):
i = self.s.union(self.items2)
self.assertEqual(self.s | set(self.items2), i)
self.assertEqual(self.s | frozenset(self.items2), i)
def test_intersection(self):
s = WeakSet(self.letters)
i = s.intersection(self.items2)
for c in self.letters:
self.assertEqual(c in i, c in self.items2 and c in self.letters)
self.assertEqual(s, WeakSet(self.letters))
self.assertEqual(type(i), WeakSet)
for C in set, frozenset, dict.fromkeys, list, tuple:
x = WeakSet([])
self.assertEqual(i.intersection(C(self.items)), x)
self.assertEqual(len(i), len(self.items2))
self.items2.pop()
gc.collect()
self.assertEqual(len(i), len(self.items2))
def test_isdisjoint(self):
self.assertTrue(self.s.isdisjoint(WeakSet(self.items2)))
self.assertTrue(not self.s.isdisjoint(WeakSet(self.letters)))
def test_and(self):
i = self.s.intersection(self.items2)
self.assertEqual(self.s & set(self.items2), i)
self.assertEqual(self.s & frozenset(self.items2), i)
def test_difference(self):
i = self.s.difference(self.items2)
for c in self.letters:
self.assertEqual(c in i, c in self.d and c not in self.items2)
self.assertEqual(self.s, WeakSet(self.items))
self.assertEqual(type(i), WeakSet)
self.assertRaises(TypeError, self.s.difference, [[]])
def test_sub(self):
i = self.s.difference(self.items2)
self.assertEqual(self.s - set(self.items2), i)
self.assertEqual(self.s - frozenset(self.items2), i)
def test_symmetric_difference(self):
i = self.s.symmetric_difference(self.items2)
for c in self.letters:
self.assertEqual(c in i, (c in self.d) ^ (c in self.items2))
self.assertEqual(self.s, WeakSet(self.items))
self.assertEqual(type(i), WeakSet)
self.assertRaises(TypeError, self.s.symmetric_difference, [[]])
self.assertEqual(len(i), len(self.items) + len(self.items2))
self.items2.pop()
gc.collect()
self.assertEqual(len(i), len(self.items) + len(self.items2))
def test_xor(self):
i = self.s.symmetric_difference(self.items2)
self.assertEqual(self.s ^ set(self.items2), i)
self.assertEqual(self.s ^ frozenset(self.items2), i)
def test_sub_and_super(self):
self.assertTrue(self.ab_weakset <= self.abcde_weakset)
self.assertTrue(self.abcde_weakset <= self.abcde_weakset)
self.assertTrue(self.abcde_weakset >= self.ab_weakset)
self.assertFalse(self.abcde_weakset <= self.def_weakset)
self.assertFalse(self.abcde_weakset >= self.def_weakset)
self.assertTrue(set('a').issubset('abc'))
self.assertTrue(set('abc').issuperset('a'))
self.assertFalse(set('a').issubset('cbs'))
self.assertFalse(set('cbs').issuperset('a'))
def test_lt(self):
self.assertTrue(self.ab_weakset < self.abcde_weakset)
self.assertFalse(self.abcde_weakset < self.def_weakset)
self.assertFalse(self.ab_weakset < self.ab_weakset)
self.assertFalse(WeakSet() < WeakSet())
def test_gt(self):
self.assertTrue(self.abcde_weakset > self.ab_weakset)
self.assertFalse(self.abcde_weakset > self.def_weakset)
self.assertFalse(self.ab_weakset > self.ab_weakset)
self.assertFalse(WeakSet() > WeakSet())
def test_gc(self):
# Create a nest of cycles to exercise overall ref count check
s = WeakSet(Foo() for i in range(1000))
for elem in s:
elem.cycle = s
elem.sub = elem
elem.set = WeakSet([elem])
def test_subclass_with_custom_hash(self):
# Bug #1257731
class H(WeakSet):
def __hash__(self):
return int(id(self) & 0x7fffffff)
s=H()
f=set()
f.add(s)
self.assertIn(s, f)
f.remove(s)
f.add(s)
f.discard(s)
def test_init(self):
s = WeakSet()
s.__init__(self.items)
self.assertEqual(s, self.s)
s.__init__(self.items2)
self.assertEqual(s, WeakSet(self.items2))
self.assertRaises(TypeError, s.__init__, s, 2);
self.assertRaises(TypeError, s.__init__, 1);
def test_constructor_identity(self):
s = WeakSet(self.items)
t = WeakSet(s)
self.assertNotEqual(id(s), id(t))
def test_hash(self):
self.assertRaises(TypeError, hash, self.s)
def test_clear(self):
self.s.clear()
self.assertEqual(self.s, WeakSet([]))
self.assertEqual(len(self.s), 0)
def test_copy(self):
dup = self.s.copy()
self.assertEqual(self.s, dup)
self.assertNotEqual(id(self.s), id(dup))
def test_add(self):
x = ustr('Q')
self.s.add(x)
self.assertIn(x, self.s)
dup = self.s.copy()
self.s.add(x)
self.assertEqual(self.s, dup)
self.assertRaises(TypeError, self.s.add, [])
self.fs.add(Foo())
self.assertTrue(len(self.fs) == 1)
self.fs.add(self.obj)
self.assertTrue(len(self.fs) == 1)
def test_remove(self):
x = ustr('a')
self.s.remove(x)
self.assertNotIn(x, self.s)
self.assertRaises(KeyError, self.s.remove, x)
self.assertRaises(TypeError, self.s.remove, [])
def test_discard(self):
a, q = ustr('a'), ustr('Q')
self.s.discard(a)
self.assertNotIn(a, self.s)
self.s.discard(q)
self.assertRaises(TypeError, self.s.discard, [])
def test_pop(self):
for i in range(len(self.s)):
elem = self.s.pop()
self.assertNotIn(elem, self.s)
self.assertRaises(KeyError, self.s.pop)
def test_update(self):
retval = self.s.update(self.items2)
self.assertEqual(retval, None)
for c in (self.items + self.items2):
self.assertIn(c, self.s)
self.assertRaises(TypeError, self.s.update, [[]])
def test_update_set(self):
self.s.update(set(self.items2))
for c in (self.items + self.items2):
self.assertIn(c, self.s)
def test_ior(self):
self.s |= set(self.items2)
for c in (self.items + self.items2):
self.assertIn(c, self.s)
def test_intersection_update(self):
retval = self.s.intersection_update(self.items2)
self.assertEqual(retval, None)
for c in (self.items + self.items2):
if c in self.items2 and c in self.items:
self.assertIn(c, self.s)
else:
self.assertNotIn(c, self.s)
self.assertRaises(TypeError, self.s.intersection_update, [[]])
def test_iand(self):
self.s &= set(self.items2)
for c in (self.items + self.items2):
if c in self.items2 and c in self.items:
self.assertIn(c, self.s)
else:
self.assertNotIn(c, self.s)
def test_difference_update(self):
retval = self.s.difference_update(self.items2)
self.assertEqual(retval, None)
for c in (self.items + self.items2):
if c in self.items and c not in self.items2:
self.assertIn(c, self.s)
else:
self.assertNotIn(c, self.s)
self.assertRaises(TypeError, self.s.difference_update, [[]])
self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]])
def test_isub(self):
self.s -= set(self.items2)
for c in (self.items + self.items2):
if c in self.items and c not in self.items2:
self.assertIn(c, self.s)
else:
self.assertNotIn(c, self.s)
def test_symmetric_difference_update(self):
retval = self.s.symmetric_difference_update(self.items2)
self.assertEqual(retval, None)
for c in (self.items + self.items2):
if (c in self.items) ^ (c in self.items2):
self.assertIn(c, self.s)
else:
self.assertNotIn(c, self.s)
self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]])
def test_ixor(self):
self.s ^= set(self.items2)
for c in (self.items + self.items2):
if (c in self.items) ^ (c in self.items2):
self.assertIn(c, self.s)
else:
self.assertNotIn(c, self.s)
def test_inplace_on_self(self):
t = self.s.copy()
t |= t
self.assertEqual(t, self.s)
t &= t
self.assertEqual(t, self.s)
t -= t
self.assertEqual(t, WeakSet())
t = self.s.copy()
t ^= t
self.assertEqual(t, WeakSet())
def test_eq(self):
# issue 5964
self.assertTrue(self.s == self.s)
self.assertTrue(self.s == WeakSet(self.items))
self.assertFalse(self.s == set(self.items))
self.assertFalse(self.s == list(self.items))
self.assertFalse(self.s == tuple(self.items))
self.assertFalse(self.s == WeakSet([Foo]))
self.assertFalse(self.s == 1)
def test_ne(self):
self.assertTrue(self.s != set(self.items))
s1 = WeakSet()
s2 = WeakSet()
self.assertFalse(s1 != s2)
def test_weak_destroy_while_iterating(self):
# Issue #7105: iterators shouldn't crash when a key is implicitly removed
# Create new items to be sure no-one else holds a reference
items = [ustr(c) for c in ('a', 'b', 'c')]
s = WeakSet(items)
it = iter(s)
next(it) # Trigger internal iteration
# Destroy an item
del items[-1]
gc.collect() # just in case
# We have removed either the first consumed items, or another one
self.assertIn(len(list(it)), [len(items), len(items) - 1])
del it
# The removal has been committed
self.assertEqual(len(s), len(items))
def test_weak_destroy_and_mutate_while_iterating(self):
# Issue #7105: iterators shouldn't crash when a key is implicitly removed
items = [ustr(c) for c in string.ascii_letters]
s = WeakSet(items)
@contextlib.contextmanager
def testcontext():
try:
it = iter(s)
# Start iterator
yielded = ustr(str(next(it)))
# Schedule an item for removal and recreate it
u = ustr(str(items.pop()))
if yielded == u:
# The iterator still has a reference to the removed item,
# advance it (issue #20006).
next(it)
gc.collect() # just in case
yield u
finally:
it = None # should commit all removals
with testcontext() as u:
self.assertNotIn(u, s)
with testcontext() as u:
self.assertRaises(KeyError, s.remove, u)
self.assertNotIn(u, s)
with testcontext() as u:
s.add(u)
self.assertIn(u, s)
t = s.copy()
with testcontext() as u:
s.update(t)
self.assertEqual(len(s), len(t))
with testcontext() as u:
s.clear()
self.assertEqual(len(s), 0)
def test_len_cycles(self):
N = 20
items = [RefCycle() for i in range(N)]
s = WeakSet(items)
del items
it = iter(s)
try:
next(it)
except StopIteration:
pass
gc.collect()
n1 = len(s)
del it
gc.collect()
n2 = len(s)
# one item may be kept alive inside the iterator
self.assertIn(n1, (0, 1))
self.assertEqual(n2, 0)
def test_len_race(self):
# Extended sanity checks for len() in the face of cyclic collection
self.addCleanup(gc.set_threshold, *gc.get_threshold())
for th in range(1, 100):
N = 20
gc.collect(0)
gc.set_threshold(th, th, th)
items = [RefCycle() for i in range(N)]
s = WeakSet(items)
del items
# All items will be collected at next garbage collection pass
it = iter(s)
try:
next(it)
except StopIteration:
pass
n1 = len(s)
del it
n2 = len(s)
self.assertGreaterEqual(n1, 0)
self.assertLessEqual(n1, N)
self.assertGreaterEqual(n2, 0)
self.assertLessEqual(n2, n1)
if __name__ == "__main__":
unittest.main()
| 15,311 | 440 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/tokenize_tests-utf8-coding-cookie-and-no-utf8-bom-sig.txt | # -*- coding: utf-8 -*-
# IMPORTANT: unlike the other test_tokenize-*.txt files, this file
# does NOT have the utf-8 BOM signature '\xef\xbb\xbf' at the start
# of it. Make sure this is not added inadvertently by your editor
# if any changes are made to this file!
# Arbitrary encoded utf-8 text (stolen from test_doctest2.py).
x = 'ÐÐÐÐÐ'
def y():
"""
And again in a comment. ÐÐÐÐÐ
"""
pass
| 421 | 14 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/dis_module.py |
# A simple module for testing the dis module.
def f(): pass
def g(): pass
| 76 | 6 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_doctest4.txt | This is a sample doctest in a text file that contains non-ASCII characters.
This file is encoded using UTF-8.
In order to get this test to pass, we have to manually specify the
encoding.
>>> 'föö'
'f\xf6\xf6'
>>> 'bÄ
r'
'b\u0105r'
| 244 | 12 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_userstring.py | # UserString is a wrapper around the native builtin string type.
# UserString instances should behave similar to builtin string objects.
import unittest
from test import string_tests
from collections import UserString
class UserStringTest(
string_tests.CommonTest,
string_tests.MixinStrUnicodeUserStringTest,
unittest.TestCase
):
type2test = UserString
# Overwrite the three testing methods, because UserString
# can't cope with arguments propagated to UserString
# (and we don't test with subclasses)
def checkequal(self, result, object, methodname, *args, **kwargs):
result = self.fixtype(result)
object = self.fixtype(object)
# we don't fix the arguments, because UserString can't cope with it
realresult = getattr(object, methodname)(*args, **kwargs)
self.assertEqual(
result,
realresult
)
def checkraises(self, exc, obj, methodname, *args):
obj = self.fixtype(obj)
# we don't fix the arguments, because UserString can't cope with it
with self.assertRaises(exc) as cm:
getattr(obj, methodname)(*args)
self.assertNotEqual(str(cm.exception), '')
def checkcall(self, object, methodname, *args):
object = self.fixtype(object)
# we don't fix the arguments, because UserString can't cope with it
getattr(object, methodname)(*args)
if __name__ == "__main__":
unittest.main()
| 1,469 | 45 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_iterlen.py | """ Test Iterator Length Transparency
Some functions or methods which accept general iterable arguments have
optional, more efficient code paths if they know how many items to expect.
For instance, map(func, iterable), will pre-allocate the exact amount of
space required whenever the iterable can report its length.
The desired invariant is: len(it)==len(list(it)).
A complication is that an iterable and iterator can be the same object. To
maintain the invariant, an iterator needs to dynamically update its length.
For instance, an iterable such as range(10) always reports its length as ten,
but it=iter(range(10)) starts at ten, and then goes to nine after next(it).
Having this capability means that map() can ignore the distinction between
map(func, iterable) and map(func, iter(iterable)).
When the iterable is immutable, the implementation can straight-forwardly
report the original length minus the cumulative number of calls to next().
This is the case for tuples, range objects, and itertools.repeat().
Some containers become temporarily immutable during iteration. This includes
dicts, sets, and collections.deque. Their implementation is equally simple
though they need to permanently set their length to zero whenever there is
an attempt to iterate after a length mutation.
The situation slightly more involved whenever an object allows length mutation
during iteration. Lists and sequence iterators are dynamically updatable.
So, if a list is extended during iteration, the iterator will continue through
the new items. If it shrinks to a point before the most recent iteration,
then no further items are available and the length is reported at zero.
Reversed objects can also be wrapped around mutable objects; however, any
appends after the current position are ignored. Any other approach leads
to confusion and possibly returning the same item more than once.
The iterators not listed above, such as enumerate and the other itertools,
are not length transparent because they have no way to distinguish between
iterables that report static length and iterators whose length changes with
each call (i.e. the difference between enumerate('abc') and
enumerate(iter('abc')).
"""
import unittest
from itertools import repeat
from collections import deque
from operator import length_hint
n = 10
class TestInvariantWithoutMutations:
def test_invariant(self):
it = self.it
for i in reversed(range(1, n+1)):
self.assertEqual(length_hint(it), i)
next(it)
self.assertEqual(length_hint(it), 0)
self.assertRaises(StopIteration, next, it)
self.assertEqual(length_hint(it), 0)
class TestTemporarilyImmutable(TestInvariantWithoutMutations):
def test_immutable_during_iteration(self):
# objects such as deques, sets, and dictionaries enforce
# length immutability during iteration
it = self.it
self.assertEqual(length_hint(it), n)
next(it)
self.assertEqual(length_hint(it), n-1)
self.mutate()
self.assertRaises(RuntimeError, next, it)
self.assertEqual(length_hint(it), 0)
## ------- Concrete Type Tests -------
class TestRepeat(TestInvariantWithoutMutations, unittest.TestCase):
def setUp(self):
self.it = repeat(None, n)
class TestXrange(TestInvariantWithoutMutations, unittest.TestCase):
def setUp(self):
self.it = iter(range(n))
class TestXrangeCustomReversed(TestInvariantWithoutMutations, unittest.TestCase):
def setUp(self):
self.it = reversed(range(n))
class TestTuple(TestInvariantWithoutMutations, unittest.TestCase):
def setUp(self):
self.it = iter(tuple(range(n)))
## ------- Types that should not be mutated during iteration -------
class TestDeque(TestTemporarilyImmutable, unittest.TestCase):
def setUp(self):
d = deque(range(n))
self.it = iter(d)
self.mutate = d.pop
class TestDequeReversed(TestTemporarilyImmutable, unittest.TestCase):
def setUp(self):
d = deque(range(n))
self.it = reversed(d)
self.mutate = d.pop
class TestDictKeys(TestTemporarilyImmutable, unittest.TestCase):
def setUp(self):
d = dict.fromkeys(range(n))
self.it = iter(d)
self.mutate = d.popitem
class TestDictItems(TestTemporarilyImmutable, unittest.TestCase):
def setUp(self):
d = dict.fromkeys(range(n))
self.it = iter(d.items())
self.mutate = d.popitem
class TestDictValues(TestTemporarilyImmutable, unittest.TestCase):
def setUp(self):
d = dict.fromkeys(range(n))
self.it = iter(d.values())
self.mutate = d.popitem
class TestSet(TestTemporarilyImmutable, unittest.TestCase):
def setUp(self):
d = set(range(n))
self.it = iter(d)
self.mutate = d.pop
## ------- Types that can mutate during iteration -------
class TestList(TestInvariantWithoutMutations, unittest.TestCase):
def setUp(self):
self.it = iter(range(n))
def test_mutation(self):
d = list(range(n))
it = iter(d)
next(it)
next(it)
self.assertEqual(length_hint(it), n - 2)
d.append(n)
self.assertEqual(length_hint(it), n - 1) # grow with append
d[1:] = []
self.assertEqual(length_hint(it), 0)
self.assertEqual(list(it), [])
d.extend(range(20))
self.assertEqual(length_hint(it), 0)
class TestListReversed(TestInvariantWithoutMutations, unittest.TestCase):
def setUp(self):
self.it = reversed(range(n))
def test_mutation(self):
d = list(range(n))
it = reversed(d)
next(it)
next(it)
self.assertEqual(length_hint(it), n - 2)
d.append(n)
self.assertEqual(length_hint(it), n - 2) # ignore append
d[1:] = []
self.assertEqual(length_hint(it), 0)
self.assertEqual(list(it), []) # confirm invariant
d.extend(range(20))
self.assertEqual(length_hint(it), 0)
## -- Check to make sure exceptions are not suppressed by __length_hint__()
class BadLen(object):
def __iter__(self):
return iter(range(10))
def __len__(self):
raise RuntimeError('hello')
class BadLengthHint(object):
def __iter__(self):
return iter(range(10))
def __length_hint__(self):
raise RuntimeError('hello')
class NoneLengthHint(object):
def __iter__(self):
return iter(range(10))
def __length_hint__(self):
return NotImplemented
class TestLengthHintExceptions(unittest.TestCase):
def test_issue1242657(self):
self.assertRaises(RuntimeError, list, BadLen())
self.assertRaises(RuntimeError, list, BadLengthHint())
self.assertRaises(RuntimeError, [].extend, BadLen())
self.assertRaises(RuntimeError, [].extend, BadLengthHint())
b = bytearray(range(10))
self.assertRaises(RuntimeError, b.extend, BadLen())
self.assertRaises(RuntimeError, b.extend, BadLengthHint())
def test_invalid_hint(self):
# Make sure an invalid result doesn't muck-up the works
self.assertEqual(list(NoneLengthHint()), list(range(10)))
if __name__ == "__main__":
unittest.main()
| 7,266 | 229 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/ssl_servers.py | import os
import sys
import ssl
import pprint
import socket
import urllib.parse
# Rename HTTPServer to _HTTPServer so as to avoid confusion with HTTPSServer.
from http.server import (HTTPServer as _HTTPServer,
SimpleHTTPRequestHandler, BaseHTTPRequestHandler)
from test import support
threading = support.import_module("threading")
here = os.path.dirname(__file__)
HOST = support.HOST
CERTFILE = os.path.join(here, 'keycert.pem')
# This one's based on HTTPServer, which is based on socketserver
class HTTPSServer(_HTTPServer):
def __init__(self, server_address, handler_class, context):
_HTTPServer.__init__(self, server_address, handler_class)
self.context = context
def __str__(self):
return ('<%s %s:%s>' %
(self.__class__.__name__,
self.server_name,
self.server_port))
def get_request(self):
# override this to wrap socket with SSL
try:
sock, addr = self.socket.accept()
sslconn = self.context.wrap_socket(sock, server_side=True)
except OSError as e:
# socket errors are silenced by the caller, print them here
if support.verbose:
sys.stderr.write("Got an error:\n%s\n" % e)
raise
return sslconn, addr
class RootedHTTPRequestHandler(SimpleHTTPRequestHandler):
# need to override translate_path to get a known root,
# instead of using os.curdir, since the test could be
# run from anywhere
server_version = "TestHTTPS/1.0"
root = here
# Avoid hanging when a request gets interrupted by the client
timeout = 5
def translate_path(self, path):
"""Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
"""
# abandon query parameters
path = urllib.parse.urlparse(path)[2]
path = os.path.normpath(urllib.parse.unquote(path))
words = path.split('/')
words = filter(None, words)
path = self.root
for word in words:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
path = os.path.join(path, word)
return path
def log_message(self, format, *args):
# we override this to suppress logging unless "verbose"
if support.verbose:
sys.stdout.write(" server (%s:%d %s):\n [%s] %s\n" %
(self.server.server_address,
self.server.server_port,
self.request.cipher(),
self.log_date_time_string(),
format%args))
class StatsRequestHandler(BaseHTTPRequestHandler):
"""Example HTTP request handler which returns SSL statistics on GET
requests.
"""
server_version = "StatsHTTPS/1.0"
def do_GET(self, send_body=True):
"""Serve a GET request."""
sock = self.rfile.raw._sock
context = sock.context
stats = {
'session_cache': context.session_stats(),
'cipher': sock.cipher(),
'compression': sock.compression(),
}
body = pprint.pformat(stats)
body = body.encode('utf-8')
self.send_response(200)
self.send_header("Content-type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
if send_body:
self.wfile.write(body)
def do_HEAD(self):
"""Serve a HEAD request."""
self.do_GET(send_body=False)
def log_request(self, format, *args):
if support.verbose:
BaseHTTPRequestHandler.log_request(self, format, *args)
class HTTPSServerThread(threading.Thread):
def __init__(self, context, host=HOST, handler_class=None):
self.flag = None
self.server = HTTPSServer((host, 0),
handler_class or RootedHTTPRequestHandler,
context)
self.port = self.server.server_port
threading.Thread.__init__(self)
self.daemon = True
def __str__(self):
return "<%s %s>" % (self.__class__.__name__, self.server)
def start(self, flag=None):
self.flag = flag
threading.Thread.start(self)
def run(self):
if self.flag:
self.flag.set()
try:
self.server.serve_forever(0.05)
finally:
self.server.server_close()
def stop(self):
self.server.shutdown()
def make_https_server(case, *, context=None, certfile=CERTFILE,
host=HOST, handler_class=None):
if context is None:
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
# We assume the certfile contains both private key and certificate
context.load_cert_chain(certfile)
server = HTTPSServerThread(context, host, handler_class)
flag = threading.Event()
server.start(flag)
flag.wait()
def cleanup():
if support.verbose:
sys.stdout.write('stopping HTTPS server\n')
server.stop()
if support.verbose:
sys.stdout.write('joining HTTPS thread\n')
server.join()
case.addCleanup(cleanup)
return server
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description='Run a test HTTPS server. '
'By default, the current directory is served.')
parser.add_argument('-p', '--port', type=int, default=4433,
help='port to listen on (default: %(default)s)')
parser.add_argument('-q', '--quiet', dest='verbose', default=True,
action='store_false', help='be less verbose')
parser.add_argument('-s', '--stats', dest='use_stats_handler', default=False,
action='store_true', help='always return stats page')
parser.add_argument('--curve-name', dest='curve_name', type=str,
action='store',
help='curve name for EC-based Diffie-Hellman')
parser.add_argument('--ciphers', dest='ciphers', type=str,
help='allowed cipher list')
parser.add_argument('--dh', dest='dh_file', type=str, action='store',
help='PEM file containing DH parameters')
args = parser.parse_args()
support.verbose = args.verbose
if args.use_stats_handler:
handler_class = StatsRequestHandler
else:
handler_class = RootedHTTPRequestHandler
handler_class.root = os.getcwd()
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(CERTFILE)
if args.curve_name:
context.set_ecdh_curve(args.curve_name)
if args.dh_file:
context.load_dh_params(args.dh_file)
if args.ciphers:
context.set_ciphers(args.ciphers)
server = HTTPSServer(("", args.port), handler_class, context)
if args.verbose:
print("Listening on https://localhost:{0.port}".format(args))
server.serve_forever(0.1)
| 7,255 | 210 | jart/cosmopolitan | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.