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_epoll.py | # Copyright (c) 2001-2006 Twisted Matrix Laboratories.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
Tests for epoll wrapper.
"""
import errno
import os
import select
import socket
import time
import unittest
if not hasattr(select, "epoll"):
raise unittest.SkipTest("test works only on Linux 2.6")
try:
select.epoll()
except OSError as e:
if e.errno == errno.ENOSYS:
raise unittest.SkipTest("kernel doesn't support epoll()")
raise
class TestEPoll(unittest.TestCase):
def setUp(self):
self.serverSocket = socket.socket()
self.serverSocket.bind(('127.0.0.1', 0))
self.serverSocket.listen()
self.connections = [self.serverSocket]
def tearDown(self):
for skt in self.connections:
skt.close()
def _connected_pair(self):
client = socket.socket()
client.setblocking(False)
try:
client.connect(('127.0.0.1', self.serverSocket.getsockname()[1]))
except OSError as e:
self.assertEqual(e.args[0], errno.EINPROGRESS)
else:
raise AssertionError("Connect should have raised EINPROGRESS")
server, addr = self.serverSocket.accept()
self.connections.extend((client, server))
return client, server
def test_create(self):
try:
ep = select.epoll(16)
except OSError as e:
raise AssertionError(str(e))
self.assertTrue(ep.fileno() > 0, ep.fileno())
self.assertTrue(not ep.closed)
ep.close()
self.assertTrue(ep.closed)
self.assertRaises(ValueError, ep.fileno)
if hasattr(select, "EPOLL_CLOEXEC"):
select.epoll(-1, select.EPOLL_CLOEXEC).close()
select.epoll(flags=select.EPOLL_CLOEXEC).close()
select.epoll(flags=0).close()
def test_badcreate(self):
self.assertRaises(TypeError, select.epoll, 1, 2, 3)
self.assertRaises(TypeError, select.epoll, 'foo')
self.assertRaises(TypeError, select.epoll, None)
self.assertRaises(TypeError, select.epoll, ())
self.assertRaises(TypeError, select.epoll, ['foo'])
self.assertRaises(TypeError, select.epoll, {})
self.assertRaises(ValueError, select.epoll, 0)
self.assertRaises(ValueError, select.epoll, -2)
self.assertRaises(ValueError, select.epoll, sizehint=-2)
if hasattr(select, "EPOLL_CLOEXEC"):
self.assertRaises(OSError, select.epoll, flags=12356)
def test_context_manager(self):
with select.epoll(16) as ep:
self.assertGreater(ep.fileno(), 0)
self.assertFalse(ep.closed)
self.assertTrue(ep.closed)
self.assertRaises(ValueError, ep.fileno)
def test_add(self):
server, client = self._connected_pair()
ep = select.epoll(2)
try:
ep.register(server.fileno(), select.EPOLLIN | select.EPOLLOUT)
ep.register(client.fileno(), select.EPOLLIN | select.EPOLLOUT)
finally:
ep.close()
# adding by object w/ fileno works, too.
ep = select.epoll(2)
try:
ep.register(server, select.EPOLLIN | select.EPOLLOUT)
ep.register(client, select.EPOLLIN | select.EPOLLOUT)
finally:
ep.close()
ep = select.epoll(2)
try:
# TypeError: argument must be an int, or have a fileno() method.
self.assertRaises(TypeError, ep.register, object(),
select.EPOLLIN | select.EPOLLOUT)
self.assertRaises(TypeError, ep.register, None,
select.EPOLLIN | select.EPOLLOUT)
# ValueError: file descriptor cannot be a negative integer (-1)
self.assertRaises(ValueError, ep.register, -1,
select.EPOLLIN | select.EPOLLOUT)
# OSError: [Errno 9] Bad file descriptor
self.assertRaises(OSError, ep.register, 10000,
select.EPOLLIN | select.EPOLLOUT)
# registering twice also raises an exception
ep.register(server, select.EPOLLIN | select.EPOLLOUT)
self.assertRaises(OSError, ep.register, server,
select.EPOLLIN | select.EPOLLOUT)
finally:
ep.close()
def test_fromfd(self):
server, client = self._connected_pair()
ep = select.epoll(2)
ep2 = select.epoll.fromfd(ep.fileno())
ep2.register(server.fileno(), select.EPOLLIN | select.EPOLLOUT)
ep2.register(client.fileno(), select.EPOLLIN | select.EPOLLOUT)
events = ep.poll(1, 4)
events2 = ep2.poll(0.9, 4)
self.assertEqual(len(events), 2)
self.assertEqual(len(events2), 2)
ep.close()
try:
ep2.poll(1, 4)
except OSError as e:
self.assertEqual(e.args[0], errno.EBADF, e)
else:
self.fail("epoll on closed fd didn't raise EBADF")
def test_control_and_wait(self):
client, server = self._connected_pair()
ep = select.epoll(16)
ep.register(server.fileno(),
select.EPOLLIN | select.EPOLLOUT | select.EPOLLET)
ep.register(client.fileno(),
select.EPOLLIN | select.EPOLLOUT | select.EPOLLET)
now = time.monotonic()
events = ep.poll(1, 4)
then = time.monotonic()
self.assertFalse(then - now > 0.1, then - now)
events.sort()
expected = [(client.fileno(), select.EPOLLOUT),
(server.fileno(), select.EPOLLOUT)]
expected.sort()
self.assertEqual(events, expected)
events = ep.poll(timeout=2.1, maxevents=4)
self.assertFalse(events)
client.send(b"Hello!")
server.send(b"world!!!")
now = time.monotonic()
events = ep.poll(1, 4)
then = time.monotonic()
self.assertFalse(then - now > 0.01)
events.sort()
expected = [(client.fileno(), select.EPOLLIN | select.EPOLLOUT),
(server.fileno(), select.EPOLLIN | select.EPOLLOUT)]
expected.sort()
self.assertEqual(events, expected)
ep.unregister(client.fileno())
ep.modify(server.fileno(), select.EPOLLOUT)
now = time.monotonic()
events = ep.poll(1, 4)
then = time.monotonic()
self.assertFalse(then - now > 0.01)
expected = [(server.fileno(), select.EPOLLOUT)]
self.assertEqual(events, expected)
def test_errors(self):
self.assertRaises(ValueError, select.epoll, -2)
self.assertRaises(ValueError, select.epoll().register, -1,
select.EPOLLIN)
def test_unregister_closed(self):
server, client = self._connected_pair()
fd = server.fileno()
ep = select.epoll(16)
ep.register(server)
now = time.monotonic()
events = ep.poll(1, 4)
then = time.monotonic()
self.assertFalse(then - now > 0.01)
server.close()
ep.unregister(fd)
def test_close(self):
open_file = open(__file__, "rb")
self.addCleanup(open_file.close)
fd = open_file.fileno()
epoll = select.epoll()
# test fileno() method and closed attribute
self.assertIsInstance(epoll.fileno(), int)
self.assertFalse(epoll.closed)
# test close()
epoll.close()
self.assertTrue(epoll.closed)
self.assertRaises(ValueError, epoll.fileno)
# close() can be called more than once
epoll.close()
# operations must fail with ValueError("I/O operation on closed ...")
self.assertRaises(ValueError, epoll.modify, fd, select.EPOLLIN)
self.assertRaises(ValueError, epoll.poll, 1.0)
self.assertRaises(ValueError, epoll.register, fd, select.EPOLLIN)
self.assertRaises(ValueError, epoll.unregister, fd)
def test_fd_non_inheritable(self):
epoll = select.epoll()
self.addCleanup(epoll.close)
self.assertEqual(os.get_inheritable(epoll.fileno()), False)
if __name__ == "__main__":
unittest.main()
| 9,209 | 265 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_sort.py | from test import support
import random
import unittest
from functools import cmp_to_key
verbose = support.verbose
nerrors = 0
def check(tag, expected, raw, compare=None):
global nerrors
if verbose:
print(" checking", tag)
orig = raw[:] # save input in case of error
if compare:
raw.sort(key=cmp_to_key(compare))
else:
raw.sort()
if len(expected) != len(raw):
print("error in", tag)
print("length mismatch;", len(expected), len(raw))
print(expected)
print(orig)
print(raw)
nerrors += 1
return
for i, good in enumerate(expected):
maybe = raw[i]
if good is not maybe:
print("error in", tag)
print("out of order at index", i, good, maybe)
print(expected)
print(orig)
print(raw)
nerrors += 1
return
class TestBase(unittest.TestCase):
def testStressfully(self):
# Try a variety of sizes at and around powers of 2, and at powers of 10.
sizes = [0]
for power in range(1, 10):
n = 2 ** power
sizes.extend(range(n-1, n+2))
sizes.extend([10, 100, 1000])
class Complains(object):
maybe_complain = True
def __init__(self, i):
self.i = i
def __lt__(self, other):
if Complains.maybe_complain and random.random() < 0.001:
if verbose:
print(" complaining at", self, other)
raise RuntimeError
return self.i < other.i
def __repr__(self):
return "Complains(%d)" % self.i
class Stable(object):
def __init__(self, key, i):
self.key = key
self.index = i
def __lt__(self, other):
return self.key < other.key
def __repr__(self):
return "Stable(%d, %d)" % (self.key, self.index)
for n in sizes:
x = list(range(n))
if verbose:
print("Testing size", n)
s = x[:]
check("identity", x, s)
s = x[:]
s.reverse()
check("reversed", x, s)
s = x[:]
random.shuffle(s)
check("random permutation", x, s)
y = x[:]
y.reverse()
s = x[:]
check("reversed via function", y, s, lambda a, b: (b>a)-(b<a))
if verbose:
print(" Checking against an insane comparison function.")
print(" If the implementation isn't careful, this may segfault.")
s = x[:]
s.sort(key=cmp_to_key(lambda a, b: int(random.random() * 3) - 1))
check("an insane function left some permutation", x, s)
if len(x) >= 2:
def bad_key(x):
raise RuntimeError
s = x[:]
self.assertRaises(RuntimeError, s.sort, key=bad_key)
x = [Complains(i) for i in x]
s = x[:]
random.shuffle(s)
Complains.maybe_complain = True
it_complained = False
try:
s.sort()
except RuntimeError:
it_complained = True
if it_complained:
Complains.maybe_complain = False
check("exception during sort left some permutation", x, s)
s = [Stable(random.randrange(10), i) for i in range(n)]
augmented = [(e, e.index) for e in s]
augmented.sort() # forced stable because ties broken by index
x = [e for e, i in augmented] # a stable sort of s
check("stability", x, s)
#==============================================================================
class TestBugs(unittest.TestCase):
def test_bug453523(self):
# bug 453523 -- list.sort() crasher.
# If this fails, the most likely outcome is a core dump.
# Mutations during a list sort should raise a ValueError.
class C:
def __lt__(self, other):
if L and random.random() < 0.75:
L.pop()
else:
L.append(3)
return random.random() < 0.5
L = [C() for i in range(50)]
self.assertRaises(ValueError, L.sort)
def test_undetected_mutation(self):
# Python 2.4a1 did not always detect mutation
memorywaster = []
for i in range(20):
def mutating_cmp(x, y):
L.append(3)
L.pop()
return (x > y) - (x < y)
L = [1,2]
self.assertRaises(ValueError, L.sort, key=cmp_to_key(mutating_cmp))
def mutating_cmp(x, y):
L.append(3)
del L[:]
return (x > y) - (x < y)
self.assertRaises(ValueError, L.sort, key=cmp_to_key(mutating_cmp))
memorywaster = [memorywaster]
#==============================================================================
class TestDecorateSortUndecorate(unittest.TestCase):
def test_decorated(self):
data = 'The quick Brown fox Jumped over The lazy Dog'.split()
copy = data[:]
random.shuffle(data)
data.sort(key=str.lower)
def my_cmp(x, y):
xlower, ylower = x.lower(), y.lower()
return (xlower > ylower) - (xlower < ylower)
copy.sort(key=cmp_to_key(my_cmp))
def test_baddecorator(self):
data = 'The quick Brown fox Jumped over The lazy Dog'.split()
self.assertRaises(TypeError, data.sort, key=lambda x,y: 0)
def test_stability(self):
data = [(random.randrange(100), i) for i in range(200)]
copy = data[:]
data.sort(key=lambda t: t[0]) # sort on the random first field
copy.sort() # sort using both fields
self.assertEqual(data, copy) # should get the same result
def test_key_with_exception(self):
# Verify that the wrapper has been removed
data = list(range(-2, 2))
dup = data[:]
self.assertRaises(ZeroDivisionError, data.sort, key=lambda x: 1/x)
self.assertEqual(data, dup)
def test_key_with_mutation(self):
data = list(range(10))
def k(x):
del data[:]
data[:] = range(20)
return x
self.assertRaises(ValueError, data.sort, key=k)
def test_key_with_mutating_del(self):
data = list(range(10))
class SortKiller(object):
def __init__(self, x):
pass
def __del__(self):
del data[:]
data[:] = range(20)
def __lt__(self, other):
return id(self) < id(other)
self.assertRaises(ValueError, data.sort, key=SortKiller)
def test_key_with_mutating_del_and_exception(self):
data = list(range(10))
## dup = data[:]
class SortKiller(object):
def __init__(self, x):
if x > 2:
raise RuntimeError
def __del__(self):
del data[:]
data[:] = list(range(20))
self.assertRaises(RuntimeError, data.sort, key=SortKiller)
## major honking subtlety: we *can't* do:
##
## self.assertEqual(data, dup)
##
## because there is a reference to a SortKiller in the
## traceback and by the time it dies we're outside the call to
## .sort() and so the list protection gimmicks are out of
## date (this cost some brain cells to figure out...).
def test_reverse(self):
data = list(range(100))
random.shuffle(data)
data.sort(reverse=True)
self.assertEqual(data, list(range(99,-1,-1)))
def test_reverse_stability(self):
data = [(random.randrange(100), i) for i in range(200)]
copy1 = data[:]
copy2 = data[:]
def my_cmp(x, y):
x0, y0 = x[0], y[0]
return (x0 > y0) - (x0 < y0)
def my_cmp_reversed(x, y):
x0, y0 = x[0], y[0]
return (y0 > x0) - (y0 < x0)
data.sort(key=cmp_to_key(my_cmp), reverse=True)
copy1.sort(key=cmp_to_key(my_cmp_reversed))
self.assertEqual(data, copy1)
copy2.sort(key=lambda x: x[0], reverse=True)
self.assertEqual(data, copy2)
#==============================================================================
if __name__ == "__main__":
unittest.main()
| 8,664 | 266 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/cfgparser.2 | # This is the main Samba configuration file. You should read the
# smb.conf(5) manual page in order to understand the options listed
# here. Samba has a huge number of configurable options (perhaps too
# many!) most of which are not shown in this example
#
# Any line which starts with a ; (semi-colon) or a # (hash)
# is a comment and is ignored. In this example we will use a #
# for commentry and a ; for parts of the config file that you
# may wish to enable
#
# NOTE: Whenever you modify this file you should run the command #"testparm" # to check that you have not made any basic syntactic #errors.
#
#======================= Global Settings =====================================
[global]
# 1. Server Naming Options:
# workgroup = NT-Domain-Name or Workgroup-Name
workgroup = MDKGROUP
# netbios name is the name you will see in "Network Neighbourhood",
# but defaults to your hostname
; netbios name = <name_of_this_server>
# server string is the equivalent of the NT Description field
server string = Samba Server %v
# Message command is run by samba when a "popup" message is sent to it.
# The example below is for use with LinPopUp:
; message command = /usr/bin/linpopup "%f" "%m" %s; rm %s
# 2. Printing Options:
# CHANGES TO ENABLE PRINTING ON ALL CUPS PRINTERS IN THE NETWORK
# (as cups is now used in linux-mandrake 7.2 by default)
# if you want to automatically load your printer list rather
# than setting them up individually then you'll need this
printcap name = lpstat
load printers = yes
# It should not be necessary to spell out the print system type unless
# yours is non-standard. Currently supported print systems include:
# bsd, sysv, plp, lprng, aix, hpux, qnx, cups
printing = cups
# Samba 2.2 supports the Windows NT-style point-and-print feature. To
# use this, you need to be able to upload print drivers to the samba
# server. The printer admins (or root) may install drivers onto samba.
# Note that this feature uses the print$ share, so you will need to
# enable it below.
# This parameter works like domain admin group:
# printer admin = @<group> <user>
; printer admin = @adm
# This should work well for winbind:
; printer admin = @"Domain Admins"
# 3. Logging Options:
# this tells Samba to use a separate log file for each machine
# that connects
log file = /var/log/samba/log.%m
# Put a capping on the size of the log files (in Kb).
max log size = 50
# Set the log (verbosity) level (0 <= log level <= 10)
; log level = 3
# 4. Security and Domain Membership Options:
# This option is important for security. It allows you to restrict
# connections to machines which are on your local network. The
# following example restricts access to two C class networks and
# the "loopback" interface. For more examples of the syntax see
# the smb.conf man page. Do not enable this if (tcp/ip) name resolution #does
# not work for all the hosts in your network.
; hosts allow = 192.168.1. 192.168.2. 127.
hosts allow = 127. //note this is only my private IP address
# Uncomment this if you want a guest account, you must add this to
# /etc/passwd
# otherwise the user "nobody" is used
; guest account = pcguest
# Security mode. Most people will want user level security. See
# security_level.txt for details.
security = user
# Use password server option only with security = server or security = # domain
# When using security = domain, you should use password server = *
; password server =
; password server = *
# Password Level allows matching of _n_ characters of the password for
# all combinations of upper and lower case.
password level = 8
; username level = 8
# You may wish to use password encryption. Please read
# ENCRYPTION.txt, Win95.txt and WinNT.txt in the Samba documentation.
# Do not enable this option unless you have read those documents
# Encrypted passwords are required for any use of samba in a Windows NT #domain
# The smbpasswd file is only required by a server doing authentication, #thus members of a domain do not need one.
encrypt passwords = yes
smb passwd file = /etc/samba/smbpasswd
# The following are needed to allow password changing from Windows to
# also update the Linux system password.
# NOTE: Use these with 'encrypt passwords' and 'smb passwd file' above.
# NOTE2: You do NOT need these to allow workstations to change only
# the encrypted SMB passwords. They allow the Unix password
# to be kept in sync with the SMB password.
; unix password sync = Yes
# You either need to setup a passwd program and passwd chat, or
# enable pam password change
; pam password change = yes
; passwd program = /usr/bin/passwd %u
; passwd chat = *New*UNIX*password* %n\n *ReType*new*UNIX*password*
# %n\n
;*passwd:*all*authentication*tokens*updated*successfully*
# Unix users can map to different SMB User names
; username map = /etc/samba/smbusers
# Using the following line enables you to customize your configuration
# on a per machine basis. The %m gets replaced with the netbios name
# of the machine that is connecting
; include = /etc/samba/smb.conf.%m
# Options for using winbind. Winbind allows you to do all account and
# authentication from a Windows or samba domain controller, creating
# accounts on the fly, and maintaining a mapping of Windows RIDs to
# unix uid's
# and gid's. winbind uid and winbind gid are the only required
# parameters.
#
# winbind uid is the range of uid's winbind can use when mapping RIDs #to uid's
; winbind uid = 10000-20000
#
# winbind gid is the range of uid's winbind can use when mapping RIDs
# to gid's
; winbind gid = 10000-20000
#
# winbind separator is the character a user must use between their
# domain name and username, defaults to "\"
; winbind separator = +
#
# winbind use default domain allows you to have winbind return
# usernames in the form user instead of DOMAIN+user for the domain
# listed in the workgroup parameter.
; winbind use default domain = yes
#
# template homedir determines the home directory for winbind users,
# with %D expanding to their domain name and %U expanding to their
# username:
; template homedir = /home/%D/%U
# When using winbind, you may want to have samba create home
# directories on the fly for authenticated users. Ensure that
# /etc/pam.d/samba is using 'service=system-auth-winbind' in pam_stack
# modules, and then enable obedience of pam restrictions below:
; obey pam restrictions = yes
#
# template shell determines the shell users authenticated by winbind #get
; template shell = /bin/bash
# 5. Browser Control and Networking Options:
# Most people will find that this option gives better performance.
# See speed.txt and the manual pages for details
socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192
# Configure Samba to use multiple interfaces
# If you have multiple network interfaces then you must list them
# here. See the man page for details.
; interfaces = 192.168.12.2/24 192.168.13.2/24
# Configure remote browse list synchronisation here
# request announcement to, or browse list sync from:
# a specific host or from / to a whole subnet (see below)
; remote browse sync = 192.168.3.25 192.168.5.255
# Cause this host to announce itself to local subnets here
; remote announce = 192.168.1.255 192.168.2.44
# set local master to no if you don't want Samba to become a master
# browser on your network. Otherwise the normal election rules apply
; local master = no
# OS Level determines the precedence of this server in master browser
# elections. The default value should be reasonable
; os level = 33
# Domain Master specifies Samba to be the Domain Master Browser. This
# allows Samba to collate browse lists between subnets. Don't use this
# if you already have a Windows NT domain controller doing this job
; domain master = yes
# Preferred Master causes Samba to force a local browser election on
# startup and gives it a slightly higher chance of winning the election
; preferred master = yes
# 6. Domain Control Options:
# Enable this if you want Samba to be a domain logon server for
# Windows95 workstations or Primary Domain Controller for WinNT and
# Win2k
; domain logons = yes
# if you enable domain logons then you may want a per-machine or
# per user logon script
# run a specific logon batch file per workstation (machine)
; logon script = %m.bat
# run a specific logon batch file per username
; logon script = %U.bat
# Where to store roaming profiles for WinNT and Win2k
# %L substitutes for this servers netbios name, %U is username
# You must uncomment the [Profiles] share below
; logon path = \\%L\Profiles\%U
# Where to store roaming profiles for Win9x. Be careful with this as it
# also impacts where Win2k finds it's /HOME share
; logon home = \\%L\%U\.profile
# The add user script is used by a domain member to add local user
# accounts that have been authenticated by the domain controller, or by
# the domain controller to add local machine accounts when adding
# machines to the domain.
# The script must work from the command line when replacing the macros,
# or the operation will fail. Check that groups exist if forcing a
# group.
# Script for domain controller for adding machines:
; add user script = /usr/sbin/useradd -d /dev/null -g machines âc
# 'Machine Account' -s /bin/false -M %u
# Script for domain controller with LDAP backend for adding machines
#(please
# configure in /etc/samba/smbldap_conf.pm first):
; add user script = /usr/share/samba/scripts/smbldap-useradd.pl -w âd
# /dev/null -g machines -c 'Machine Account' -s /bin/false %u
# Script for domain member for adding local accounts for authenticated
# users:
; add user script = /usr/sbin/useradd -s /bin/false %u
# Domain groups:
# domain admin group is a list of unix users or groups who are made
# members
# of the Domain Admin group
; domain admin group = root @wheel
#
# domain guest groups is a list of unix users or groups who are made
# members
# of the Domain Guests group
; domain guest group = nobody @guest
# LDAP configuration for Domain Controlling:
# The account (dn) that samba uses to access the LDAP server
# This account needs to have write access to the LDAP tree
# You will need to give samba the password for this dn, by
# running 'smbpasswd -w mypassword'
; ldap admin dn = cn=root,dc=mydomain,dc=com
; ldap ssl = start_tls
# start_tls should run on 389, but samba defaults incorrectly to 636
; ldap port = 389
; ldap suffix = dc=mydomain,dc=com
; ldap server = ldap.mydomain.com
# 7. Name Resolution Options:
# All NetBIOS names must be resolved to IP Addresses
# 'Name Resolve Order' allows the named resolution mechanism to be
# specified the default order is "host lmhosts wins bcast". "host"
# means use the unix system gethostbyname() function call that will use
# either /etc/hosts OR DNS or NIS depending on the settings of
# /etc/host.config, /etc/nsswitch.conf
# and the /etc/resolv.conf file. "host" therefore is system
# configuration dependent. This parameter is most often of use to
# prevent DNS lookups
# in order to resolve NetBIOS names to IP Addresses. Use with care!
# The example below excludes use of name resolution for machines that
# are NOT on the local network segment - OR - are not deliberately to
# be known via lmhosts or via WINS.
; name resolve order = wins lmhosts bcast
# Windows Internet Name Serving Support Section:
# WINS Support - Tells the NMBD component of Samba to enable it's WINS
# Server
; wins support = yes
# WINS Server - Tells the NMBD components of Samba to be a WINS Client
# Note: Samba can be either a WINS Server, or a WINS Client, but
# NOT both
; wins server = w.x.y.z
# WINS Proxy - Tells Samba to answer name resolution queries on
# behalf of a non WINS capable client, for this to work there must be
# at least one WINS Server on the network. The default is NO.
; wins proxy = yes
# DNS Proxy - tells Samba whether or not to try to resolve NetBIOS
# names via DNS nslookups. The built-in default for versions 1.9.17 is
# yes, this has been changed in version 1.9.18 to no.
dns proxy = no
# 8. File Naming Options:
# Case Preservation can be handy - system default is _no_
# NOTE: These can be set on a per share basis
; preserve case = no
; short preserve case = no
# Default case is normally upper case for all DOS files
; default case = lower
# Be very careful with case sensitivity - it can break things!
; case sensitive = no
# Enabling internationalization:
# you can match a Windows code page with a UNIX character set.
# Windows: 437 (US), 737 (GREEK), 850 (Latin1 - Western European),
# 852 (Eastern Eu.), 861 (Icelandic), 932 (Cyrillic - Russian),
# 936 (Japanese - Shift-JIS), 936 (Simpl. Chinese), 949 (Korean
# Hangul),
# 950 (Trad. Chin.).
# UNIX: ISO8859-1 (Western European), ISO8859-2 (Eastern Eu.),
# ISO8859-5 (Russian Cyrillic), KOI8-R (Alt-Russ. Cyril.)
# This is an example for french users:
; client code page = 850
; character set = ISO8859-1
#============================ Share Definitions ==============================
[homes]
comment = Home Directories
browseable = no
writable = yes
# You can enable VFS recycle bin on a per share basis:
# Uncomment the next 2 lines (make sure you create a
# .recycle folder in the base of the share and ensure
# all users will have write access to it. See
# examples/VFS/recycle/REAME in samba-doc for details
; vfs object = /usr/lib/samba/vfs/recycle.so
; vfs options= /etc/samba/recycle.conf
# Un-comment the following and create the netlogon directory for Domain
# Logons
; [netlogon]
; comment = Network Logon Service
; path = /var/lib/samba/netlogon
; guest ok = yes
; writable = no
#Uncomment the following 2 lines if you would like your login scripts
# to be created dynamically by ntlogon (check that you have it in the
# correct location (the default of the ntlogon rpm available in
# contribs)
;root preexec = /usr/bin/ntlogon -u %U -g %G -o %a -d /var/lib/samba/netlogon
;root postexec = rm -f /var/lib/samba/netlogon/%U.bat
# Un-comment the following to provide a specific roving profile share
# the default is to use the user's home directory
;[Profiles]
; path = /var/lib/samba/profiles
; browseable = no
; guest ok = yes
# NOTE: If you have a CUPS print system there is no need to
# specifically define each individual printer.
# You must configure the samba printers with the appropriate Windows
# drivers on your Windows clients. On the Samba server no filtering is
# done. If you wish that the server provides the driver and the clients
# send PostScript ("Generic PostScript Printer" under Windows), you
# have to swap the 'print command' line below with the commented one.
[printers]
comment = All Printers
path = /var/spool/samba
browseable = no
# to allow user 'guest account' to print.
guest ok = yes
writable = no
printable = yes
create mode = 0700
# =====================================
# print command: see above for details.
# =====================================
print command = lpr-cups -P %p -o raw %s -r
# using client side printer drivers.
; print command = lpr-cups -P %p %s
# using cups own drivers (use generic PostScript on clients).
# The following two commands are the samba defaults for printing=cups
# change them only if you need different options:
; lpq command = lpq -P %p
; lprm command = cancel %p-%j
# This share is used for Windows NT-style point-and-print support.
# To be able to install drivers, you need to be either root, or listed
# in the printer admin parameter above. Note that you also need write
# access to the directory and share definition to be able to upload the
# drivers.
# For more information on this, please see the Printing Support Section
# of /usr/share/doc/samba-/docs/Samba-HOWTO-Collection.pdf
[print$]
path = /var/lib/samba/printers
browseable = yes
read only = yes
write list = @adm root
# A useful application of samba is to make a PDF-generation service
# To streamline this, install windows postscript drivers (preferably
# colour)on the samba server, so that clients can automatically install
# them.
[pdf-generator]
path = /var/tmp
guest ok = No
printable = Yes
comment = PDF Generator (only valid users)
#print command = /usr/share/samba/scripts/print-pdf file path win_path recipient IP &
print command = /usr/share/samba/scripts/print-pdf %s ~%u \\\\\\\\%L\\\\%u %m %I &
# This one is useful for people to share files
[tmp]
comment = Temporary file space
path = /tmp
read only = no
public = yes
echo command = cat %s; rm %s
# A publicly accessible directory, but read only, except for people in
# the "staff" group
;[public]
; comment = Public Stuff
; path = /home/samba/public
; public = yes
; writable = no
; write list = @staff
# Audited directory through experimental VFS audit.so module:
# Uncomment next line.
; vfs object = /usr/lib/samba/vfs/audit.so
# Other examples.
#
# A private printer, usable only by Fred. Spool data will be placed in
# Fred's
# home directory. Note that fred must have write access to the spool
# directory,
# wherever it is.
;[fredsprn]
; comment = Fred's Printer
; valid users = fred
; path = /homes/fred
; printer = freds_printer
; public = no
; writable = no
; printable = yes
-----------------------------------------------------------
# A private directory, usable only by Fred. Note that Fred requires
# write access to the directory.
;[fredsdir]
[Agustin]
; comment = Fred's Service
comment = Agustin Private Files
; path = /usr/somewhere/private
path = /home/agustin/Documents
; valid users = fred
valid users = agustin
; public = no
; writable = yes
writable = yes
; printable = no
-----------------------------------------------------------
# a service which has a different directory for each machine that
# connects this allows you to tailor configurations to incoming
# machines. You could also use the %u option to tailor it by user name.
# The %m gets replaced with the machine name that is connecting.
;[pchome]
; comment = PC Directories
; path = /usr/pc/%m
; public = no
; writable = yes
-----------------------------------------------------------
# A publicly accessible directory, read/write to all users. Note that
# all files created in the directory by users will be owned by the
# default user, so any user with access can delete any other user's
# files. Obviously this directory must be writable by the default user.
# Another user could of course be specified, in which case all files
# would be owned by that user instead.
;[public]
; path = /usr/somewhere/else/public
; public = yes
; only guest = yes
; writable = yes
; printable = no
-----------------------------------------------------------
# The following two entries demonstrate how to share a directory so
# that two users can place files there that will be owned by the
# specific users. In this setup, the directory should be writable by
# both users and should have the sticky bit set on it to prevent abuse.
# Obviously this could be extended to as many users as required.
;[myshare]
; comment = Mary's and Fred's stuff
; path = /usr/somewhere/shared
; valid users = mary fred
; public = no
; writable = yes
; printable = no
; create mask = 0765
| 19,472 | 538 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_uuid.py | import unittest.mock
from test import support
import builtins
import io
import os
import shutil
import subprocess
import uuid
def importable(name):
try:
__import__(name)
return True
except:
return False
class TestUUID(unittest.TestCase):
def test_UUID(self):
equal = self.assertEqual
ascending = []
for (string, curly, hex, bytes, bytes_le, fields, integer, urn,
time, clock_seq, variant, version) in [
('00000000-0000-0000-0000-000000000000',
'{00000000-0000-0000-0000-000000000000}',
'00000000000000000000000000000000',
b'\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0',
b'\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0',
(0, 0, 0, 0, 0, 0),
0,
'urn:uuid:00000000-0000-0000-0000-000000000000',
0, 0, uuid.RESERVED_NCS, None),
('00010203-0405-0607-0809-0a0b0c0d0e0f',
'{00010203-0405-0607-0809-0a0b0c0d0e0f}',
'000102030405060708090a0b0c0d0e0f',
b'\0\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\x0d\x0e\x0f',
b'\x03\x02\x01\0\x05\x04\x07\x06\x08\t\n\x0b\x0c\x0d\x0e\x0f',
(0x00010203, 0x0405, 0x0607, 8, 9, 0x0a0b0c0d0e0f),
0x000102030405060708090a0b0c0d0e0f,
'urn:uuid:00010203-0405-0607-0809-0a0b0c0d0e0f',
0x607040500010203, 0x809, uuid.RESERVED_NCS, None),
('02d9e6d5-9467-382e-8f9b-9300a64ac3cd',
'{02d9e6d5-9467-382e-8f9b-9300a64ac3cd}',
'02d9e6d59467382e8f9b9300a64ac3cd',
b'\x02\xd9\xe6\xd5\x94\x67\x38\x2e\x8f\x9b\x93\x00\xa6\x4a\xc3\xcd',
b'\xd5\xe6\xd9\x02\x67\x94\x2e\x38\x8f\x9b\x93\x00\xa6\x4a\xc3\xcd',
(0x02d9e6d5, 0x9467, 0x382e, 0x8f, 0x9b, 0x9300a64ac3cd),
0x02d9e6d59467382e8f9b9300a64ac3cd,
'urn:uuid:02d9e6d5-9467-382e-8f9b-9300a64ac3cd',
0x82e946702d9e6d5, 0xf9b, uuid.RFC_4122, 3),
('12345678-1234-5678-1234-567812345678',
'{12345678-1234-5678-1234-567812345678}',
'12345678123456781234567812345678',
b'\x12\x34\x56\x78'*4,
b'\x78\x56\x34\x12\x34\x12\x78\x56\x12\x34\x56\x78\x12\x34\x56\x78',
(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678),
0x12345678123456781234567812345678,
'urn:uuid:12345678-1234-5678-1234-567812345678',
0x678123412345678, 0x1234, uuid.RESERVED_NCS, None),
('6ba7b810-9dad-11d1-80b4-00c04fd430c8',
'{6ba7b810-9dad-11d1-80b4-00c04fd430c8}',
'6ba7b8109dad11d180b400c04fd430c8',
b'\x6b\xa7\xb8\x10\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
b'\x10\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
(0x6ba7b810, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8),
0x6ba7b8109dad11d180b400c04fd430c8,
'urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8',
0x1d19dad6ba7b810, 0xb4, uuid.RFC_4122, 1),
('6ba7b811-9dad-11d1-80b4-00c04fd430c8',
'{6ba7b811-9dad-11d1-80b4-00c04fd430c8}',
'6ba7b8119dad11d180b400c04fd430c8',
b'\x6b\xa7\xb8\x11\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
b'\x11\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
(0x6ba7b811, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8),
0x6ba7b8119dad11d180b400c04fd430c8,
'urn:uuid:6ba7b811-9dad-11d1-80b4-00c04fd430c8',
0x1d19dad6ba7b811, 0xb4, uuid.RFC_4122, 1),
('6ba7b812-9dad-11d1-80b4-00c04fd430c8',
'{6ba7b812-9dad-11d1-80b4-00c04fd430c8}',
'6ba7b8129dad11d180b400c04fd430c8',
b'\x6b\xa7\xb8\x12\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
b'\x12\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
(0x6ba7b812, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8),
0x6ba7b8129dad11d180b400c04fd430c8,
'urn:uuid:6ba7b812-9dad-11d1-80b4-00c04fd430c8',
0x1d19dad6ba7b812, 0xb4, uuid.RFC_4122, 1),
('6ba7b814-9dad-11d1-80b4-00c04fd430c8',
'{6ba7b814-9dad-11d1-80b4-00c04fd430c8}',
'6ba7b8149dad11d180b400c04fd430c8',
b'\x6b\xa7\xb8\x14\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
b'\x14\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
(0x6ba7b814, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8),
0x6ba7b8149dad11d180b400c04fd430c8,
'urn:uuid:6ba7b814-9dad-11d1-80b4-00c04fd430c8',
0x1d19dad6ba7b814, 0xb4, uuid.RFC_4122, 1),
('7d444840-9dc0-11d1-b245-5ffdce74fad2',
'{7d444840-9dc0-11d1-b245-5ffdce74fad2}',
'7d4448409dc011d1b2455ffdce74fad2',
b'\x7d\x44\x48\x40\x9d\xc0\x11\xd1\xb2\x45\x5f\xfd\xce\x74\xfa\xd2',
b'\x40\x48\x44\x7d\xc0\x9d\xd1\x11\xb2\x45\x5f\xfd\xce\x74\xfa\xd2',
(0x7d444840, 0x9dc0, 0x11d1, 0xb2, 0x45, 0x5ffdce74fad2),
0x7d4448409dc011d1b2455ffdce74fad2,
'urn:uuid:7d444840-9dc0-11d1-b245-5ffdce74fad2',
0x1d19dc07d444840, 0x3245, uuid.RFC_4122, 1),
('e902893a-9d22-3c7e-a7b8-d6e313b71d9f',
'{e902893a-9d22-3c7e-a7b8-d6e313b71d9f}',
'e902893a9d223c7ea7b8d6e313b71d9f',
b'\xe9\x02\x89\x3a\x9d\x22\x3c\x7e\xa7\xb8\xd6\xe3\x13\xb7\x1d\x9f',
b'\x3a\x89\x02\xe9\x22\x9d\x7e\x3c\xa7\xb8\xd6\xe3\x13\xb7\x1d\x9f',
(0xe902893a, 0x9d22, 0x3c7e, 0xa7, 0xb8, 0xd6e313b71d9f),
0xe902893a9d223c7ea7b8d6e313b71d9f,
'urn:uuid:e902893a-9d22-3c7e-a7b8-d6e313b71d9f',
0xc7e9d22e902893a, 0x27b8, uuid.RFC_4122, 3),
('eb424026-6f54-4ef8-a4d0-bb658a1fc6cf',
'{eb424026-6f54-4ef8-a4d0-bb658a1fc6cf}',
'eb4240266f544ef8a4d0bb658a1fc6cf',
b'\xeb\x42\x40\x26\x6f\x54\x4e\xf8\xa4\xd0\xbb\x65\x8a\x1f\xc6\xcf',
b'\x26\x40\x42\xeb\x54\x6f\xf8\x4e\xa4\xd0\xbb\x65\x8a\x1f\xc6\xcf',
(0xeb424026, 0x6f54, 0x4ef8, 0xa4, 0xd0, 0xbb658a1fc6cf),
0xeb4240266f544ef8a4d0bb658a1fc6cf,
'urn:uuid:eb424026-6f54-4ef8-a4d0-bb658a1fc6cf',
0xef86f54eb424026, 0x24d0, uuid.RFC_4122, 4),
('f81d4fae-7dec-11d0-a765-00a0c91e6bf6',
'{f81d4fae-7dec-11d0-a765-00a0c91e6bf6}',
'f81d4fae7dec11d0a76500a0c91e6bf6',
b'\xf8\x1d\x4f\xae\x7d\xec\x11\xd0\xa7\x65\x00\xa0\xc9\x1e\x6b\xf6',
b'\xae\x4f\x1d\xf8\xec\x7d\xd0\x11\xa7\x65\x00\xa0\xc9\x1e\x6b\xf6',
(0xf81d4fae, 0x7dec, 0x11d0, 0xa7, 0x65, 0x00a0c91e6bf6),
0xf81d4fae7dec11d0a76500a0c91e6bf6,
'urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6',
0x1d07decf81d4fae, 0x2765, uuid.RFC_4122, 1),
('fffefdfc-fffe-fffe-fffe-fffefdfcfbfa',
'{fffefdfc-fffe-fffe-fffe-fffefdfcfbfa}',
'fffefdfcfffefffefffefffefdfcfbfa',
b'\xff\xfe\xfd\xfc\xff\xfe\xff\xfe\xff\xfe\xff\xfe\xfd\xfc\xfb\xfa',
b'\xfc\xfd\xfe\xff\xfe\xff\xfe\xff\xff\xfe\xff\xfe\xfd\xfc\xfb\xfa',
(0xfffefdfc, 0xfffe, 0xfffe, 0xff, 0xfe, 0xfffefdfcfbfa),
0xfffefdfcfffefffefffefffefdfcfbfa,
'urn:uuid:fffefdfc-fffe-fffe-fffe-fffefdfcfbfa',
0xffefffefffefdfc, 0x3ffe, uuid.RESERVED_FUTURE, None),
('ffffffff-ffff-ffff-ffff-ffffffffffff',
'{ffffffff-ffff-ffff-ffff-ffffffffffff}',
'ffffffffffffffffffffffffffffffff',
b'\xff'*16,
b'\xff'*16,
(0xffffffff, 0xffff, 0xffff, 0xff, 0xff, 0xffffffffffff),
0xffffffffffffffffffffffffffffffff,
'urn:uuid:ffffffff-ffff-ffff-ffff-ffffffffffff',
0xfffffffffffffff, 0x3fff, uuid.RESERVED_FUTURE, None),
]:
equivalents = []
# Construct each UUID in several different ways.
for u in [uuid.UUID(string), uuid.UUID(curly), uuid.UUID(hex),
uuid.UUID(bytes=bytes), uuid.UUID(bytes_le=bytes_le),
uuid.UUID(fields=fields), uuid.UUID(int=integer),
uuid.UUID(urn)]:
# Test all conversions and properties of the UUID object.
equal(str(u), string)
equal(int(u), integer)
equal(u.bytes, bytes)
equal(u.bytes_le, bytes_le)
equal(u.fields, fields)
equal(u.time_low, fields[0])
equal(u.time_mid, fields[1])
equal(u.time_hi_version, fields[2])
equal(u.clock_seq_hi_variant, fields[3])
equal(u.clock_seq_low, fields[4])
equal(u.node, fields[5])
equal(u.hex, hex)
equal(u.int, integer)
equal(u.urn, urn)
equal(u.time, time)
equal(u.clock_seq, clock_seq)
equal(u.variant, variant)
equal(u.version, version)
equivalents.append(u)
# Different construction methods should give the same UUID.
for u in equivalents:
for v in equivalents:
equal(u, v)
# Bug 7380: "bytes" and "bytes_le" should give the same type.
equal(type(u.bytes), builtins.bytes)
equal(type(u.bytes_le), builtins.bytes)
ascending.append(u)
# Test comparison of UUIDs.
for i in range(len(ascending)):
for j in range(len(ascending)):
equal(i < j, ascending[i] < ascending[j])
equal(i <= j, ascending[i] <= ascending[j])
equal(i == j, ascending[i] == ascending[j])
equal(i > j, ascending[i] > ascending[j])
equal(i >= j, ascending[i] >= ascending[j])
equal(i != j, ascending[i] != ascending[j])
# Test sorting of UUIDs (above list is in ascending order).
resorted = ascending[:]
resorted.reverse()
resorted.sort()
equal(ascending, resorted)
def test_exceptions(self):
badvalue = lambda f: self.assertRaises(ValueError, f)
badtype = lambda f: self.assertRaises(TypeError, f)
# Badly formed hex strings.
badvalue(lambda: uuid.UUID(''))
badvalue(lambda: uuid.UUID('abc'))
badvalue(lambda: uuid.UUID('1234567812345678123456781234567'))
badvalue(lambda: uuid.UUID('123456781234567812345678123456789'))
badvalue(lambda: uuid.UUID('123456781234567812345678z2345678'))
# Badly formed bytes.
badvalue(lambda: uuid.UUID(bytes='abc'))
badvalue(lambda: uuid.UUID(bytes='\0'*15))
badvalue(lambda: uuid.UUID(bytes='\0'*17))
# Badly formed bytes_le.
badvalue(lambda: uuid.UUID(bytes_le='abc'))
badvalue(lambda: uuid.UUID(bytes_le='\0'*15))
badvalue(lambda: uuid.UUID(bytes_le='\0'*17))
# Badly formed fields.
badvalue(lambda: uuid.UUID(fields=(1,)))
badvalue(lambda: uuid.UUID(fields=(1, 2, 3, 4, 5)))
badvalue(lambda: uuid.UUID(fields=(1, 2, 3, 4, 5, 6, 7)))
# Field values out of range.
badvalue(lambda: uuid.UUID(fields=(-1, 0, 0, 0, 0, 0)))
badvalue(lambda: uuid.UUID(fields=(0x100000000, 0, 0, 0, 0, 0)))
badvalue(lambda: uuid.UUID(fields=(0, -1, 0, 0, 0, 0)))
badvalue(lambda: uuid.UUID(fields=(0, 0x10000, 0, 0, 0, 0)))
badvalue(lambda: uuid.UUID(fields=(0, 0, -1, 0, 0, 0)))
badvalue(lambda: uuid.UUID(fields=(0, 0, 0x10000, 0, 0, 0)))
badvalue(lambda: uuid.UUID(fields=(0, 0, 0, -1, 0, 0)))
badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0x100, 0, 0)))
badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, -1, 0)))
badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0x100, 0)))
badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0, -1)))
badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0, 0x1000000000000)))
# Version number out of range.
badvalue(lambda: uuid.UUID('00'*16, version=0))
badvalue(lambda: uuid.UUID('00'*16, version=6))
# Integer value out of range.
badvalue(lambda: uuid.UUID(int=-1))
badvalue(lambda: uuid.UUID(int=1<<128))
# Must supply exactly one of hex, bytes, fields, int.
h, b, f, i = '00'*16, b'\0'*16, (0, 0, 0, 0, 0, 0), 0
uuid.UUID(h)
uuid.UUID(hex=h)
uuid.UUID(bytes=b)
uuid.UUID(bytes_le=b)
uuid.UUID(fields=f)
uuid.UUID(int=i)
# Wrong number of arguments (positional).
badtype(lambda: uuid.UUID())
badtype(lambda: uuid.UUID(h, b))
badtype(lambda: uuid.UUID(h, b, b))
badtype(lambda: uuid.UUID(h, b, b, f))
badtype(lambda: uuid.UUID(h, b, b, f, i))
# Duplicate arguments.
for hh in [[], [('hex', h)]]:
for bb in [[], [('bytes', b)]]:
for bble in [[], [('bytes_le', b)]]:
for ii in [[], [('int', i)]]:
for ff in [[], [('fields', f)]]:
args = dict(hh + bb + bble + ii + ff)
if len(args) != 0:
badtype(lambda: uuid.UUID(h, **args))
if len(args) != 1:
badtype(lambda: uuid.UUID(**args))
# Immutability.
u = uuid.UUID(h)
badtype(lambda: setattr(u, 'hex', h))
badtype(lambda: setattr(u, 'bytes', b))
badtype(lambda: setattr(u, 'bytes_le', b))
badtype(lambda: setattr(u, 'fields', f))
badtype(lambda: setattr(u, 'int', i))
badtype(lambda: setattr(u, 'time_low', 0))
badtype(lambda: setattr(u, 'time_mid', 0))
badtype(lambda: setattr(u, 'time_hi_version', 0))
badtype(lambda: setattr(u, 'time_hi_version', 0))
badtype(lambda: setattr(u, 'clock_seq_hi_variant', 0))
badtype(lambda: setattr(u, 'clock_seq_low', 0))
badtype(lambda: setattr(u, 'node', 0))
# Comparison with a non-UUID object
badtype(lambda: u < object())
badtype(lambda: u > object())
def test_getnode(self):
node1 = uuid.getnode()
self.assertTrue(0 < node1 < (1 << 48), '%012x' % node1)
# Test it again to ensure consistency.
node2 = uuid.getnode()
self.assertEqual(node1, node2, '%012x != %012x' % (node1, node2))
# bpo-32502: UUID1 requires a 48-bit identifier, but hardware identifiers
# need not necessarily be 48 bits (e.g., EUI-64).
def test_uuid1_eui64(self):
# Confirm that uuid.getnode ignores hardware addresses larger than 48
# bits. Mock out each platform's *_getnode helper functions to return
# something just larger than 48 bits to test. This will cause
# uuid.getnode to fall back on uuid._random_getnode, which will
# generate a valid value.
too_large_getter = lambda: 1 << 48
with unittest.mock.patch.multiple(
uuid,
_node=None, # Ignore any cached node value.
_NODE_GETTERS_WIN32=[too_large_getter],
_NODE_GETTERS_UNIX=[too_large_getter],
):
node = uuid.getnode()
self.assertTrue(0 < node < (1 << 48), '%012x' % node)
# Confirm that uuid1 can use the generated node, i.e., the that
# uuid.getnode fell back on uuid._random_getnode() rather than using
# the value from too_large_getter above.
try:
uuid.uuid1(node=node)
except ValueError as e:
self.fail('uuid1 was given an invalid node ID')
@unittest.skipUnless(importable('ctypes'), 'requires ctypes')
def test_uuid1(self):
equal = self.assertEqual
# Make sure uuid1() generates UUIDs that are actually version 1.
for u in [uuid.uuid1() for i in range(10)]:
equal(u.variant, uuid.RFC_4122)
equal(u.version, 1)
# Make sure the generated UUIDs are actually unique.
uuids = {}
for u in [uuid.uuid1() for i in range(1000)]:
uuids[u] = 1
equal(len(uuids.keys()), 1000)
# Make sure the supplied node ID appears in the UUID.
u = uuid.uuid1(0)
equal(u.node, 0)
u = uuid.uuid1(0x123456789abc)
equal(u.node, 0x123456789abc)
u = uuid.uuid1(0xffffffffffff)
equal(u.node, 0xffffffffffff)
# Make sure the supplied clock sequence appears in the UUID.
u = uuid.uuid1(0x123456789abc, 0)
equal(u.node, 0x123456789abc)
equal(((u.clock_seq_hi_variant & 0x3f) << 8) | u.clock_seq_low, 0)
u = uuid.uuid1(0x123456789abc, 0x1234)
equal(u.node, 0x123456789abc)
equal(((u.clock_seq_hi_variant & 0x3f) << 8) |
u.clock_seq_low, 0x1234)
u = uuid.uuid1(0x123456789abc, 0x3fff)
equal(u.node, 0x123456789abc)
equal(((u.clock_seq_hi_variant & 0x3f) << 8) |
u.clock_seq_low, 0x3fff)
def test_uuid3(self):
equal = self.assertEqual
# Test some known version-3 UUIDs.
for u, v in [(uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org'),
'6fa459ea-ee8a-3ca4-894e-db77e160355e'),
(uuid.uuid3(uuid.NAMESPACE_URL, 'http://python.org/'),
'9fe8e8c4-aaa8-32a9-a55c-4535a88b748d'),
(uuid.uuid3(uuid.NAMESPACE_OID, '1.3.6.1'),
'dd1a1cef-13d5-368a-ad82-eca71acd4cd1'),
(uuid.uuid3(uuid.NAMESPACE_X500, 'c=ca'),
'658d3002-db6b-3040-a1d1-8ddd7d189a4d'),
]:
equal(u.variant, uuid.RFC_4122)
equal(u.version, 3)
equal(u, uuid.UUID(v))
equal(str(u), v)
def test_uuid4(self):
equal = self.assertEqual
# Make sure uuid4() generates UUIDs that are actually version 4.
for u in [uuid.uuid4() for i in range(10)]:
equal(u.variant, uuid.RFC_4122)
equal(u.version, 4)
# Make sure the generated UUIDs are actually unique.
uuids = {}
for u in [uuid.uuid4() for i in range(1000)]:
uuids[u] = 1
equal(len(uuids.keys()), 1000)
def test_uuid5(self):
equal = self.assertEqual
# Test some known version-5 UUIDs.
for u, v in [(uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org'),
'886313e1-3b8a-5372-9b90-0c9aee199e5d'),
(uuid.uuid5(uuid.NAMESPACE_URL, 'http://python.org/'),
'4c565f0d-3f5a-5890-b41b-20cf47701c5e'),
(uuid.uuid5(uuid.NAMESPACE_OID, '1.3.6.1'),
'1447fa61-5277-5fef-a9b3-fbc6e44f4af3'),
(uuid.uuid5(uuid.NAMESPACE_X500, 'c=ca'),
'cc957dd1-a972-5349-98cd-874190002798'),
]:
equal(u.variant, uuid.RFC_4122)
equal(u.version, 5)
equal(u, uuid.UUID(v))
equal(str(u), v)
@unittest.skipUnless(os.name == 'posix', 'requires Posix')
def testIssue8621(self):
# On at least some versions of OSX uuid.uuid4 generates
# the same sequence of UUIDs in the parent and any
# children started using fork.
fds = os.pipe()
pid = os.fork()
if pid == 0:
os.close(fds[0])
value = uuid.uuid4()
os.write(fds[1], value.hex.encode('latin-1'))
os._exit(0)
else:
os.close(fds[1])
self.addCleanup(os.close, fds[0])
parent_value = uuid.uuid4().hex
os.waitpid(pid, 0)
child_value = os.read(fds[0], 100).decode('latin-1')
self.assertNotEqual(parent_value, child_value)
class TestInternals(unittest.TestCase):
@unittest.skipUnless(os.name == 'posix', 'requires Posix')
def test_find_mac(self):
data = '''
fake hwaddr
cscotun0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
eth0 Link encap:Ethernet HWaddr 12:34:56:78:90:ab
'''
popen = unittest.mock.MagicMock()
popen.stdout = io.BytesIO(data.encode())
with unittest.mock.patch.object(shutil, 'which',
return_value='/sbin/ifconfig'):
with unittest.mock.patch.object(subprocess, 'Popen',
return_value=popen):
mac = uuid._find_mac(
command='ifconfig',
args='',
hw_identifiers=[b'hwaddr'],
get_index=lambda x: x + 1,
)
self.assertEqual(mac, 0x1234567890ab)
def check_node(self, node, requires=None):
if requires and node is None:
self.skipTest('requires ' + requires)
hex = '%012x' % node
if support.verbose >= 2:
print(hex, end=' ')
self.assertTrue(0 < node < (1 << 48),
"%s is not an RFC 4122 node ID" % hex)
@unittest.skipUnless(os.name == 'posix', 'requires Posix')
def test_ifconfig_getnode(self):
node = uuid._ifconfig_getnode()
self.check_node(node, 'ifconfig')
@unittest.skipUnless(os.name == 'posix', 'requires Posix')
def test_ip_getnode(self):
node = uuid._ip_getnode()
self.check_node(node, 'ip')
@unittest.skipUnless(os.name == 'posix', 'requires Posix')
def test_arp_getnode(self):
return
node = uuid._arp_getnode()
self.check_node(node, 'arp')
@unittest.skipUnless(os.name == 'posix', 'requires Posix')
def test_lanscan_getnode(self):
node = uuid._lanscan_getnode()
self.check_node(node, 'lanscan')
@unittest.skipUnless(os.name == 'posix', 'requires Posix')
def test_netstat_getnode(self):
node = uuid._netstat_getnode()
self.check_node(node, 'netstat')
@unittest.skipUnless(os.name == 'nt', 'requires Windows')
def test_ipconfig_getnode(self):
node = uuid._ipconfig_getnode()
self.check_node(node, 'ipconfig')
@unittest.skipUnless(importable('win32wnet'), 'requires win32wnet')
@unittest.skipUnless(importable('netbios'), 'requires netbios')
def test_netbios_getnode(self):
node = uuid._netbios_getnode()
self.check_node(node)
def test_random_getnode(self):
node = uuid._random_getnode()
# The multicast bit, i.e. the least significant bit of first octet,
# must be set for randomly generated MAC addresses. See RFC 4122,
# $4.1.6.
self.assertTrue(node & (1 << 40), '%012x' % node)
self.check_node(node)
@unittest.skipUnless(os.name == 'posix', 'requires Posix')
@unittest.skipUnless(importable('ctypes'), 'requires ctypes')
def test_unixdll_getnode(self):
try: # Issues 1481, 3581: _uuid_generate_time() might be None.
node = uuid._unixdll_getnode()
except TypeError:
self.skipTest('requires uuid_generate_time')
self.check_node(node)
@unittest.skipUnless(os.name == 'nt', 'requires Windows')
@unittest.skipUnless(importable('ctypes'), 'requires ctypes')
def test_windll_getnode(self):
node = uuid._windll_getnode()
self.check_node(node)
if __name__ == '__main__':
unittest.main()
| 23,725 | 539 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_codecencodings_jp.py | #
# test_codecencodings_jp.py
# Codec encoding tests for Japanese encodings.
#
from test import multibytecodec_support
import unittest
class Test_CP932(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'cp932'
tstring = multibytecodec_support.load_teststring('shift_jis')
codectests = (
# invalid bytes
(b"abc\x81\x00\x81\x00\x82\x84", "strict", None),
(b"abc\xf8", "strict", None),
(b"abc\x81\x00\x82\x84", "replace", "abc\ufffd\x00\uff44"),
(b"abc\x81\x00\x82\x84\x88", "replace", "abc\ufffd\x00\uff44\ufffd"),
(b"abc\x81\x00\x82\x84", "ignore", "abc\x00\uff44"),
(b"ab\xEBxy", "replace", "ab\uFFFDxy"),
(b"ab\xF0\x39xy", "replace", "ab\uFFFD9xy"),
(b"ab\xEA\xF0xy", "replace", 'ab\ufffd\ue038y'),
# sjis vs cp932
(b"\\\x7e", "replace", "\\\x7e"),
(b"\x81\x5f\x81\x61\x81\x7c", "replace", "\uff3c\u2225\uff0d"),
)
euc_commontests = (
# invalid bytes
(b"abc\x80\x80\xc1\xc4", "strict", None),
(b"abc\x80\x80\xc1\xc4", "replace", "abc\ufffd\ufffd\u7956"),
(b"abc\x80\x80\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\u7956\ufffd"),
(b"abc\x80\x80\xc1\xc4", "ignore", "abc\u7956"),
(b"abc\xc8", "strict", None),
(b"abc\x8f\x83\x83", "replace", "abc\ufffd\ufffd\ufffd"),
(b"\x82\xFCxy", "replace", "\ufffd\ufffdxy"),
(b"\xc1\x64", "strict", None),
(b"\xa1\xc0", "strict", "\uff3c"),
(b"\xa1\xc0\\", "strict", "\uff3c\\"),
(b"\x8eXY", "replace", "\ufffdXY"),
)
class Test_EUC_JIS_2004(multibytecodec_support.TestBase,
unittest.TestCase):
encoding = 'euc_jis_2004'
tstring = multibytecodec_support.load_teststring('euc_jisx0213')
codectests = euc_commontests
xmlcharnametest = (
"\xab\u211c\xbb = \u2329\u1234\u232a",
b"\xa9\xa8ℜ\xa9\xb2 = ⟨ሴ⟩"
)
class Test_EUC_JISX0213(multibytecodec_support.TestBase,
unittest.TestCase):
encoding = 'euc_jisx0213'
tstring = multibytecodec_support.load_teststring('euc_jisx0213')
codectests = euc_commontests
xmlcharnametest = (
"\xab\u211c\xbb = \u2329\u1234\u232a",
b"\xa9\xa8ℜ\xa9\xb2 = ⟨ሴ⟩"
)
class Test_EUC_JP_COMPAT(multibytecodec_support.TestBase,
unittest.TestCase):
encoding = 'euc_jp'
tstring = multibytecodec_support.load_teststring('euc_jp')
codectests = euc_commontests + (
("\xa5", "strict", b"\x5c"),
("\u203e", "strict", b"\x7e"),
)
shiftjis_commonenctests = (
(b"abc\x80\x80\x82\x84", "strict", None),
(b"abc\xf8", "strict", None),
(b"abc\x80\x80\x82\x84def", "ignore", "abc\uff44def"),
)
class Test_SJIS_COMPAT(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'shift_jis'
tstring = multibytecodec_support.load_teststring('shift_jis')
codectests = shiftjis_commonenctests + (
(b"abc\x80\x80\x82\x84", "replace", "abc\ufffd\ufffd\uff44"),
(b"abc\x80\x80\x82\x84\x88", "replace", "abc\ufffd\ufffd\uff44\ufffd"),
(b"\\\x7e", "strict", "\\\x7e"),
(b"\x81\x5f\x81\x61\x81\x7c", "strict", "\uff3c\u2016\u2212"),
(b"abc\x81\x39", "replace", "abc\ufffd9"),
(b"abc\xEA\xFC", "replace", "abc\ufffd\ufffd"),
(b"abc\xFF\x58", "replace", "abc\ufffdX"),
)
class Test_SJIS_2004(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'shift_jis_2004'
tstring = multibytecodec_support.load_teststring('shift_jis')
codectests = shiftjis_commonenctests + (
(b"\\\x7e", "strict", "\xa5\u203e"),
(b"\x81\x5f\x81\x61\x81\x7c", "strict", "\\\u2016\u2212"),
(b"abc\xEA\xFC", "strict", "abc\u64bf"),
(b"\x81\x39xy", "replace", "\ufffd9xy"),
(b"\xFF\x58xy", "replace", "\ufffdXxy"),
(b"\x80\x80\x82\x84xy", "replace", "\ufffd\ufffd\uff44xy"),
(b"\x80\x80\x82\x84\x88xy", "replace", "\ufffd\ufffd\uff44\u5864y"),
(b"\xFC\xFBxy", "replace", '\ufffd\u95b4y'),
)
xmlcharnametest = (
"\xab\u211c\xbb = \u2329\u1234\u232a",
b"\x85Gℜ\x85Q = ⟨ሴ⟩"
)
class Test_SJISX0213(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'shift_jisx0213'
tstring = multibytecodec_support.load_teststring('shift_jisx0213')
codectests = shiftjis_commonenctests + (
(b"abc\x80\x80\x82\x84", "replace", "abc\ufffd\ufffd\uff44"),
(b"abc\x80\x80\x82\x84\x88", "replace", "abc\ufffd\ufffd\uff44\ufffd"),
# sjis vs cp932
(b"\\\x7e", "replace", "\xa5\u203e"),
(b"\x81\x5f\x81\x61\x81\x7c", "replace", "\x5c\u2016\u2212"),
)
xmlcharnametest = (
"\xab\u211c\xbb = \u2329\u1234\u232a",
b"\x85Gℜ\x85Q = ⟨ሴ⟩"
)
if __name__ == "__main__":
unittest.main()
| 4,907 | 127 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_zipimport_support.py | # This test module covers support in various parts of the standard library
# for working with modules located inside zipfiles
# The tests are centralised in this fashion to make it easy to drop them
# if a platform doesn't support zipimport
import test.support
import os
import os.path
import sys
import textwrap
import zipfile
import zipimport
import doctest
import inspect
import linecache
import unittest
from test.support.script_helper import (spawn_python, kill_python, assert_python_ok,
make_script, make_zip_script)
verbose = test.support.verbose
# Library modules covered by this test set
# pdb (Issue 4201)
# inspect (Issue 4223)
# doctest (Issue 4197)
# Other test modules with zipimport related tests
# test_zipimport (of course!)
# test_cmd_line_script (covers the zipimport support in runpy)
# Retrieve some helpers from other test cases
from test import (test_doctest, sample_doctest, sample_doctest_no_doctests,
sample_doctest_no_docstrings)
def _run_object_doctest(obj, module):
finder = doctest.DocTestFinder(verbose=verbose, recurse=False)
runner = doctest.DocTestRunner(verbose=verbose)
# Use the object's fully qualified name if it has one
# Otherwise, use the module's name
try:
name = "%s.%s" % (obj.__module__, obj.__qualname__)
except AttributeError:
name = module.__name__
for example in finder.find(obj, name, module):
runner.run(example)
f, t = runner.failures, runner.tries
if f:
raise test.support.TestFailed("%d of %d doctests failed" % (f, t))
if verbose:
print ('doctest (%s) ... %d tests with zero failures' % (module.__name__, t))
return f, t
class ZipSupportTests(unittest.TestCase):
# This used to use the ImportHooksBaseTestCase to restore
# the state of the import related information
# in the sys module after each test. However, that restores
# *too much* information and breaks for the invocation
# of test_doctest. So we do our own thing and leave
# sys.modules alone.
# We also clear the linecache and zipimport cache
# just to avoid any bogus errors due to name reuse in the tests
def setUp(self):
linecache.clearcache()
zipimport._zip_directory_cache.clear()
self.path = sys.path[:]
self.meta_path = sys.meta_path[:]
self.path_hooks = sys.path_hooks[:]
sys.path_importer_cache.clear()
def tearDown(self):
sys.path[:] = self.path
sys.meta_path[:] = self.meta_path
sys.path_hooks[:] = self.path_hooks
sys.path_importer_cache.clear()
def test_inspect_getsource_issue4223(self):
test_src = "def foo(): pass\n"
with test.support.temp_dir() as d:
init_name = make_script(d, '__init__', test_src)
name_in_zip = os.path.join('zip_pkg',
os.path.basename(init_name))
zip_name, run_name = make_zip_script(d, 'test_zip',
init_name, name_in_zip)
os.remove(init_name)
sys.path.insert(0, zip_name)
import zip_pkg
try:
self.assertEqual(inspect.getsource(zip_pkg.foo), test_src)
finally:
del sys.modules["zip_pkg"]
def test_doctest_issue4197(self):
# To avoid having to keep two copies of the doctest module's
# unit tests in sync, this test works by taking the source of
# test_doctest itself, rewriting it a bit to cope with a new
# location, and then throwing it in a zip file to make sure
# everything still works correctly
test_src = inspect.getsource(test_doctest)
test_src = test_src.replace(
"from test import test_doctest",
"import test_zipped_doctest as test_doctest")
test_src = test_src.replace("test.test_doctest",
"test_zipped_doctest")
test_src = test_src.replace("test.sample_doctest",
"sample_zipped_doctest")
# The sample doctest files rewritten to include in the zipped version.
sample_sources = {}
for mod in [sample_doctest, sample_doctest_no_doctests,
sample_doctest_no_docstrings]:
src = inspect.getsource(mod)
src = src.replace("test.test_doctest", "test_zipped_doctest")
# Rewrite the module name so that, for example,
# "test.sample_doctest" becomes "sample_zipped_doctest".
mod_name = mod.__name__.split(".")[-1]
mod_name = mod_name.replace("sample_", "sample_zipped_")
sample_sources[mod_name] = src
with test.support.temp_dir() as d:
script_name = make_script(d, 'test_zipped_doctest',
test_src)
zip_name, run_name = make_zip_script(d, 'test_zip',
script_name)
z = zipfile.ZipFile(zip_name, 'a')
for mod_name, src in sample_sources.items():
z.writestr(mod_name + ".py", src)
z.close()
if verbose:
zip_file = zipfile.ZipFile(zip_name, 'r')
print ('Contents of %r:' % zip_name)
zip_file.printdir()
zip_file.close()
os.remove(script_name)
sys.path.insert(0, zip_name)
import test_zipped_doctest
try:
# Some of the doc tests depend on the colocated text files
# which aren't available to the zipped version (the doctest
# module currently requires real filenames for non-embedded
# tests). So we're forced to be selective about which tests
# to run.
# doctest could really use some APIs which take a text
# string or a file object instead of a filename...
known_good_tests = [
test_zipped_doctest.SampleClass,
test_zipped_doctest.SampleClass.NestedClass,
test_zipped_doctest.SampleClass.NestedClass.__init__,
test_zipped_doctest.SampleClass.__init__,
test_zipped_doctest.SampleClass.a_classmethod,
test_zipped_doctest.SampleClass.a_property,
test_zipped_doctest.SampleClass.a_staticmethod,
test_zipped_doctest.SampleClass.double,
test_zipped_doctest.SampleClass.get,
test_zipped_doctest.SampleNewStyleClass,
test_zipped_doctest.SampleNewStyleClass.__init__,
test_zipped_doctest.SampleNewStyleClass.double,
test_zipped_doctest.SampleNewStyleClass.get,
test_zipped_doctest.sample_func,
test_zipped_doctest.test_DocTest,
test_zipped_doctest.test_DocTestParser,
test_zipped_doctest.test_DocTestRunner.basics,
test_zipped_doctest.test_DocTestRunner.exceptions,
test_zipped_doctest.test_DocTestRunner.option_directives,
test_zipped_doctest.test_DocTestRunner.optionflags,
test_zipped_doctest.test_DocTestRunner.verbose_flag,
test_zipped_doctest.test_Example,
test_zipped_doctest.test_debug,
test_zipped_doctest.test_testsource,
test_zipped_doctest.test_trailing_space_in_test,
test_zipped_doctest.test_DocTestSuite,
test_zipped_doctest.test_DocTestFinder,
]
# These tests are the ones which need access
# to the data files, so we don't run them
fail_due_to_missing_data_files = [
test_zipped_doctest.test_DocFileSuite,
test_zipped_doctest.test_testfile,
test_zipped_doctest.test_unittest_reportflags,
]
for obj in known_good_tests:
_run_object_doctest(obj, test_zipped_doctest)
finally:
del sys.modules["test_zipped_doctest"]
def test_doctest_main_issue4197(self):
test_src = textwrap.dedent("""\
class Test:
">>> 'line 2'"
pass
import doctest
doctest.testmod()
""")
pattern = 'File "%s", line 2, in %s'
with test.support.temp_dir() as d:
script_name = make_script(d, 'script', test_src)
rc, out, err = assert_python_ok(script_name)
expected = pattern % (script_name, "__main__.Test")
if verbose:
print ("Expected line", expected)
print ("Got stdout:")
print (ascii(out))
self.assertIn(expected.encode('utf-8'), out)
zip_name, run_name = make_zip_script(d, "test_zip",
script_name, '__main__.py')
rc, out, err = assert_python_ok(zip_name)
expected = pattern % (run_name, "__main__.Test")
if verbose:
print ("Expected line", expected)
print ("Got stdout:")
print (ascii(out))
self.assertIn(expected.encode('utf-8'), out)
def test_pdb_issue4201(self):
test_src = textwrap.dedent("""\
def f():
pass
import pdb
pdb.Pdb(nosigint=True).runcall(f)
""")
with test.support.temp_dir() as d:
script_name = make_script(d, 'script', test_src)
p = spawn_python(script_name)
p.stdin.write(b'l\n')
data = kill_python(p)
# bdb/pdb applies normcase to its filename before displaying
self.assertIn(os.path.normcase(script_name.encode('utf-8')), data)
zip_name, run_name = make_zip_script(d, "test_zip",
script_name, '__main__.py')
p = spawn_python(zip_name)
p.stdin.write(b'l\n')
data = kill_python(p)
# bdb/pdb applies normcase to its filename before displaying
self.assertIn(os.path.normcase(run_name.encode('utf-8')), data)
def tearDownModule():
test.support.reap_children()
if __name__ == '__main__':
unittest.main()
| 10,714 | 245 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/bad_coding2.py | #coding: utf8
print('æ')
| 30 | 3 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_cgitb.py | from test.support import temp_dir
from test.support.script_helper import assert_python_failure
import unittest
import sys
import cgitb
class TestCgitb(unittest.TestCase):
def test_fonts(self):
text = "Hello Robbie!"
self.assertEqual(cgitb.small(text), "<small>{}</small>".format(text))
self.assertEqual(cgitb.strong(text), "<strong>{}</strong>".format(text))
self.assertEqual(cgitb.grey(text),
'<font color="#909090">{}</font>'.format(text))
def test_blanks(self):
self.assertEqual(cgitb.small(""), "")
self.assertEqual(cgitb.strong(""), "")
self.assertEqual(cgitb.grey(""), "")
def test_html(self):
try:
raise ValueError("Hello World")
except ValueError as err:
# If the html was templated we could do a bit more here.
# At least check that we get details on what we just raised.
html = cgitb.html(sys.exc_info())
self.assertIn("ValueError", html)
self.assertIn(str(err), html)
def test_text(self):
try:
raise ValueError("Hello World")
except ValueError as err:
text = cgitb.text(sys.exc_info())
self.assertIn("ValueError", text)
self.assertIn("Hello World", text)
def test_syshook_no_logdir_default_format(self):
with temp_dir() as tracedir:
rc, out, err = assert_python_failure(
'-c',
('import cgitb; cgitb.enable(logdir=%s); '
'raise ValueError("Hello World")') % repr(tracedir))
out = out.decode(sys.getfilesystemencoding())
self.assertIn("ValueError", out)
self.assertIn("Hello World", out)
self.assertIn("<strong><module></strong>", out)
# By default we emit HTML markup.
self.assertIn('<p>', out)
self.assertIn('</p>', out)
def test_syshook_no_logdir_text_format(self):
# Issue 12890: we were emitting the <p> tag in text mode.
with temp_dir() as tracedir:
rc, out, err = assert_python_failure(
'-c',
('import cgitb; cgitb.enable(format="text", logdir=%s); '
'raise ValueError("Hello World")') % repr(tracedir))
out = out.decode(sys.getfilesystemencoding())
self.assertIn("ValueError", out)
self.assertIn("Hello World", out)
self.assertNotIn('<p>', out)
self.assertNotIn('</p>', out)
if __name__ == "__main__":
unittest.main()
| 2,565 | 69 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/double_const.py | from test.support import TestFailed
# A test for SF bug 422177: manifest float constants varied way too much in
# precision depending on whether Python was loading a module for the first
# time, or reloading it from a precompiled .pyc. The "expected" failure
# mode is that when test_import imports this after all .pyc files have been
# erased, it passes, but when test_import imports this from
# double_const.pyc, it fails. This indicates a woeful loss of precision in
# the marshal format for doubles. It's also possible that repr() doesn't
# produce enough digits to get reasonable precision for this box.
PI = 3.14159265358979324
TWOPI = 6.28318530717958648
PI_str = "3.14159265358979324"
TWOPI_str = "6.28318530717958648"
# Verify that the double x is within a few bits of eval(x_str).
def check_ok(x, x_str):
assert x > 0.0
x2 = eval(x_str)
assert x2 > 0.0
diff = abs(x - x2)
# If diff is no larger than 3 ULP (wrt x2), then diff/8 is no larger
# than 0.375 ULP, so adding diff/8 to x2 should have no effect.
if x2 + (diff / 8.) != x2:
raise TestFailed("Manifest const %s lost too much precision " % x_str)
check_ok(PI, PI_str)
check_ok(TWOPI, TWOPI_str)
| 1,212 | 31 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_stringprep.py | # To fully test this module, we would need a copy of the stringprep tables.
# Since we don't have them, this test checks only a few code points.
import unittest
from stringprep import *
class StringprepTests(unittest.TestCase):
def test(self):
self.assertTrue(in_table_a1("\u0221"))
self.assertFalse(in_table_a1("\u0222"))
self.assertTrue(in_table_b1("\u00ad"))
self.assertFalse(in_table_b1("\u00ae"))
self.assertTrue(map_table_b2("\u0041"), "\u0061")
self.assertTrue(map_table_b2("\u0061"), "\u0061")
self.assertTrue(map_table_b3("\u0041"), "\u0061")
self.assertTrue(map_table_b3("\u0061"), "\u0061")
self.assertTrue(in_table_c11("\u0020"))
self.assertFalse(in_table_c11("\u0021"))
self.assertTrue(in_table_c12("\u00a0"))
self.assertFalse(in_table_c12("\u00a1"))
self.assertTrue(in_table_c12("\u00a0"))
self.assertFalse(in_table_c12("\u00a1"))
self.assertTrue(in_table_c11_c12("\u00a0"))
self.assertFalse(in_table_c11_c12("\u00a1"))
self.assertTrue(in_table_c21("\u001f"))
self.assertFalse(in_table_c21("\u0020"))
self.assertTrue(in_table_c22("\u009f"))
self.assertFalse(in_table_c22("\u00a0"))
self.assertTrue(in_table_c21_c22("\u009f"))
self.assertFalse(in_table_c21_c22("\u00a0"))
self.assertTrue(in_table_c3("\ue000"))
self.assertFalse(in_table_c3("\uf900"))
self.assertTrue(in_table_c4("\uffff"))
self.assertFalse(in_table_c4("\u0000"))
self.assertTrue(in_table_c5("\ud800"))
self.assertFalse(in_table_c5("\ud7ff"))
self.assertTrue(in_table_c6("\ufff9"))
self.assertFalse(in_table_c6("\ufffe"))
self.assertTrue(in_table_c7("\u2ff0"))
self.assertFalse(in_table_c7("\u2ffc"))
self.assertTrue(in_table_c8("\u0340"))
self.assertFalse(in_table_c8("\u0342"))
# C.9 is not in the bmp
# self.assertTrue(in_table_c9(u"\U000E0001"))
# self.assertFalse(in_table_c8(u"\U000E0002"))
self.assertTrue(in_table_d1("\u05be"))
self.assertFalse(in_table_d1("\u05bf"))
self.assertTrue(in_table_d2("\u0041"))
self.assertFalse(in_table_d2("\u0040"))
# This would generate a hash of all predicates. However, running
# it is quite expensive, and only serves to detect changes in the
# unicode database. Instead, stringprep.py asserts the version of
# the database.
# import hashlib
# predicates = [k for k in dir(stringprep) if k.startswith("in_table")]
# predicates.sort()
# for p in predicates:
# f = getattr(stringprep, p)
# # Collect all BMP code points
# data = ["0"] * 0x10000
# for i in range(0x10000):
# if f(unichr(i)):
# data[i] = "1"
# data = "".join(data)
# h = hashlib.sha1()
# h.update(data)
# print p, h.hexdigest()
if __name__ == '__main__':
unittest.main()
| 3,113 | 93 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_isinstance.py | # Tests some corner cases with isinstance() and issubclass(). While these
# tests use new style classes and properties, they actually do whitebox
# testing of error conditions uncovered when using extension types.
import unittest
import sys
import cosmo
class TestIsInstanceExceptions(unittest.TestCase):
# Test to make sure that an AttributeError when accessing the instance's
# class's bases is masked. This was actually a bug in Python 2.2 and
# 2.2.1 where the exception wasn't caught but it also wasn't being cleared
# (leading to an "undetected error" in the debug build). Set up is,
# isinstance(inst, cls) where:
#
# - cls isn't a type, or a tuple
# - cls has a __bases__ attribute
# - inst has a __class__ attribute
# - inst.__class__ as no __bases__ attribute
#
# Sounds complicated, I know, but this mimics a situation where an
# extension type raises an AttributeError when its __bases__ attribute is
# gotten. In that case, isinstance() should return False.
def test_class_has_no_bases(self):
class I(object):
def getclass(self):
# This must return an object that has no __bases__ attribute
return None
__class__ = property(getclass)
class C(object):
def getbases(self):
return ()
__bases__ = property(getbases)
self.assertEqual(False, isinstance(I(), C()))
# Like above except that inst.__class__.__bases__ raises an exception
# other than AttributeError
def test_bases_raises_other_than_attribute_error(self):
class E(object):
def getbases(self):
raise RuntimeError
__bases__ = property(getbases)
class I(object):
def getclass(self):
return E()
__class__ = property(getclass)
class C(object):
def getbases(self):
return ()
__bases__ = property(getbases)
self.assertRaises(RuntimeError, isinstance, I(), C())
# Here's a situation where getattr(cls, '__bases__') raises an exception.
# If that exception is not AttributeError, it should not get masked
def test_dont_mask_non_attribute_error(self):
class I: pass
class C(object):
def getbases(self):
raise RuntimeError
__bases__ = property(getbases)
self.assertRaises(RuntimeError, isinstance, I(), C())
# Like above, except that getattr(cls, '__bases__') raises an
# AttributeError, which /should/ get masked as a TypeError
def test_mask_attribute_error(self):
class I: pass
class C(object):
def getbases(self):
raise AttributeError
__bases__ = property(getbases)
self.assertRaises(TypeError, isinstance, I(), C())
# check that we don't mask non AttributeErrors
# see: http://bugs.python.org/issue1574217
def test_isinstance_dont_mask_non_attribute_error(self):
class C(object):
def getclass(self):
raise RuntimeError
__class__ = property(getclass)
c = C()
self.assertRaises(RuntimeError, isinstance, c, bool)
# test another code path
class D: pass
self.assertRaises(RuntimeError, isinstance, c, D)
# These tests are similar to above, but tickle certain code paths in
# issubclass() instead of isinstance() -- really PyObject_IsSubclass()
# vs. PyObject_IsInstance().
class TestIsSubclassExceptions(unittest.TestCase):
def test_dont_mask_non_attribute_error(self):
class C(object):
def getbases(self):
raise RuntimeError
__bases__ = property(getbases)
class S(C): pass
self.assertRaises(RuntimeError, issubclass, C(), S())
def test_mask_attribute_error(self):
class C(object):
def getbases(self):
raise AttributeError
__bases__ = property(getbases)
class S(C): pass
self.assertRaises(TypeError, issubclass, C(), S())
# Like above, but test the second branch, where the __bases__ of the
# second arg (the cls arg) is tested. This means the first arg must
# return a valid __bases__, and it's okay for it to be a normal --
# unrelated by inheritance -- class.
def test_dont_mask_non_attribute_error_in_cls_arg(self):
class B: pass
class C(object):
def getbases(self):
raise RuntimeError
__bases__ = property(getbases)
self.assertRaises(RuntimeError, issubclass, B, C())
def test_mask_attribute_error_in_cls_arg(self):
class B: pass
class C(object):
def getbases(self):
raise AttributeError
__bases__ = property(getbases)
self.assertRaises(TypeError, issubclass, B, C())
# meta classes for creating abstract classes and instances
class AbstractClass(object):
def __init__(self, bases):
self.bases = bases
def getbases(self):
return self.bases
__bases__ = property(getbases)
def __call__(self):
return AbstractInstance(self)
class AbstractInstance(object):
def __init__(self, klass):
self.klass = klass
def getclass(self):
return self.klass
__class__ = property(getclass)
# abstract classes
AbstractSuper = AbstractClass(bases=())
AbstractChild = AbstractClass(bases=(AbstractSuper,))
# normal classes
class Super:
pass
class Child(Super):
pass
# new-style classes
class NewSuper(object):
pass
class NewChild(NewSuper):
pass
class TestIsInstanceIsSubclass(unittest.TestCase):
# Tests to ensure that isinstance and issubclass work on abstract
# classes and instances. Before the 2.2 release, TypeErrors were
# raised when boolean values should have been returned. The bug was
# triggered by mixing 'normal' classes and instances were with
# 'abstract' classes and instances. This case tries to test all
# combinations.
def test_isinstance_normal(self):
# normal instances
self.assertEqual(True, isinstance(Super(), Super))
self.assertEqual(False, isinstance(Super(), Child))
self.assertEqual(False, isinstance(Super(), AbstractSuper))
self.assertEqual(False, isinstance(Super(), AbstractChild))
self.assertEqual(True, isinstance(Child(), Super))
self.assertEqual(False, isinstance(Child(), AbstractSuper))
def test_isinstance_abstract(self):
# abstract instances
self.assertEqual(True, isinstance(AbstractSuper(), AbstractSuper))
self.assertEqual(False, isinstance(AbstractSuper(), AbstractChild))
self.assertEqual(False, isinstance(AbstractSuper(), Super))
self.assertEqual(False, isinstance(AbstractSuper(), Child))
self.assertEqual(True, isinstance(AbstractChild(), AbstractChild))
self.assertEqual(True, isinstance(AbstractChild(), AbstractSuper))
self.assertEqual(False, isinstance(AbstractChild(), Super))
self.assertEqual(False, isinstance(AbstractChild(), Child))
def test_subclass_normal(self):
# normal classes
self.assertEqual(True, issubclass(Super, Super))
self.assertEqual(False, issubclass(Super, AbstractSuper))
self.assertEqual(False, issubclass(Super, Child))
self.assertEqual(True, issubclass(Child, Child))
self.assertEqual(True, issubclass(Child, Super))
self.assertEqual(False, issubclass(Child, AbstractSuper))
def test_subclass_abstract(self):
# abstract classes
self.assertEqual(True, issubclass(AbstractSuper, AbstractSuper))
self.assertEqual(False, issubclass(AbstractSuper, AbstractChild))
self.assertEqual(False, issubclass(AbstractSuper, Child))
self.assertEqual(True, issubclass(AbstractChild, AbstractChild))
self.assertEqual(True, issubclass(AbstractChild, AbstractSuper))
self.assertEqual(False, issubclass(AbstractChild, Super))
self.assertEqual(False, issubclass(AbstractChild, Child))
def test_subclass_tuple(self):
# test with a tuple as the second argument classes
self.assertEqual(True, issubclass(Child, (Child,)))
self.assertEqual(True, issubclass(Child, (Super,)))
self.assertEqual(False, issubclass(Super, (Child,)))
self.assertEqual(True, issubclass(Super, (Child, Super)))
self.assertEqual(False, issubclass(Child, ()))
self.assertEqual(True, issubclass(Super, (Child, (Super,))))
self.assertEqual(True, issubclass(NewChild, (NewChild,)))
self.assertEqual(True, issubclass(NewChild, (NewSuper,)))
self.assertEqual(False, issubclass(NewSuper, (NewChild,)))
self.assertEqual(True, issubclass(NewSuper, (NewChild, NewSuper)))
self.assertEqual(False, issubclass(NewChild, ()))
self.assertEqual(True, issubclass(NewSuper, (NewChild, (NewSuper,))))
self.assertEqual(True, issubclass(int, (int, (float, int))))
self.assertEqual(True, issubclass(str, (str, (Child, NewChild, str))))
@unittest.skipUnless(cosmo.MODE == "dbg", "disabled recursion checking")
def test_subclass_recursion_limit(self):
# make sure that issubclass raises RecursionError before the C stack is
# blown
self.assertRaises(RecursionError, blowstack, issubclass, str, str)
@unittest.skipUnless(cosmo.MODE == "dbg", "disabled recursion checking")
def test_isinstance_recursion_limit(self):
# make sure that issubclass raises RecursionError before the C stack is
# blown
self.assertRaises(RecursionError, blowstack, isinstance, '', str)
def blowstack(fxn, arg, compare_to):
# Make sure that calling isinstance with a deeply nested tuple for its
# argument will raise RecursionError eventually.
tuple_arg = (compare_to,)
for cnt in range(sys.getrecursionlimit()+5):
tuple_arg = (tuple_arg,)
fxn(arg, tuple_arg)
if __name__ == '__main__':
unittest.main()
| 10,175 | 284 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_eof.py | """test script for a few new invalid token catches"""
import unittest
from test import support
class EOFTestCase(unittest.TestCase):
def test_EOFC(self):
expect = "EOL while scanning string literal (<string>, line 1)"
try:
eval("""'this is a test\
""")
except SyntaxError as msg:
self.assertEqual(str(msg), expect)
else:
raise support.TestFailed
def test_EOFS(self):
expect = ("EOF while scanning triple-quoted string literal "
"(<string>, line 1)")
try:
eval("""'''this is a test""")
except SyntaxError as msg:
self.assertEqual(str(msg), expect)
else:
raise support.TestFailed
if __name__ == "__main__":
unittest.main()
| 803 | 29 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/inspect_fodder.py | # line 1
'A module docstring.'
import sys, inspect
# line 5
# line 7
def spam(a, b, c, d=3, e=4, f=5, *g, **h):
eggs(b + d, c + f)
# line 11
def eggs(x, y):
"A docstring."
global fr, st
fr = inspect.currentframe()
st = inspect.stack()
p = x
q = y / 0
# line 20
class StupidGit:
"""A longer,
indented
docstring."""
# line 27
def abuse(self, a, b, c):
"""Another
\tdocstring
containing
\ttabs
\t
"""
self.argue(a, b, c)
# line 40
def argue(self, a, b, c):
try:
spam(a, b, c)
except:
self.ex = sys.exc_info()
self.tr = inspect.trace()
@property
def contradiction(self):
'The automatic gainsaying.'
pass
# line 53
class MalodorousPervert(StupidGit):
def abuse(self, a, b, c):
pass
@property
def contradiction(self):
pass
Tit = MalodorousPervert
class ParrotDroppings:
pass
class FesteringGob(MalodorousPervert, ParrotDroppings):
def abuse(self, a, b, c):
pass
@property
def contradiction(self):
pass
async def lobbest(grenade):
pass
currentframe = inspect.currentframe()
try:
raise Exception()
except:
tb = sys.exc_info()[2]
| 1,268 | 83 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_pty.py | from test.support import verbose, import_module, reap_children
# Skip these tests if termios is not available
import_module('termios')
import errno
import pty
import os
import sys
import select
import signal
import socket
import io # readline
import unittest
TEST_STRING_1 = b"I wish to buy a fish license.\n"
TEST_STRING_2 = b"For my pet fish, Eric.\n"
if verbose:
def debug(msg):
print(msg)
else:
def debug(msg):
pass
# Note that os.read() is nondeterministic so we need to be very careful
# to make the test suite deterministic. A normal call to os.read() may
# give us less than expected.
#
# Beware, on my Linux system, if I put 'foo\n' into a terminal fd, I get
# back 'foo\r\n' at the other end. The behavior depends on the termios
# setting. The newline translation may be OS-specific. To make the
# test suite deterministic and OS-independent, the functions _readline
# and normalize_output can be used.
def normalize_output(data):
# Some operating systems do conversions on newline. We could possibly
# fix that by doing the appropriate termios.tcsetattr()s. I couldn't
# figure out the right combo on Tru64 and I don't have an IRIX box.
# So just normalize the output and doc the problem O/Ses by allowing
# certain combinations for some platforms, but avoid allowing other
# differences (like extra whitespace, trailing garbage, etc.)
# This is about the best we can do without getting some feedback
# from someone more knowledgable.
# OSF/1 (Tru64) apparently turns \n into \r\r\n.
if data.endswith(b'\r\r\n'):
return data.replace(b'\r\r\n', b'\n')
# IRIX apparently turns \n into \r\n.
if data.endswith(b'\r\n'):
return data.replace(b'\r\n', b'\n')
return data
def _readline(fd):
"""Read one line. May block forever if no newline is read."""
reader = io.FileIO(fd, mode='rb', closefd=False)
return reader.readline()
# Marginal testing of pty suite. Cannot do extensive 'do or fail' testing
# because pty code is not too portable.
# XXX(nnorwitz): these tests leak fds when there is an error.
class PtyTest(unittest.TestCase):
def setUp(self):
# isatty() and close() can hang on some platforms. Set an alarm
# before running the test to make sure we don't hang forever.
old_alarm = signal.signal(signal.SIGALRM, self.handle_sig)
self.addCleanup(signal.signal, signal.SIGALRM, old_alarm)
self.addCleanup(signal.alarm, 0)
signal.alarm(10)
def handle_sig(self, sig, frame):
self.fail("isatty hung")
def test_basic(self):
try:
debug("Calling master_open()")
master_fd, slave_name = pty.master_open()
debug("Got master_fd '%d', slave_name '%s'" %
(master_fd, slave_name))
debug("Calling slave_open(%r)" % (slave_name,))
slave_fd = pty.slave_open(slave_name)
debug("Got slave_fd '%d'" % slave_fd)
except OSError:
# " An optional feature could not be imported " ... ?
raise unittest.SkipTest("Pseudo-terminals (seemingly) not functional.")
self.assertTrue(os.isatty(slave_fd), 'slave_fd is not a tty')
# Solaris requires reading the fd before anything is returned.
# My guess is that since we open and close the slave fd
# in master_open(), we need to read the EOF.
# Ensure the fd is non-blocking in case there's nothing to read.
blocking = os.get_blocking(master_fd)
try:
os.set_blocking(master_fd, False)
try:
s1 = os.read(master_fd, 1024)
self.assertEqual(b'', s1)
except OSError as e:
if e.errno != errno.EAGAIN:
raise
finally:
# Restore the original flags.
os.set_blocking(master_fd, blocking)
debug("Writing to slave_fd")
os.write(slave_fd, TEST_STRING_1)
s1 = _readline(master_fd)
self.assertEqual(b'I wish to buy a fish license.\n',
normalize_output(s1))
debug("Writing chunked output")
os.write(slave_fd, TEST_STRING_2[:5])
os.write(slave_fd, TEST_STRING_2[5:])
s2 = _readline(master_fd)
self.assertEqual(b'For my pet fish, Eric.\n', normalize_output(s2))
os.close(slave_fd)
os.close(master_fd)
def test_fork(self):
debug("calling pty.fork()")
pid, master_fd = pty.fork()
if pid == pty.CHILD:
# stdout should be connected to a tty.
if not os.isatty(1):
debug("Child's fd 1 is not a tty?!")
os._exit(3)
# After pty.fork(), the child should already be a session leader.
# (on those systems that have that concept.)
debug("In child, calling os.setsid()")
try:
os.setsid()
except OSError:
# Good, we already were session leader
debug("Good: OSError was raised.")
pass
except AttributeError:
# Have pty, but not setsid()?
debug("No setsid() available?")
pass
except:
# We don't want this error to propagate, escaping the call to
# os._exit() and causing very peculiar behavior in the calling
# regrtest.py !
# Note: could add traceback printing here.
debug("An unexpected error was raised.")
os._exit(1)
else:
debug("os.setsid() succeeded! (bad!)")
os._exit(2)
os._exit(4)
else:
debug("Waiting for child (%d) to finish." % pid)
# In verbose mode, we have to consume the debug output from the
# child or the child will block, causing this test to hang in the
# parent's waitpid() call. The child blocks after a
# platform-dependent amount of data is written to its fd. On
# Linux 2.6, it's 4000 bytes and the child won't block, but on OS
# X even the small writes in the child above will block it. Also
# on Linux, the read() will raise an OSError (input/output error)
# when it tries to read past the end of the buffer but the child's
# already exited, so catch and discard those exceptions. It's not
# worth checking for EIO.
while True:
try:
data = os.read(master_fd, 80)
except OSError:
break
if not data:
break
sys.stdout.write(str(data.replace(b'\r\n', b'\n'),
encoding='ascii'))
##line = os.read(master_fd, 80)
##lines = line.replace('\r\n', '\n').split('\n')
##if False and lines != ['In child, calling os.setsid()',
## 'Good: OSError was raised.', '']:
## raise TestFailed("Unexpected output from child: %r" % line)
(pid, status) = os.waitpid(pid, 0)
res = status >> 8
debug("Child (%d) exited with status %d (%d)." % (pid, res, status))
if res == 1:
self.fail("Child raised an unexpected exception in os.setsid()")
elif res == 2:
self.fail("pty.fork() failed to make child a session leader.")
elif res == 3:
self.fail("Child spawned by pty.fork() did not have a tty as stdout")
elif res != 4:
self.fail("pty.fork() failed for unknown reasons.")
##debug("Reading from master_fd now that the child has exited")
##try:
## s1 = os.read(master_fd, 1024)
##except OSError:
## pass
##else:
## raise TestFailed("Read from master_fd did not raise exception")
os.close(master_fd)
# pty.fork() passed.
class SmallPtyTests(unittest.TestCase):
"""These tests don't spawn children or hang."""
def setUp(self):
self.orig_stdin_fileno = pty.STDIN_FILENO
self.orig_stdout_fileno = pty.STDOUT_FILENO
self.orig_pty_select = pty.select
self.fds = [] # A list of file descriptors to close.
self.files = []
self.select_rfds_lengths = []
self.select_rfds_results = []
def tearDown(self):
pty.STDIN_FILENO = self.orig_stdin_fileno
pty.STDOUT_FILENO = self.orig_stdout_fileno
pty.select = self.orig_pty_select
for file in self.files:
try:
file.close()
except OSError:
pass
for fd in self.fds:
try:
os.close(fd)
except OSError:
pass
def _pipe(self):
pipe_fds = os.pipe()
self.fds.extend(pipe_fds)
return pipe_fds
def _socketpair(self):
socketpair = socket.socketpair()
self.files.extend(socketpair)
return socketpair
def _mock_select(self, rfds, wfds, xfds):
# This will raise IndexError when no more expected calls exist.
self.assertEqual(self.select_rfds_lengths.pop(0), len(rfds))
return self.select_rfds_results.pop(0), [], []
def test__copy_to_each(self):
"""Test the normal data case on both master_fd and stdin."""
read_from_stdout_fd, mock_stdout_fd = self._pipe()
pty.STDOUT_FILENO = mock_stdout_fd
mock_stdin_fd, write_to_stdin_fd = self._pipe()
pty.STDIN_FILENO = mock_stdin_fd
socketpair = self._socketpair()
masters = [s.fileno() for s in socketpair]
# Feed data. Smaller than PIPEBUF. These writes will not block.
os.write(masters[1], b'from master')
os.write(write_to_stdin_fd, b'from stdin')
# Expect two select calls, the last one will cause IndexError
pty.select = self._mock_select
self.select_rfds_lengths.append(2)
self.select_rfds_results.append([mock_stdin_fd, masters[0]])
self.select_rfds_lengths.append(2)
with self.assertRaises(IndexError):
pty._copy(masters[0])
# Test that the right data went to the right places.
rfds = select.select([read_from_stdout_fd, masters[1]], [], [], 0)[0]
self.assertEqual([read_from_stdout_fd, masters[1]], rfds)
self.assertEqual(os.read(read_from_stdout_fd, 20), b'from master')
self.assertEqual(os.read(masters[1], 20), b'from stdin')
def test__copy_eof_on_all(self):
"""Test the empty read EOF case on both master_fd and stdin."""
read_from_stdout_fd, mock_stdout_fd = self._pipe()
pty.STDOUT_FILENO = mock_stdout_fd
mock_stdin_fd, write_to_stdin_fd = self._pipe()
pty.STDIN_FILENO = mock_stdin_fd
socketpair = self._socketpair()
masters = [s.fileno() for s in socketpair]
socketpair[1].close()
os.close(write_to_stdin_fd)
# Expect two select calls, the last one will cause IndexError
pty.select = self._mock_select
self.select_rfds_lengths.append(2)
self.select_rfds_results.append([mock_stdin_fd, masters[0]])
# We expect that both fds were removed from the fds list as they
# both encountered an EOF before the second select call.
self.select_rfds_lengths.append(0)
with self.assertRaises(IndexError):
pty._copy(masters[0])
def tearDownModule():
reap_children()
if __name__ == "__main__":
unittest.main()
| 11,761 | 314 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/mapping_tests.py | # tests common to dict and UserDict
import unittest
import collections
import sys
import cosmo
class BasicTestMappingProtocol(unittest.TestCase):
# This base class can be used to check that an object conforms to the
# mapping protocol
# Functions that can be useful to override to adapt to dictionary
# semantics
type2test = None # which class is being tested (overwrite in subclasses)
def _reference(self):
"""Return a dictionary of values which are invariant by storage
in the object under test."""
return {"1": "2", "key1":"value1", "key2":(1,2,3)}
def _empty_mapping(self):
"""Return an empty mapping object"""
return self.type2test()
def _full_mapping(self, data):
"""Return a mapping object with the value contained in data
dictionary"""
x = self._empty_mapping()
for key, value in data.items():
x[key] = value
return x
def __init__(self, *args, **kw):
unittest.TestCase.__init__(self, *args, **kw)
self.reference = self._reference().copy()
# A (key, value) pair not in the mapping
key, value = self.reference.popitem()
self.other = {key:value}
# A (key, value) pair in the mapping
key, value = self.reference.popitem()
self.inmapping = {key:value}
self.reference[key] = value
def test_read(self):
# Test for read only operations on mapping
p = self._empty_mapping()
p1 = dict(p) #workaround for singleton objects
d = self._full_mapping(self.reference)
if d is p:
p = p1
#Indexing
for key, value in self.reference.items():
self.assertEqual(d[key], value)
knownkey = list(self.other.keys())[0]
self.assertRaises(KeyError, lambda:d[knownkey])
#len
self.assertEqual(len(p), 0)
self.assertEqual(len(d), len(self.reference))
#__contains__
for k in self.reference:
self.assertIn(k, d)
for k in self.other:
self.assertNotIn(k, d)
#cmp
self.assertEqual(p, p)
self.assertEqual(d, d)
self.assertNotEqual(p, d)
self.assertNotEqual(d, p)
#bool
if p: self.fail("Empty mapping must compare to False")
if not d: self.fail("Full mapping must compare to True")
# keys(), items(), iterkeys() ...
def check_iterandlist(iter, lst, ref):
self.assertTrue(hasattr(iter, '__next__'))
self.assertTrue(hasattr(iter, '__iter__'))
x = list(iter)
self.assertTrue(set(x)==set(lst)==set(ref))
check_iterandlist(iter(d.keys()), list(d.keys()),
self.reference.keys())
check_iterandlist(iter(d), list(d.keys()), self.reference.keys())
check_iterandlist(iter(d.values()), list(d.values()),
self.reference.values())
check_iterandlist(iter(d.items()), list(d.items()),
self.reference.items())
#get
key, value = next(iter(d.items()))
knownkey, knownvalue = next(iter(self.other.items()))
self.assertEqual(d.get(key, knownvalue), value)
self.assertEqual(d.get(knownkey, knownvalue), knownvalue)
self.assertNotIn(knownkey, d)
def test_write(self):
# Test for write operations on mapping
p = self._empty_mapping()
#Indexing
for key, value in self.reference.items():
p[key] = value
self.assertEqual(p[key], value)
for key in self.reference.keys():
del p[key]
self.assertRaises(KeyError, lambda:p[key])
p = self._empty_mapping()
#update
p.update(self.reference)
self.assertEqual(dict(p), self.reference)
items = list(p.items())
p = self._empty_mapping()
p.update(items)
self.assertEqual(dict(p), self.reference)
d = self._full_mapping(self.reference)
#setdefault
key, value = next(iter(d.items()))
knownkey, knownvalue = next(iter(self.other.items()))
self.assertEqual(d.setdefault(key, knownvalue), value)
self.assertEqual(d[key], value)
self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue)
self.assertEqual(d[knownkey], knownvalue)
#pop
self.assertEqual(d.pop(knownkey), knownvalue)
self.assertNotIn(knownkey, d)
self.assertRaises(KeyError, d.pop, knownkey)
default = 909
d[knownkey] = knownvalue
self.assertEqual(d.pop(knownkey, default), knownvalue)
self.assertNotIn(knownkey, d)
self.assertEqual(d.pop(knownkey, default), default)
#popitem
key, value = d.popitem()
self.assertNotIn(key, d)
self.assertEqual(value, self.reference[key])
p=self._empty_mapping()
self.assertRaises(KeyError, p.popitem)
def test_constructor(self):
self.assertEqual(self._empty_mapping(), self._empty_mapping())
def test_bool(self):
self.assertTrue(not self._empty_mapping())
self.assertTrue(self.reference)
self.assertTrue(bool(self._empty_mapping()) is False)
self.assertTrue(bool(self.reference) is True)
def test_keys(self):
d = self._empty_mapping()
self.assertEqual(list(d.keys()), [])
d = self.reference
self.assertIn(list(self.inmapping.keys())[0], d.keys())
self.assertNotIn(list(self.other.keys())[0], d.keys())
self.assertRaises(TypeError, d.keys, None)
def test_values(self):
d = self._empty_mapping()
self.assertEqual(list(d.values()), [])
self.assertRaises(TypeError, d.values, None)
def test_items(self):
d = self._empty_mapping()
self.assertEqual(list(d.items()), [])
self.assertRaises(TypeError, d.items, None)
def test_len(self):
d = self._empty_mapping()
self.assertEqual(len(d), 0)
def test_getitem(self):
d = self.reference
self.assertEqual(d[list(self.inmapping.keys())[0]],
list(self.inmapping.values())[0])
self.assertRaises(TypeError, d.__getitem__)
def test_update(self):
# mapping argument
d = self._empty_mapping()
d.update(self.other)
self.assertEqual(list(d.items()), list(self.other.items()))
# No argument
d = self._empty_mapping()
d.update()
self.assertEqual(d, self._empty_mapping())
# item sequence
d = self._empty_mapping()
d.update(self.other.items())
self.assertEqual(list(d.items()), list(self.other.items()))
# Iterator
d = self._empty_mapping()
d.update(self.other.items())
self.assertEqual(list(d.items()), list(self.other.items()))
# FIXME: Doesn't work with UserDict
# self.assertRaises((TypeError, AttributeError), d.update, None)
self.assertRaises((TypeError, AttributeError), d.update, 42)
outerself = self
class SimpleUserDict:
def __init__(self):
self.d = outerself.reference
def keys(self):
return self.d.keys()
def __getitem__(self, i):
return self.d[i]
d.clear()
d.update(SimpleUserDict())
i1 = sorted(d.items())
i2 = sorted(self.reference.items())
self.assertEqual(i1, i2)
class Exc(Exception): pass
d = self._empty_mapping()
class FailingUserDict:
def keys(self):
raise Exc
self.assertRaises(Exc, d.update, FailingUserDict())
d.clear()
class FailingUserDict:
def keys(self):
class BogonIter:
def __init__(self):
self.i = 1
def __iter__(self):
return self
def __next__(self):
if self.i:
self.i = 0
return 'a'
raise Exc
return BogonIter()
def __getitem__(self, key):
return key
self.assertRaises(Exc, d.update, FailingUserDict())
class FailingUserDict:
def keys(self):
class BogonIter:
def __init__(self):
self.i = ord('a')
def __iter__(self):
return self
def __next__(self):
if self.i <= ord('z'):
rtn = chr(self.i)
self.i += 1
return rtn
raise StopIteration
return BogonIter()
def __getitem__(self, key):
raise Exc
self.assertRaises(Exc, d.update, FailingUserDict())
d = self._empty_mapping()
class badseq(object):
def __iter__(self):
return self
def __next__(self):
raise Exc()
self.assertRaises(Exc, d.update, badseq())
self.assertRaises(ValueError, d.update, [(1, 2, 3)])
# no test_fromkeys or test_copy as both os.environ and selves don't support it
def test_get(self):
d = self._empty_mapping()
self.assertTrue(d.get(list(self.other.keys())[0]) is None)
self.assertEqual(d.get(list(self.other.keys())[0], 3), 3)
d = self.reference
self.assertTrue(d.get(list(self.other.keys())[0]) is None)
self.assertEqual(d.get(list(self.other.keys())[0], 3), 3)
self.assertEqual(d.get(list(self.inmapping.keys())[0]),
list(self.inmapping.values())[0])
self.assertEqual(d.get(list(self.inmapping.keys())[0], 3),
list(self.inmapping.values())[0])
self.assertRaises(TypeError, d.get)
self.assertRaises(TypeError, d.get, None, None, None)
def test_setdefault(self):
d = self._empty_mapping()
self.assertRaises(TypeError, d.setdefault)
def test_popitem(self):
d = self._empty_mapping()
self.assertRaises(KeyError, d.popitem)
self.assertRaises(TypeError, d.popitem, 42)
def test_pop(self):
d = self._empty_mapping()
k, v = list(self.inmapping.items())[0]
d[k] = v
self.assertRaises(KeyError, d.pop, list(self.other.keys())[0])
self.assertEqual(d.pop(k), v)
self.assertEqual(len(d), 0)
self.assertRaises(KeyError, d.pop, k)
class TestMappingProtocol(BasicTestMappingProtocol):
def test_constructor(self):
BasicTestMappingProtocol.test_constructor(self)
self.assertTrue(self._empty_mapping() is not self._empty_mapping())
self.assertEqual(self.type2test(x=1, y=2), {"x": 1, "y": 2})
def test_bool(self):
BasicTestMappingProtocol.test_bool(self)
self.assertTrue(not self._empty_mapping())
self.assertTrue(self._full_mapping({"x": "y"}))
self.assertTrue(bool(self._empty_mapping()) is False)
self.assertTrue(bool(self._full_mapping({"x": "y"})) is True)
def test_keys(self):
BasicTestMappingProtocol.test_keys(self)
d = self._empty_mapping()
self.assertEqual(list(d.keys()), [])
d = self._full_mapping({'a': 1, 'b': 2})
k = d.keys()
self.assertIn('a', k)
self.assertIn('b', k)
self.assertNotIn('c', k)
def test_values(self):
BasicTestMappingProtocol.test_values(self)
d = self._full_mapping({1:2})
self.assertEqual(list(d.values()), [2])
def test_items(self):
BasicTestMappingProtocol.test_items(self)
d = self._full_mapping({1:2})
self.assertEqual(list(d.items()), [(1, 2)])
def test_contains(self):
d = self._empty_mapping()
self.assertNotIn('a', d)
self.assertTrue(not ('a' in d))
self.assertTrue('a' not in d)
d = self._full_mapping({'a': 1, 'b': 2})
self.assertIn('a', d)
self.assertIn('b', d)
self.assertNotIn('c', d)
self.assertRaises(TypeError, d.__contains__)
def test_len(self):
BasicTestMappingProtocol.test_len(self)
d = self._full_mapping({'a': 1, 'b': 2})
self.assertEqual(len(d), 2)
def test_getitem(self):
BasicTestMappingProtocol.test_getitem(self)
d = self._full_mapping({'a': 1, 'b': 2})
self.assertEqual(d['a'], 1)
self.assertEqual(d['b'], 2)
d['c'] = 3
d['a'] = 4
self.assertEqual(d['c'], 3)
self.assertEqual(d['a'], 4)
del d['b']
self.assertEqual(d, {'a': 4, 'c': 3})
self.assertRaises(TypeError, d.__getitem__)
def test_clear(self):
d = self._full_mapping({1:1, 2:2, 3:3})
d.clear()
self.assertEqual(d, {})
self.assertRaises(TypeError, d.clear, None)
def test_update(self):
BasicTestMappingProtocol.test_update(self)
# mapping argument
d = self._empty_mapping()
d.update({1:100})
d.update({2:20})
d.update({1:1, 2:2, 3:3})
self.assertEqual(d, {1:1, 2:2, 3:3})
# no argument
d.update()
self.assertEqual(d, {1:1, 2:2, 3:3})
# keyword arguments
d = self._empty_mapping()
d.update(x=100)
d.update(y=20)
d.update(x=1, y=2, z=3)
self.assertEqual(d, {"x":1, "y":2, "z":3})
# item sequence
d = self._empty_mapping()
d.update([("x", 100), ("y", 20)])
self.assertEqual(d, {"x":100, "y":20})
# Both item sequence and keyword arguments
d = self._empty_mapping()
d.update([("x", 100), ("y", 20)], x=1, y=2)
self.assertEqual(d, {"x":1, "y":2})
# iterator
d = self._full_mapping({1:3, 2:4})
d.update(self._full_mapping({1:2, 3:4, 5:6}).items())
self.assertEqual(d, {1:2, 2:4, 3:4, 5:6})
class SimpleUserDict:
def __init__(self):
self.d = {1:1, 2:2, 3:3}
def keys(self):
return self.d.keys()
def __getitem__(self, i):
return self.d[i]
d.clear()
d.update(SimpleUserDict())
self.assertEqual(d, {1:1, 2:2, 3:3})
def test_fromkeys(self):
self.assertEqual(self.type2test.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
d = self._empty_mapping()
self.assertTrue(not(d.fromkeys('abc') is d))
self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0})
self.assertEqual(d.fromkeys([]), {})
def g():
yield 1
self.assertEqual(d.fromkeys(g()), {1:None})
self.assertRaises(TypeError, {}.fromkeys, 3)
class dictlike(self.type2test): pass
self.assertEqual(dictlike.fromkeys('a'), {'a':None})
self.assertEqual(dictlike().fromkeys('a'), {'a':None})
self.assertTrue(dictlike.fromkeys('a').__class__ is dictlike)
self.assertTrue(dictlike().fromkeys('a').__class__ is dictlike)
self.assertTrue(type(dictlike.fromkeys('a')) is dictlike)
class mydict(self.type2test):
def __new__(cls):
return collections.UserDict()
ud = mydict.fromkeys('ab')
self.assertEqual(ud, {'a':None, 'b':None})
self.assertIsInstance(ud, collections.UserDict)
self.assertRaises(TypeError, dict.fromkeys)
class Exc(Exception): pass
class baddict1(self.type2test):
def __init__(self):
raise Exc()
self.assertRaises(Exc, baddict1.fromkeys, [1])
class BadSeq(object):
def __iter__(self):
return self
def __next__(self):
raise Exc()
self.assertRaises(Exc, self.type2test.fromkeys, BadSeq())
class baddict2(self.type2test):
def __setitem__(self, key, value):
raise Exc()
self.assertRaises(Exc, baddict2.fromkeys, [1])
def test_copy(self):
d = self._full_mapping({1:1, 2:2, 3:3})
self.assertEqual(d.copy(), {1:1, 2:2, 3:3})
d = self._empty_mapping()
self.assertEqual(d.copy(), d)
self.assertIsInstance(d.copy(), d.__class__)
self.assertRaises(TypeError, d.copy, None)
def test_get(self):
BasicTestMappingProtocol.test_get(self)
d = self._empty_mapping()
self.assertTrue(d.get('c') is None)
self.assertEqual(d.get('c', 3), 3)
d = self._full_mapping({'a' : 1, 'b' : 2})
self.assertTrue(d.get('c') is None)
self.assertEqual(d.get('c', 3), 3)
self.assertEqual(d.get('a'), 1)
self.assertEqual(d.get('a', 3), 1)
def test_setdefault(self):
BasicTestMappingProtocol.test_setdefault(self)
d = self._empty_mapping()
self.assertTrue(d.setdefault('key0') is None)
d.setdefault('key0', [])
self.assertTrue(d.setdefault('key0') is None)
d.setdefault('key', []).append(3)
self.assertEqual(d['key'][0], 3)
d.setdefault('key', []).append(4)
self.assertEqual(len(d['key']), 2)
def test_popitem(self):
BasicTestMappingProtocol.test_popitem(self)
for copymode in -1, +1:
# -1: b has same structure as a
# +1: b is a.copy()
for log2size in range(12):
size = 2**log2size
a = self._empty_mapping()
b = self._empty_mapping()
for i in range(size):
a[repr(i)] = i
if copymode < 0:
b[repr(i)] = i
if copymode > 0:
b = a.copy()
for i in range(size):
ka, va = ta = a.popitem()
self.assertEqual(va, int(ka))
kb, vb = tb = b.popitem()
self.assertEqual(vb, int(kb))
self.assertTrue(not(copymode < 0 and ta != tb))
self.assertTrue(not a)
self.assertTrue(not b)
def test_pop(self):
BasicTestMappingProtocol.test_pop(self)
# Tests for pop with specified key
d = self._empty_mapping()
k, v = 'abc', 'def'
self.assertEqual(d.pop(k, v), v)
d[k] = v
self.assertEqual(d.pop(k, 1), v)
class TestHashMappingProtocol(TestMappingProtocol):
def test_getitem(self):
TestMappingProtocol.test_getitem(self)
class Exc(Exception): pass
class BadEq(object):
def __eq__(self, other):
raise Exc()
def __hash__(self):
return 24
d = self._empty_mapping()
d[BadEq()] = 42
self.assertRaises(KeyError, d.__getitem__, 23)
class BadHash(object):
fail = False
def __hash__(self):
if self.fail:
raise Exc()
else:
return 42
d = self._empty_mapping()
x = BadHash()
d[x] = 42
x.fail = True
self.assertRaises(Exc, d.__getitem__, x)
def test_fromkeys(self):
TestMappingProtocol.test_fromkeys(self)
class mydict(self.type2test):
def __new__(cls):
return collections.UserDict()
ud = mydict.fromkeys('ab')
self.assertEqual(ud, {'a':None, 'b':None})
self.assertIsInstance(ud, collections.UserDict)
def test_pop(self):
TestMappingProtocol.test_pop(self)
class Exc(Exception): pass
class BadHash(object):
fail = False
def __hash__(self):
if self.fail:
raise Exc()
else:
return 42
d = self._empty_mapping()
x = BadHash()
d[x] = 42
x.fail = True
self.assertRaises(Exc, d.pop, x)
def test_mutatingiteration(self):
d = self._empty_mapping()
d[1] = 1
try:
for i in d:
d[i+1] = 1
except RuntimeError:
pass
else:
self.fail("changing dict size during iteration doesn't raise Error")
def test_repr(self):
d = self._empty_mapping()
self.assertEqual(repr(d), '{}')
d[1] = 2
self.assertEqual(repr(d), '{1: 2}')
d = self._empty_mapping()
d[1] = d
self.assertEqual(repr(d), '{1: {...}}')
class Exc(Exception): pass
class BadRepr(object):
def __repr__(self):
raise Exc()
d = self._full_mapping({1: BadRepr()})
self.assertRaises(Exc, repr, d)
@unittest.skipUnless(cosmo.MODE == "dbg", "disabled recursion checking")
def test_repr_deep(self):
d = self._empty_mapping()
for i in range(sys.getrecursionlimit() + 100):
d0 = d
d = self._empty_mapping()
d[1] = d0
self.assertRaises(RecursionError, repr, d)
def test_eq(self):
self.assertEqual(self._empty_mapping(), self._empty_mapping())
self.assertEqual(self._full_mapping({1: 2}),
self._full_mapping({1: 2}))
class Exc(Exception): pass
class BadCmp(object):
def __eq__(self, other):
raise Exc()
def __hash__(self):
return 1
d1 = self._full_mapping({BadCmp(): 1})
d2 = self._full_mapping({1: 1})
self.assertRaises(Exc, lambda: BadCmp()==1)
self.assertRaises(Exc, lambda: d1==d2)
def test_setdefault(self):
TestMappingProtocol.test_setdefault(self)
class Exc(Exception): pass
class BadHash(object):
fail = False
def __hash__(self):
if self.fail:
raise Exc()
else:
return 42
d = self._empty_mapping()
x = BadHash()
d[x] = 42
x.fail = True
self.assertRaises(Exc, d.setdefault, x, [])
| 22,358 | 669 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_wait3.py | """This test checks for correct wait3() behavior.
"""
import os
import time
import unittest
from test.fork_wait import ForkWait
from test.support import reap_children
if not hasattr(os, 'fork'):
raise unittest.SkipTest("os.fork not defined")
if not hasattr(os, 'wait3'):
raise unittest.SkipTest("os.wait3 not defined")
class Wait3Test(ForkWait):
def wait_impl(self, cpid):
# This many iterations can be required, since some previously run
# tests (e.g. test_ctypes) could have spawned a lot of children
# very quickly.
deadline = time.monotonic() + 10.0
while time.monotonic() <= deadline:
# wait3() shouldn't hang, but some of the buildbots seem to hang
# in the forking tests. This is an attempt to fix the problem.
spid, status, rusage = os.wait3(os.WNOHANG)
if spid == cpid:
break
time.sleep(0.1)
self.assertEqual(spid, cpid)
self.assertEqual(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8))
self.assertTrue(rusage)
def tearDownModule():
reap_children()
if __name__ == "__main__":
unittest.main()
| 1,183 | 39 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_codecencodings_cn.py | #
# test_codecencodings_cn.py
# Codec encoding tests for PRC encodings.
#
from test import multibytecodec_support
import unittest
class Test_GB2312(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'gb2312'
tstring = multibytecodec_support.load_teststring('gb2312')
codectests = (
# invalid bytes
(b"abc\x81\x81\xc1\xc4", "strict", None),
(b"abc\xc8", "strict", None),
(b"abc\x81\x81\xc1\xc4", "replace", "abc\ufffd\ufffd\u804a"),
(b"abc\x81\x81\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\u804a\ufffd"),
(b"abc\x81\x81\xc1\xc4", "ignore", "abc\u804a"),
(b"\xc1\x64", "strict", None),
)
class Test_GBK(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'gbk'
tstring = multibytecodec_support.load_teststring('gbk')
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\u804a"),
(b"abc\x80\x80\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\u804a\ufffd"),
(b"abc\x80\x80\xc1\xc4", "ignore", "abc\u804a"),
(b"\x83\x34\x83\x31", "strict", None),
("\u30fb", "strict", None),
)
class Test_GB18030(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'gb18030'
tstring = multibytecodec_support.load_teststring('gb18030')
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\u804a"),
(b"abc\x80\x80\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\u804a\ufffd"),
(b"abc\x80\x80\xc1\xc4", "ignore", "abc\u804a"),
(b"abc\x84\x39\x84\x39\xc1\xc4", "replace", "abc\ufffd9\ufffd9\u804a"),
("\u30fb", "strict", b"\x819\xa79"),
(b"abc\x84\x32\x80\x80def", "replace", 'abc\ufffd2\ufffd\ufffddef'),
(b"abc\x81\x30\x81\x30def", "strict", 'abc\x80def'),
(b"abc\x86\x30\x81\x30def", "replace", 'abc\ufffd0\ufffd0def'),
# issue29990
(b"\xff\x30\x81\x30", "strict", None),
(b"\x81\x30\xff\x30", "strict", None),
(b"abc\x81\x39\xff\x39\xc1\xc4", "replace", "abc\ufffd\x39\ufffd\x39\u804a"),
(b"abc\xab\x36\xff\x30def", "replace", 'abc\ufffd\x36\ufffd\x30def'),
(b"abc\xbf\x38\xff\x32\xc1\xc4", "ignore", "abc\x38\x32\u804a"),
)
has_iso10646 = True
class Test_HZ(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'hz'
tstring = multibytecodec_support.load_teststring('hz')
codectests = (
# test '~\n' (3 lines)
(b'This sentence is in ASCII.\n'
b'The next sentence is in GB.~{<:Ky2;S{#,~}~\n'
b'~{NpJ)l6HK!#~}Bye.\n',
'strict',
'This sentence is in ASCII.\n'
'The next sentence is in GB.'
'\u5df1\u6240\u4e0d\u6b32\uff0c\u52ff\u65bd\u65bc\u4eba\u3002'
'Bye.\n'),
# test '~\n' (4 lines)
(b'This sentence is in ASCII.\n'
b'The next sentence is in GB.~\n'
b'~{<:Ky2;S{#,NpJ)l6HK!#~}~\n'
b'Bye.\n',
'strict',
'This sentence is in ASCII.\n'
'The next sentence is in GB.'
'\u5df1\u6240\u4e0d\u6b32\uff0c\u52ff\u65bd\u65bc\u4eba\u3002'
'Bye.\n'),
# invalid bytes
(b'ab~cd', 'replace', 'ab\uFFFDcd'),
(b'ab\xffcd', 'replace', 'ab\uFFFDcd'),
(b'ab~{\x81\x81\x41\x44~}cd', 'replace', 'ab\uFFFD\uFFFD\u804Acd'),
(b'ab~{\x41\x44~}cd', 'replace', 'ab\u804Acd'),
(b"ab~{\x79\x79\x41\x44~}cd", "replace", "ab\ufffd\ufffd\u804acd"),
# issue 30003
('ab~cd', 'strict', b'ab~~cd'), # escape ~
(b'~{Dc~~:C~}', 'strict', None), # ~~ only in ASCII mode
(b'~{Dc~\n:C~}', 'strict', None), # ~\n only in ASCII mode
)
if __name__ == "__main__":
unittest.main()
| 3,944 | 97 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_asynchat.py | # test asynchat
from test import support
# If this fails, the test will be skipped.
thread = support.import_module('_thread')
import asynchat
import asyncore
import errno
import socket
import sys
import time
import unittest
import unittest.mock
try:
import _thread
import threading
except ImportError:
threading = None
HOST = support.HOST
SERVER_QUIT = b'QUIT\n'
TIMEOUT = 3.0
if threading:
class echo_server(threading.Thread):
# parameter to determine the number of bytes passed back to the
# client each send
chunk_size = 1
def __init__(self, event):
threading.Thread.__init__(self)
self.event = event
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.port = support.bind_port(self.sock)
# This will be set if the client wants us to wait before echoing
# data back.
self.start_resend_event = None
def run(self):
self.sock.listen()
self.event.set()
conn, client = self.sock.accept()
self.buffer = b""
# collect data until quit message is seen
while SERVER_QUIT not in self.buffer:
data = conn.recv(1)
if not data:
break
self.buffer = self.buffer + data
# remove the SERVER_QUIT message
self.buffer = self.buffer.replace(SERVER_QUIT, b'')
if self.start_resend_event:
self.start_resend_event.wait()
# re-send entire set of collected data
try:
# this may fail on some tests, such as test_close_when_done,
# since the client closes the channel when it's done sending
while self.buffer:
n = conn.send(self.buffer[:self.chunk_size])
time.sleep(0.001)
self.buffer = self.buffer[n:]
except:
pass
conn.close()
self.sock.close()
class echo_client(asynchat.async_chat):
def __init__(self, terminator, server_port):
asynchat.async_chat.__init__(self)
self.contents = []
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((HOST, server_port))
self.set_terminator(terminator)
self.buffer = b""
def handle_connect(self):
pass
if sys.platform == 'darwin':
# select.poll returns a select.POLLHUP at the end of the tests
# on darwin, so just ignore it
def handle_expt(self):
pass
def collect_incoming_data(self, data):
self.buffer += data
def found_terminator(self):
self.contents.append(self.buffer)
self.buffer = b""
def start_echo_server():
event = threading.Event()
s = echo_server(event)
s.start()
event.wait()
event.clear()
time.sleep(0.01) # Give server time to start accepting.
return s, event
@unittest.skipUnless(threading, 'Threading required for this test.')
class TestAsynchat(unittest.TestCase):
usepoll = False
def setUp(self):
self._threads = support.threading_setup()
def tearDown(self):
support.threading_cleanup(*self._threads)
def line_terminator_check(self, term, server_chunk):
event = threading.Event()
s = echo_server(event)
s.chunk_size = server_chunk
s.start()
event.wait()
event.clear()
time.sleep(0.01) # Give server time to start accepting.
c = echo_client(term, s.port)
c.push(b"hello ")
c.push(b"world" + term)
c.push(b"I'm not dead yet!" + term)
c.push(SERVER_QUIT)
asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
s.join(timeout=TIMEOUT)
if s.is_alive():
self.fail("join() timed out")
self.assertEqual(c.contents, [b"hello world", b"I'm not dead yet!"])
# the line terminator tests below check receiving variously-sized
# chunks back from the server in order to exercise all branches of
# async_chat.handle_read
def test_line_terminator1(self):
# test one-character terminator
for l in (1, 2, 3):
self.line_terminator_check(b'\n', l)
def test_line_terminator2(self):
# test two-character terminator
for l in (1, 2, 3):
self.line_terminator_check(b'\r\n', l)
def test_line_terminator3(self):
# test three-character terminator
for l in (1, 2, 3):
self.line_terminator_check(b'qqq', l)
def numeric_terminator_check(self, termlen):
# Try reading a fixed number of bytes
s, event = start_echo_server()
c = echo_client(termlen, s.port)
data = b"hello world, I'm not dead yet!\n"
c.push(data)
c.push(SERVER_QUIT)
asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
s.join(timeout=TIMEOUT)
if s.is_alive():
self.fail("join() timed out")
self.assertEqual(c.contents, [data[:termlen]])
def test_numeric_terminator1(self):
# check that ints & longs both work (since type is
# explicitly checked in async_chat.handle_read)
self.numeric_terminator_check(1)
def test_numeric_terminator2(self):
self.numeric_terminator_check(6)
def test_none_terminator(self):
# Try reading a fixed number of bytes
s, event = start_echo_server()
c = echo_client(None, s.port)
data = b"hello world, I'm not dead yet!\n"
c.push(data)
c.push(SERVER_QUIT)
asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
s.join(timeout=TIMEOUT)
if s.is_alive():
self.fail("join() timed out")
self.assertEqual(c.contents, [])
self.assertEqual(c.buffer, data)
def test_simple_producer(self):
s, event = start_echo_server()
c = echo_client(b'\n', s.port)
data = b"hello world\nI'm not dead yet!\n"
p = asynchat.simple_producer(data+SERVER_QUIT, buffer_size=8)
c.push_with_producer(p)
asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
s.join(timeout=TIMEOUT)
if s.is_alive():
self.fail("join() timed out")
self.assertEqual(c.contents, [b"hello world", b"I'm not dead yet!"])
def test_string_producer(self):
s, event = start_echo_server()
c = echo_client(b'\n', s.port)
data = b"hello world\nI'm not dead yet!\n"
c.push_with_producer(data+SERVER_QUIT)
asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
s.join(timeout=TIMEOUT)
if s.is_alive():
self.fail("join() timed out")
self.assertEqual(c.contents, [b"hello world", b"I'm not dead yet!"])
def test_empty_line(self):
# checks that empty lines are handled correctly
s, event = start_echo_server()
c = echo_client(b'\n', s.port)
c.push(b"hello world\n\nI'm not dead yet!\n")
c.push(SERVER_QUIT)
asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
s.join(timeout=TIMEOUT)
if s.is_alive():
self.fail("join() timed out")
self.assertEqual(c.contents,
[b"hello world", b"", b"I'm not dead yet!"])
def test_close_when_done(self):
s, event = start_echo_server()
s.start_resend_event = threading.Event()
c = echo_client(b'\n', s.port)
c.push(b"hello world\nI'm not dead yet!\n")
c.push(SERVER_QUIT)
c.close_when_done()
asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
# Only allow the server to start echoing data back to the client after
# the client has closed its connection. This prevents a race condition
# where the server echoes all of its data before we can check that it
# got any down below.
s.start_resend_event.set()
s.join(timeout=TIMEOUT)
if s.is_alive():
self.fail("join() timed out")
self.assertEqual(c.contents, [])
# the server might have been able to send a byte or two back, but this
# at least checks that it received something and didn't just fail
# (which could still result in the client not having received anything)
self.assertGreater(len(s.buffer), 0)
def test_push(self):
# Issue #12523: push() should raise a TypeError if it doesn't get
# a bytes string
s, event = start_echo_server()
c = echo_client(b'\n', s.port)
data = b'bytes\n'
c.push(data)
c.push(bytearray(data))
c.push(memoryview(data))
self.assertRaises(TypeError, c.push, 10)
self.assertRaises(TypeError, c.push, 'unicode')
c.push(SERVER_QUIT)
asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
s.join(timeout=TIMEOUT)
self.assertEqual(c.contents, [b'bytes', b'bytes', b'bytes'])
class TestAsynchat_WithPoll(TestAsynchat):
usepoll = True
class TestAsynchatMocked(unittest.TestCase):
def test_blockingioerror(self):
# Issue #16133: handle_read() must ignore BlockingIOError
sock = unittest.mock.Mock()
sock.recv.side_effect = BlockingIOError(errno.EAGAIN)
dispatcher = asynchat.async_chat()
dispatcher.set_socket(sock)
self.addCleanup(dispatcher.del_channel)
with unittest.mock.patch.object(dispatcher, 'handle_error') as error:
dispatcher.handle_read()
self.assertFalse(error.called)
class TestHelperFunctions(unittest.TestCase):
def test_find_prefix_at_end(self):
self.assertEqual(asynchat.find_prefix_at_end("qwerty\r", "\r\n"), 1)
self.assertEqual(asynchat.find_prefix_at_end("qwertydkjf", "\r\n"), 0)
class TestNotConnected(unittest.TestCase):
def test_disallow_negative_terminator(self):
# Issue #11259
client = asynchat.async_chat()
self.assertRaises(ValueError, client.set_terminator, -1)
if __name__ == "__main__":
unittest.main()
| 10,353 | 310 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_urlparse.py | import sys
import unicodedata
import unittest
import urllib.parse
RFC1808_BASE = "http://a/b/c/d;p?q#f"
RFC2396_BASE = "http://a/b/c/d;p?q"
RFC3986_BASE = 'http://a/b/c/d;p?q'
SIMPLE_BASE = 'http://a/b/c/d'
# Each parse_qsl testcase is a two-tuple that contains
# a string with the query and a list with the expected result.
parse_qsl_test_cases = [
("", []),
("&", []),
("&&", []),
("=", [('', '')]),
("=a", [('', 'a')]),
("a", [('a', '')]),
("a=", [('a', '')]),
("&a=b", [('a', 'b')]),
("a=a+b&b=b+c", [('a', 'a b'), ('b', 'b c')]),
("a=1&a=2", [('a', '1'), ('a', '2')]),
(b"", []),
(b"&", []),
(b"&&", []),
(b"=", [(b'', b'')]),
(b"=a", [(b'', b'a')]),
(b"a", [(b'a', b'')]),
(b"a=", [(b'a', b'')]),
(b"&a=b", [(b'a', b'b')]),
(b"a=a+b&b=b+c", [(b'a', b'a b'), (b'b', b'b c')]),
(b"a=1&a=2", [(b'a', b'1'), (b'a', b'2')]),
(";a=b", [(';a', 'b')]),
("a=a+b;b=b+c", [('a', 'a b;b=b c')]),
(b";a=b", [(b';a', b'b')]),
(b"a=a+b;b=b+c", [(b'a', b'a b;b=b c')]),
]
# Each parse_qs testcase is a two-tuple that contains
# a string with the query and a dictionary with the expected result.
parse_qs_test_cases = [
("", {}),
("&", {}),
("&&", {}),
("=", {'': ['']}),
("=a", {'': ['a']}),
("a", {'a': ['']}),
("a=", {'a': ['']}),
("&a=b", {'a': ['b']}),
("a=a+b&b=b+c", {'a': ['a b'], 'b': ['b c']}),
("a=1&a=2", {'a': ['1', '2']}),
(b"", {}),
(b"&", {}),
(b"&&", {}),
(b"=", {b'': [b'']}),
(b"=a", {b'': [b'a']}),
(b"a", {b'a': [b'']}),
(b"a=", {b'a': [b'']}),
(b"&a=b", {b'a': [b'b']}),
(b"a=a+b&b=b+c", {b'a': [b'a b'], b'b': [b'b c']}),
(b"a=1&a=2", {b'a': [b'1', b'2']}),
(";a=b", {';a': ['b']}),
("a=a+b;b=b+c", {'a': ['a b;b=b c']}),
(b";a=b", {b';a': [b'b']}),
(b"a=a+b;b=b+c", {b'a':[ b'a b;b=b c']}),
]
class UrlParseTestCase(unittest.TestCase):
def checkRoundtrips(self, url, parsed, split):
result = urllib.parse.urlparse(url)
self.assertEqual(result, parsed)
t = (result.scheme, result.netloc, result.path,
result.params, result.query, result.fragment)
self.assertEqual(t, parsed)
# put it back together and it should be the same
result2 = urllib.parse.urlunparse(result)
self.assertEqual(result2, url)
self.assertEqual(result2, result.geturl())
# the result of geturl() is a fixpoint; we can always parse it
# again to get the same result:
result3 = urllib.parse.urlparse(result.geturl())
self.assertEqual(result3.geturl(), result.geturl())
self.assertEqual(result3, result)
self.assertEqual(result3.scheme, result.scheme)
self.assertEqual(result3.netloc, result.netloc)
self.assertEqual(result3.path, result.path)
self.assertEqual(result3.params, result.params)
self.assertEqual(result3.query, result.query)
self.assertEqual(result3.fragment, result.fragment)
self.assertEqual(result3.username, result.username)
self.assertEqual(result3.password, result.password)
self.assertEqual(result3.hostname, result.hostname)
self.assertEqual(result3.port, result.port)
# check the roundtrip using urlsplit() as well
result = urllib.parse.urlsplit(url)
self.assertEqual(result, split)
t = (result.scheme, result.netloc, result.path,
result.query, result.fragment)
self.assertEqual(t, split)
result2 = urllib.parse.urlunsplit(result)
self.assertEqual(result2, url)
self.assertEqual(result2, result.geturl())
# check the fixpoint property of re-parsing the result of geturl()
result3 = urllib.parse.urlsplit(result.geturl())
self.assertEqual(result3.geturl(), result.geturl())
self.assertEqual(result3, result)
self.assertEqual(result3.scheme, result.scheme)
self.assertEqual(result3.netloc, result.netloc)
self.assertEqual(result3.path, result.path)
self.assertEqual(result3.query, result.query)
self.assertEqual(result3.fragment, result.fragment)
self.assertEqual(result3.username, result.username)
self.assertEqual(result3.password, result.password)
self.assertEqual(result3.hostname, result.hostname)
self.assertEqual(result3.port, result.port)
def test_qsl(self):
for orig, expect in parse_qsl_test_cases:
result = urllib.parse.parse_qsl(orig, keep_blank_values=True)
self.assertEqual(result, expect, "Error parsing %r" % orig)
expect_without_blanks = [v for v in expect if len(v[1])]
result = urllib.parse.parse_qsl(orig, keep_blank_values=False)
self.assertEqual(result, expect_without_blanks,
"Error parsing %r" % orig)
def test_qs(self):
for orig, expect in parse_qs_test_cases:
result = urllib.parse.parse_qs(orig, keep_blank_values=True)
self.assertEqual(result, expect, "Error parsing %r" % orig)
expect_without_blanks = {v: expect[v]
for v in expect if len(expect[v][0])}
result = urllib.parse.parse_qs(orig, keep_blank_values=False)
self.assertEqual(result, expect_without_blanks,
"Error parsing %r" % orig)
def test_roundtrips(self):
str_cases = [
('file:///tmp/junk.txt',
('file', '', '/tmp/junk.txt', '', '', ''),
('file', '', '/tmp/junk.txt', '', '')),
('imap://mail.python.org/mbox1',
('imap', 'mail.python.org', '/mbox1', '', '', ''),
('imap', 'mail.python.org', '/mbox1', '', '')),
('mms://wms.sys.hinet.net/cts/Drama/09006251100.asf',
('mms', 'wms.sys.hinet.net', '/cts/Drama/09006251100.asf',
'', '', ''),
('mms', 'wms.sys.hinet.net', '/cts/Drama/09006251100.asf',
'', '')),
('nfs://server/path/to/file.txt',
('nfs', 'server', '/path/to/file.txt', '', '', ''),
('nfs', 'server', '/path/to/file.txt', '', '')),
('svn+ssh://svn.zope.org/repos/main/ZConfig/trunk/',
('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/',
'', '', ''),
('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/',
'', '')),
('git+ssh://[email protected]/user/project.git',
('git+ssh', '[email protected]','/user/project.git',
'','',''),
('git+ssh', '[email protected]','/user/project.git',
'', '')),
]
def _encode(t):
return (t[0].encode('ascii'),
tuple(x.encode('ascii') for x in t[1]),
tuple(x.encode('ascii') for x in t[2]))
bytes_cases = [_encode(x) for x in str_cases]
for url, parsed, split in str_cases + bytes_cases:
self.checkRoundtrips(url, parsed, split)
def test_http_roundtrips(self):
# urllib.parse.urlsplit treats 'http:' as an optimized special case,
# so we test both 'http:' and 'https:' in all the following.
# Three cheers for white box knowledge!
str_cases = [
('://www.python.org',
('www.python.org', '', '', '', ''),
('www.python.org', '', '', '')),
('://www.python.org#abc',
('www.python.org', '', '', '', 'abc'),
('www.python.org', '', '', 'abc')),
('://www.python.org?q=abc',
('www.python.org', '', '', 'q=abc', ''),
('www.python.org', '', 'q=abc', '')),
('://www.python.org/#abc',
('www.python.org', '/', '', '', 'abc'),
('www.python.org', '/', '', 'abc')),
('://a/b/c/d;p?q#f',
('a', '/b/c/d', 'p', 'q', 'f'),
('a', '/b/c/d;p', 'q', 'f')),
]
def _encode(t):
return (t[0].encode('ascii'),
tuple(x.encode('ascii') for x in t[1]),
tuple(x.encode('ascii') for x in t[2]))
bytes_cases = [_encode(x) for x in str_cases]
str_schemes = ('http', 'https')
bytes_schemes = (b'http', b'https')
str_tests = str_schemes, str_cases
bytes_tests = bytes_schemes, bytes_cases
for schemes, test_cases in (str_tests, bytes_tests):
for scheme in schemes:
for url, parsed, split in test_cases:
url = scheme + url
parsed = (scheme,) + parsed
split = (scheme,) + split
self.checkRoundtrips(url, parsed, split)
def checkJoin(self, base, relurl, expected):
str_components = (base, relurl, expected)
self.assertEqual(urllib.parse.urljoin(base, relurl), expected)
bytes_components = baseb, relurlb, expectedb = [
x.encode('ascii') for x in str_components]
self.assertEqual(urllib.parse.urljoin(baseb, relurlb), expectedb)
def test_unparse_parse(self):
str_cases = ['Python', './Python','x-newscheme://foo.com/stuff','x://y','x:/y','x:/','/',]
bytes_cases = [x.encode('ascii') for x in str_cases]
for u in str_cases + bytes_cases:
self.assertEqual(urllib.parse.urlunsplit(urllib.parse.urlsplit(u)), u)
self.assertEqual(urllib.parse.urlunparse(urllib.parse.urlparse(u)), u)
def test_RFC1808(self):
# "normal" cases from RFC 1808:
self.checkJoin(RFC1808_BASE, 'g:h', 'g:h')
self.checkJoin(RFC1808_BASE, 'g', 'http://a/b/c/g')
self.checkJoin(RFC1808_BASE, './g', 'http://a/b/c/g')
self.checkJoin(RFC1808_BASE, 'g/', 'http://a/b/c/g/')
self.checkJoin(RFC1808_BASE, '/g', 'http://a/g')
self.checkJoin(RFC1808_BASE, '//g', 'http://g')
self.checkJoin(RFC1808_BASE, 'g?y', 'http://a/b/c/g?y')
self.checkJoin(RFC1808_BASE, 'g?y/./x', 'http://a/b/c/g?y/./x')
self.checkJoin(RFC1808_BASE, '#s', 'http://a/b/c/d;p?q#s')
self.checkJoin(RFC1808_BASE, 'g#s', 'http://a/b/c/g#s')
self.checkJoin(RFC1808_BASE, 'g#s/./x', 'http://a/b/c/g#s/./x')
self.checkJoin(RFC1808_BASE, 'g?y#s', 'http://a/b/c/g?y#s')
self.checkJoin(RFC1808_BASE, 'g;x', 'http://a/b/c/g;x')
self.checkJoin(RFC1808_BASE, 'g;x?y#s', 'http://a/b/c/g;x?y#s')
self.checkJoin(RFC1808_BASE, '.', 'http://a/b/c/')
self.checkJoin(RFC1808_BASE, './', 'http://a/b/c/')
self.checkJoin(RFC1808_BASE, '..', 'http://a/b/')
self.checkJoin(RFC1808_BASE, '../', 'http://a/b/')
self.checkJoin(RFC1808_BASE, '../g', 'http://a/b/g')
self.checkJoin(RFC1808_BASE, '../..', 'http://a/')
self.checkJoin(RFC1808_BASE, '../../', 'http://a/')
self.checkJoin(RFC1808_BASE, '../../g', 'http://a/g')
# "abnormal" cases from RFC 1808:
self.checkJoin(RFC1808_BASE, '', 'http://a/b/c/d;p?q#f')
self.checkJoin(RFC1808_BASE, 'g.', 'http://a/b/c/g.')
self.checkJoin(RFC1808_BASE, '.g', 'http://a/b/c/.g')
self.checkJoin(RFC1808_BASE, 'g..', 'http://a/b/c/g..')
self.checkJoin(RFC1808_BASE, '..g', 'http://a/b/c/..g')
self.checkJoin(RFC1808_BASE, './../g', 'http://a/b/g')
self.checkJoin(RFC1808_BASE, './g/.', 'http://a/b/c/g/')
self.checkJoin(RFC1808_BASE, 'g/./h', 'http://a/b/c/g/h')
self.checkJoin(RFC1808_BASE, 'g/../h', 'http://a/b/c/h')
# RFC 1808 and RFC 1630 disagree on these (according to RFC 1808),
# so we'll not actually run these tests (which expect 1808 behavior).
#self.checkJoin(RFC1808_BASE, 'http:g', 'http:g')
#self.checkJoin(RFC1808_BASE, 'http:', 'http:')
# XXX: The following tests are no longer compatible with RFC3986
# self.checkJoin(RFC1808_BASE, '../../../g', 'http://a/../g')
# self.checkJoin(RFC1808_BASE, '../../../../g', 'http://a/../../g')
# self.checkJoin(RFC1808_BASE, '/./g', 'http://a/./g')
# self.checkJoin(RFC1808_BASE, '/../g', 'http://a/../g')
def test_RFC2368(self):
# Issue 11467: path that starts with a number is not parsed correctly
self.assertEqual(urllib.parse.urlparse('mailto:[email protected]'),
('mailto', '', '[email protected]', '', '', ''))
def test_RFC2396(self):
# cases from RFC 2396
self.checkJoin(RFC2396_BASE, 'g:h', 'g:h')
self.checkJoin(RFC2396_BASE, 'g', 'http://a/b/c/g')
self.checkJoin(RFC2396_BASE, './g', 'http://a/b/c/g')
self.checkJoin(RFC2396_BASE, 'g/', 'http://a/b/c/g/')
self.checkJoin(RFC2396_BASE, '/g', 'http://a/g')
self.checkJoin(RFC2396_BASE, '//g', 'http://g')
self.checkJoin(RFC2396_BASE, 'g?y', 'http://a/b/c/g?y')
self.checkJoin(RFC2396_BASE, '#s', 'http://a/b/c/d;p?q#s')
self.checkJoin(RFC2396_BASE, 'g#s', 'http://a/b/c/g#s')
self.checkJoin(RFC2396_BASE, 'g?y#s', 'http://a/b/c/g?y#s')
self.checkJoin(RFC2396_BASE, 'g;x', 'http://a/b/c/g;x')
self.checkJoin(RFC2396_BASE, 'g;x?y#s', 'http://a/b/c/g;x?y#s')
self.checkJoin(RFC2396_BASE, '.', 'http://a/b/c/')
self.checkJoin(RFC2396_BASE, './', 'http://a/b/c/')
self.checkJoin(RFC2396_BASE, '..', 'http://a/b/')
self.checkJoin(RFC2396_BASE, '../', 'http://a/b/')
self.checkJoin(RFC2396_BASE, '../g', 'http://a/b/g')
self.checkJoin(RFC2396_BASE, '../..', 'http://a/')
self.checkJoin(RFC2396_BASE, '../../', 'http://a/')
self.checkJoin(RFC2396_BASE, '../../g', 'http://a/g')
self.checkJoin(RFC2396_BASE, '', RFC2396_BASE)
self.checkJoin(RFC2396_BASE, 'g.', 'http://a/b/c/g.')
self.checkJoin(RFC2396_BASE, '.g', 'http://a/b/c/.g')
self.checkJoin(RFC2396_BASE, 'g..', 'http://a/b/c/g..')
self.checkJoin(RFC2396_BASE, '..g', 'http://a/b/c/..g')
self.checkJoin(RFC2396_BASE, './../g', 'http://a/b/g')
self.checkJoin(RFC2396_BASE, './g/.', 'http://a/b/c/g/')
self.checkJoin(RFC2396_BASE, 'g/./h', 'http://a/b/c/g/h')
self.checkJoin(RFC2396_BASE, 'g/../h', 'http://a/b/c/h')
self.checkJoin(RFC2396_BASE, 'g;x=1/./y', 'http://a/b/c/g;x=1/y')
self.checkJoin(RFC2396_BASE, 'g;x=1/../y', 'http://a/b/c/y')
self.checkJoin(RFC2396_BASE, 'g?y/./x', 'http://a/b/c/g?y/./x')
self.checkJoin(RFC2396_BASE, 'g?y/../x', 'http://a/b/c/g?y/../x')
self.checkJoin(RFC2396_BASE, 'g#s/./x', 'http://a/b/c/g#s/./x')
self.checkJoin(RFC2396_BASE, 'g#s/../x', 'http://a/b/c/g#s/../x')
# XXX: The following tests are no longer compatible with RFC3986
# self.checkJoin(RFC2396_BASE, '../../../g', 'http://a/../g')
# self.checkJoin(RFC2396_BASE, '../../../../g', 'http://a/../../g')
# self.checkJoin(RFC2396_BASE, '/./g', 'http://a/./g')
# self.checkJoin(RFC2396_BASE, '/../g', 'http://a/../g')
def test_RFC3986(self):
self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y')
self.checkJoin(RFC3986_BASE, ';x', 'http://a/b/c/;x')
self.checkJoin(RFC3986_BASE, 'g:h','g:h')
self.checkJoin(RFC3986_BASE, 'g','http://a/b/c/g')
self.checkJoin(RFC3986_BASE, './g','http://a/b/c/g')
self.checkJoin(RFC3986_BASE, 'g/','http://a/b/c/g/')
self.checkJoin(RFC3986_BASE, '/g','http://a/g')
self.checkJoin(RFC3986_BASE, '//g','http://g')
self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y')
self.checkJoin(RFC3986_BASE, 'g?y','http://a/b/c/g?y')
self.checkJoin(RFC3986_BASE, '#s','http://a/b/c/d;p?q#s')
self.checkJoin(RFC3986_BASE, 'g#s','http://a/b/c/g#s')
self.checkJoin(RFC3986_BASE, 'g?y#s','http://a/b/c/g?y#s')
self.checkJoin(RFC3986_BASE, ';x','http://a/b/c/;x')
self.checkJoin(RFC3986_BASE, 'g;x','http://a/b/c/g;x')
self.checkJoin(RFC3986_BASE, 'g;x?y#s','http://a/b/c/g;x?y#s')
self.checkJoin(RFC3986_BASE, '','http://a/b/c/d;p?q')
self.checkJoin(RFC3986_BASE, '.','http://a/b/c/')
self.checkJoin(RFC3986_BASE, './','http://a/b/c/')
self.checkJoin(RFC3986_BASE, '..','http://a/b/')
self.checkJoin(RFC3986_BASE, '../','http://a/b/')
self.checkJoin(RFC3986_BASE, '../g','http://a/b/g')
self.checkJoin(RFC3986_BASE, '../..','http://a/')
self.checkJoin(RFC3986_BASE, '../../','http://a/')
self.checkJoin(RFC3986_BASE, '../../g','http://a/g')
self.checkJoin(RFC3986_BASE, '../../../g', 'http://a/g')
# Abnormal Examples
# The 'abnormal scenarios' are incompatible with RFC2986 parsing
# Tests are here for reference.
self.checkJoin(RFC3986_BASE, '../../../g','http://a/g')
self.checkJoin(RFC3986_BASE, '../../../../g','http://a/g')
self.checkJoin(RFC3986_BASE, '/./g','http://a/g')
self.checkJoin(RFC3986_BASE, '/../g','http://a/g')
self.checkJoin(RFC3986_BASE, 'g.','http://a/b/c/g.')
self.checkJoin(RFC3986_BASE, '.g','http://a/b/c/.g')
self.checkJoin(RFC3986_BASE, 'g..','http://a/b/c/g..')
self.checkJoin(RFC3986_BASE, '..g','http://a/b/c/..g')
self.checkJoin(RFC3986_BASE, './../g','http://a/b/g')
self.checkJoin(RFC3986_BASE, './g/.','http://a/b/c/g/')
self.checkJoin(RFC3986_BASE, 'g/./h','http://a/b/c/g/h')
self.checkJoin(RFC3986_BASE, 'g/../h','http://a/b/c/h')
self.checkJoin(RFC3986_BASE, 'g;x=1/./y','http://a/b/c/g;x=1/y')
self.checkJoin(RFC3986_BASE, 'g;x=1/../y','http://a/b/c/y')
self.checkJoin(RFC3986_BASE, 'g?y/./x','http://a/b/c/g?y/./x')
self.checkJoin(RFC3986_BASE, 'g?y/../x','http://a/b/c/g?y/../x')
self.checkJoin(RFC3986_BASE, 'g#s/./x','http://a/b/c/g#s/./x')
self.checkJoin(RFC3986_BASE, 'g#s/../x','http://a/b/c/g#s/../x')
#self.checkJoin(RFC3986_BASE, 'http:g','http:g') # strict parser
self.checkJoin(RFC3986_BASE, 'http:g','http://a/b/c/g') #relaxed parser
# Test for issue9721
self.checkJoin('http://a/b/c/de', ';x','http://a/b/c/;x')
def test_urljoins(self):
self.checkJoin(SIMPLE_BASE, 'g:h','g:h')
self.checkJoin(SIMPLE_BASE, 'http:g','http://a/b/c/g')
self.checkJoin(SIMPLE_BASE, 'http:','http://a/b/c/d')
self.checkJoin(SIMPLE_BASE, 'g','http://a/b/c/g')
self.checkJoin(SIMPLE_BASE, './g','http://a/b/c/g')
self.checkJoin(SIMPLE_BASE, 'g/','http://a/b/c/g/')
self.checkJoin(SIMPLE_BASE, '/g','http://a/g')
self.checkJoin(SIMPLE_BASE, '//g','http://g')
self.checkJoin(SIMPLE_BASE, '?y','http://a/b/c/d?y')
self.checkJoin(SIMPLE_BASE, 'g?y','http://a/b/c/g?y')
self.checkJoin(SIMPLE_BASE, 'g?y/./x','http://a/b/c/g?y/./x')
self.checkJoin(SIMPLE_BASE, '.','http://a/b/c/')
self.checkJoin(SIMPLE_BASE, './','http://a/b/c/')
self.checkJoin(SIMPLE_BASE, '..','http://a/b/')
self.checkJoin(SIMPLE_BASE, '../','http://a/b/')
self.checkJoin(SIMPLE_BASE, '../g','http://a/b/g')
self.checkJoin(SIMPLE_BASE, '../..','http://a/')
self.checkJoin(SIMPLE_BASE, '../../g','http://a/g')
self.checkJoin(SIMPLE_BASE, './../g','http://a/b/g')
self.checkJoin(SIMPLE_BASE, './g/.','http://a/b/c/g/')
self.checkJoin(SIMPLE_BASE, 'g/./h','http://a/b/c/g/h')
self.checkJoin(SIMPLE_BASE, 'g/../h','http://a/b/c/h')
self.checkJoin(SIMPLE_BASE, 'http:g','http://a/b/c/g')
self.checkJoin(SIMPLE_BASE, 'http:','http://a/b/c/d')
self.checkJoin(SIMPLE_BASE, 'http:?y','http://a/b/c/d?y')
self.checkJoin(SIMPLE_BASE, 'http:g?y','http://a/b/c/g?y')
self.checkJoin(SIMPLE_BASE, 'http:g?y/./x','http://a/b/c/g?y/./x')
self.checkJoin('http:///', '..','http:///')
self.checkJoin('', 'http://a/b/c/g?y/./x','http://a/b/c/g?y/./x')
self.checkJoin('', 'http://a/./g', 'http://a/./g')
self.checkJoin('svn://pathtorepo/dir1', 'dir2', 'svn://pathtorepo/dir2')
self.checkJoin('svn+ssh://pathtorepo/dir1', 'dir2', 'svn+ssh://pathtorepo/dir2')
self.checkJoin('ws://a/b','g','ws://a/g')
self.checkJoin('wss://a/b','g','wss://a/g')
# XXX: The following tests are no longer compatible with RFC3986
# self.checkJoin(SIMPLE_BASE, '../../../g','http://a/../g')
# self.checkJoin(SIMPLE_BASE, '/./g','http://a/./g')
# test for issue22118 duplicate slashes
self.checkJoin(SIMPLE_BASE + '/', 'foo', SIMPLE_BASE + '/foo')
# Non-RFC-defined tests, covering variations of base and trailing
# slashes
self.checkJoin('http://a/b/c/d/e/', '../../f/g/', 'http://a/b/c/f/g/')
self.checkJoin('http://a/b/c/d/e', '../../f/g/', 'http://a/b/f/g/')
self.checkJoin('http://a/b/c/d/e/', '/../../f/g/', 'http://a/f/g/')
self.checkJoin('http://a/b/c/d/e', '/../../f/g/', 'http://a/f/g/')
self.checkJoin('http://a/b/c/d/e/', '../../f/g', 'http://a/b/c/f/g')
self.checkJoin('http://a/b/', '../../f/g/', 'http://a/f/g/')
# issue 23703: don't duplicate filename
self.checkJoin('a', 'b', 'b')
def test_RFC2732(self):
str_cases = [
('http://Test.python.org:5432/foo/', 'test.python.org', 5432),
('http://12.34.56.78:5432/foo/', '12.34.56.78', 5432),
('http://[::1]:5432/foo/', '::1', 5432),
('http://[dead:beef::1]:5432/foo/', 'dead:beef::1', 5432),
('http://[dead:beef::]:5432/foo/', 'dead:beef::', 5432),
('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]:5432/foo/',
'dead:beef:cafe:5417:affe:8fa3:deaf:feed', 5432),
('http://[::12.34.56.78]:5432/foo/', '::12.34.56.78', 5432),
('http://[::ffff:12.34.56.78]:5432/foo/',
'::ffff:12.34.56.78', 5432),
('http://Test.python.org/foo/', 'test.python.org', None),
('http://12.34.56.78/foo/', '12.34.56.78', None),
('http://[::1]/foo/', '::1', None),
('http://[dead:beef::1]/foo/', 'dead:beef::1', None),
('http://[dead:beef::]/foo/', 'dead:beef::', None),
('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/',
'dead:beef:cafe:5417:affe:8fa3:deaf:feed', None),
('http://[::12.34.56.78]/foo/', '::12.34.56.78', None),
('http://[::ffff:12.34.56.78]/foo/',
'::ffff:12.34.56.78', None),
('http://Test.python.org:/foo/', 'test.python.org', None),
('http://12.34.56.78:/foo/', '12.34.56.78', None),
('http://[::1]:/foo/', '::1', None),
('http://[dead:beef::1]:/foo/', 'dead:beef::1', None),
('http://[dead:beef::]:/foo/', 'dead:beef::', None),
('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]:/foo/',
'dead:beef:cafe:5417:affe:8fa3:deaf:feed', None),
('http://[::12.34.56.78]:/foo/', '::12.34.56.78', None),
('http://[::ffff:12.34.56.78]:/foo/',
'::ffff:12.34.56.78', None),
]
def _encode(t):
return t[0].encode('ascii'), t[1].encode('ascii'), t[2]
bytes_cases = [_encode(x) for x in str_cases]
for url, hostname, port in str_cases + bytes_cases:
urlparsed = urllib.parse.urlparse(url)
self.assertEqual((urlparsed.hostname, urlparsed.port) , (hostname, port))
str_cases = [
'http://::12.34.56.78]/',
'http://[::1/foo/',
'ftp://[::1/foo/bad]/bad',
'http://[::1/foo/bad]/bad',
'http://[::ffff:12.34.56.78']
bytes_cases = [x.encode('ascii') for x in str_cases]
for invalid_url in str_cases + bytes_cases:
self.assertRaises(ValueError, urllib.parse.urlparse, invalid_url)
def test_urldefrag(self):
str_cases = [
('http://python.org#frag', 'http://python.org', 'frag'),
('http://python.org', 'http://python.org', ''),
('http://python.org/#frag', 'http://python.org/', 'frag'),
('http://python.org/', 'http://python.org/', ''),
('http://python.org/?q#frag', 'http://python.org/?q', 'frag'),
('http://python.org/?q', 'http://python.org/?q', ''),
('http://python.org/p#frag', 'http://python.org/p', 'frag'),
('http://python.org/p?q', 'http://python.org/p?q', ''),
(RFC1808_BASE, 'http://a/b/c/d;p?q', 'f'),
(RFC2396_BASE, 'http://a/b/c/d;p?q', ''),
]
def _encode(t):
return type(t)(x.encode('ascii') for x in t)
bytes_cases = [_encode(x) for x in str_cases]
for url, defrag, frag in str_cases + bytes_cases:
result = urllib.parse.urldefrag(url)
self.assertEqual(result.geturl(), url)
self.assertEqual(result, (defrag, frag))
self.assertEqual(result.url, defrag)
self.assertEqual(result.fragment, frag)
def test_urlsplit_scoped_IPv6(self):
p = urllib.parse.urlsplit('http://[FE80::822a:a8ff:fe49:470c%tESt]:1234')
self.assertEqual(p.hostname, "fe80::822a:a8ff:fe49:470c%tESt")
self.assertEqual(p.netloc, '[FE80::822a:a8ff:fe49:470c%tESt]:1234')
p = urllib.parse.urlsplit(b'http://[FE80::822a:a8ff:fe49:470c%tESt]:1234')
self.assertEqual(p.hostname, b"fe80::822a:a8ff:fe49:470c%tESt")
self.assertEqual(p.netloc, b'[FE80::822a:a8ff:fe49:470c%tESt]:1234')
def test_urlsplit_attributes(self):
url = "HTTP://WWW.PYTHON.ORG/doc/#frag"
p = urllib.parse.urlsplit(url)
self.assertEqual(p.scheme, "http")
self.assertEqual(p.netloc, "WWW.PYTHON.ORG")
self.assertEqual(p.path, "/doc/")
self.assertEqual(p.query, "")
self.assertEqual(p.fragment, "frag")
self.assertEqual(p.username, None)
self.assertEqual(p.password, None)
self.assertEqual(p.hostname, "www.python.org")
self.assertEqual(p.port, None)
# geturl() won't return exactly the original URL in this case
# since the scheme is always case-normalized
# We handle this by ignoring the first 4 characters of the URL
self.assertEqual(p.geturl()[4:], url[4:])
url = "http://User:[email protected]:080/doc/?query=yes#frag"
p = urllib.parse.urlsplit(url)
self.assertEqual(p.scheme, "http")
self.assertEqual(p.netloc, "User:[email protected]:080")
self.assertEqual(p.path, "/doc/")
self.assertEqual(p.query, "query=yes")
self.assertEqual(p.fragment, "frag")
self.assertEqual(p.username, "User")
self.assertEqual(p.password, "Pass")
self.assertEqual(p.hostname, "www.python.org")
self.assertEqual(p.port, 80)
self.assertEqual(p.geturl(), url)
# Addressing issue1698, which suggests Username can contain
# "@" characters. Though not RFC compliant, many ftp sites allow
# and request email addresses as usernames.
url = "http://[email protected]:[email protected]:080/doc/?query=yes#frag"
p = urllib.parse.urlsplit(url)
self.assertEqual(p.scheme, "http")
self.assertEqual(p.netloc, "[email protected]:[email protected]:080")
self.assertEqual(p.path, "/doc/")
self.assertEqual(p.query, "query=yes")
self.assertEqual(p.fragment, "frag")
self.assertEqual(p.username, "[email protected]")
self.assertEqual(p.password, "Pass")
self.assertEqual(p.hostname, "www.python.org")
self.assertEqual(p.port, 80)
self.assertEqual(p.geturl(), url)
# And check them all again, only with bytes this time
url = b"HTTP://WWW.PYTHON.ORG/doc/#frag"
p = urllib.parse.urlsplit(url)
self.assertEqual(p.scheme, b"http")
self.assertEqual(p.netloc, b"WWW.PYTHON.ORG")
self.assertEqual(p.path, b"/doc/")
self.assertEqual(p.query, b"")
self.assertEqual(p.fragment, b"frag")
self.assertEqual(p.username, None)
self.assertEqual(p.password, None)
self.assertEqual(p.hostname, b"www.python.org")
self.assertEqual(p.port, None)
self.assertEqual(p.geturl()[4:], url[4:])
url = b"http://User:[email protected]:080/doc/?query=yes#frag"
p = urllib.parse.urlsplit(url)
self.assertEqual(p.scheme, b"http")
self.assertEqual(p.netloc, b"User:[email protected]:080")
self.assertEqual(p.path, b"/doc/")
self.assertEqual(p.query, b"query=yes")
self.assertEqual(p.fragment, b"frag")
self.assertEqual(p.username, b"User")
self.assertEqual(p.password, b"Pass")
self.assertEqual(p.hostname, b"www.python.org")
self.assertEqual(p.port, 80)
self.assertEqual(p.geturl(), url)
url = b"http://[email protected]:[email protected]:080/doc/?query=yes#frag"
p = urllib.parse.urlsplit(url)
self.assertEqual(p.scheme, b"http")
self.assertEqual(p.netloc, b"[email protected]:[email protected]:080")
self.assertEqual(p.path, b"/doc/")
self.assertEqual(p.query, b"query=yes")
self.assertEqual(p.fragment, b"frag")
self.assertEqual(p.username, b"[email protected]")
self.assertEqual(p.password, b"Pass")
self.assertEqual(p.hostname, b"www.python.org")
self.assertEqual(p.port, 80)
self.assertEqual(p.geturl(), url)
# Verify an illegal port raises ValueError
url = b"HTTP://WWW.PYTHON.ORG:65536/doc/#frag"
p = urllib.parse.urlsplit(url)
with self.assertRaisesRegex(ValueError, "out of range"):
p.port
def test_urlsplit_remove_unsafe_bytes(self):
# Remove ASCII tabs and newlines from input, for http common case scenario.
url = "h\nttp://www.python\n.org\t/java\nscript:\talert('msg\r\n')/?query\n=\tsomething#frag\nment"
p = urllib.parse.urlsplit(url)
self.assertEqual(p.scheme, "http")
self.assertEqual(p.netloc, "www.python.org")
self.assertEqual(p.path, "/javascript:alert('msg')/")
self.assertEqual(p.query, "query=something")
self.assertEqual(p.fragment, "fragment")
self.assertEqual(p.username, None)
self.assertEqual(p.password, None)
self.assertEqual(p.hostname, "www.python.org")
self.assertEqual(p.port, None)
self.assertEqual(p.geturl(), "http://www.python.org/javascript:alert('msg')/?query=something#fragment")
# Remove ASCII tabs and newlines from input as bytes, for http common case scenario.
url = b"h\nttp://www.python\n.org\t/java\nscript:\talert('msg\r\n')/?query\n=\tsomething#frag\nment"
p = urllib.parse.urlsplit(url)
self.assertEqual(p.scheme, b"http")
self.assertEqual(p.netloc, b"www.python.org")
self.assertEqual(p.path, b"/javascript:alert('msg')/")
self.assertEqual(p.query, b"query=something")
self.assertEqual(p.fragment, b"fragment")
self.assertEqual(p.username, None)
self.assertEqual(p.password, None)
self.assertEqual(p.hostname, b"www.python.org")
self.assertEqual(p.port, None)
self.assertEqual(p.geturl(), b"http://www.python.org/javascript:alert('msg')/?query=something#fragment")
# any scheme
url = "x-new-scheme\t://www.python\n.org\t/java\nscript:\talert('msg\r\n')/?query\n=\tsomething#frag\nment"
p = urllib.parse.urlsplit(url)
self.assertEqual(p.geturl(), "x-new-scheme://www.python.org/javascript:alert('msg')/?query=something#fragment")
# Remove ASCII tabs and newlines from input as bytes, any scheme.
url = b"x-new-scheme\t://www.python\n.org\t/java\nscript:\talert('msg\r\n')/?query\n=\tsomething#frag\nment"
p = urllib.parse.urlsplit(url)
self.assertEqual(p.geturl(), b"x-new-scheme://www.python.org/javascript:alert('msg')/?query=something#fragment")
# Unsafe bytes is not returned from urlparse cache.
# scheme is stored after parsing, sending an scheme with unsafe bytes *will not* return an unsafe scheme
url = "https://www.python\n.org\t/java\nscript:\talert('msg\r\n')/?query\n=\tsomething#frag\nment"
scheme = "htt\nps"
for _ in range(2):
p = urllib.parse.urlsplit(url, scheme=scheme)
self.assertEqual(p.scheme, "https")
self.assertEqual(p.geturl(), "https://www.python.org/javascript:alert('msg')/?query=something#fragment")
def test_attributes_bad_port(self):
"""Check handling of invalid ports."""
for bytes in (False, True):
for parse in (urllib.parse.urlsplit, urllib.parse.urlparse):
for port in ("foo", "1.5", "-1", "0x10"):
with self.subTest(bytes=bytes, parse=parse, port=port):
netloc = "www.example.net:" + port
url = "http://" + netloc
if bytes:
netloc = netloc.encode("ascii")
url = url.encode("ascii")
p = parse(url)
self.assertEqual(p.netloc, netloc)
with self.assertRaises(ValueError):
p.port
def test_attributes_without_netloc(self):
# This example is straight from RFC 3261. It looks like it
# should allow the username, hostname, and port to be filled
# in, but doesn't. Since it's a URI and doesn't use the
# scheme://netloc syntax, the netloc and related attributes
# should be left empty.
uri = "sip:[email protected];maddr=239.255.255.1;ttl=15"
p = urllib.parse.urlsplit(uri)
self.assertEqual(p.netloc, "")
self.assertEqual(p.username, None)
self.assertEqual(p.password, None)
self.assertEqual(p.hostname, None)
self.assertEqual(p.port, None)
self.assertEqual(p.geturl(), uri)
p = urllib.parse.urlparse(uri)
self.assertEqual(p.netloc, "")
self.assertEqual(p.username, None)
self.assertEqual(p.password, None)
self.assertEqual(p.hostname, None)
self.assertEqual(p.port, None)
self.assertEqual(p.geturl(), uri)
# You guessed it, repeating the test with bytes input
uri = b"sip:[email protected];maddr=239.255.255.1;ttl=15"
p = urllib.parse.urlsplit(uri)
self.assertEqual(p.netloc, b"")
self.assertEqual(p.username, None)
self.assertEqual(p.password, None)
self.assertEqual(p.hostname, None)
self.assertEqual(p.port, None)
self.assertEqual(p.geturl(), uri)
p = urllib.parse.urlparse(uri)
self.assertEqual(p.netloc, b"")
self.assertEqual(p.username, None)
self.assertEqual(p.password, None)
self.assertEqual(p.hostname, None)
self.assertEqual(p.port, None)
self.assertEqual(p.geturl(), uri)
def test_noslash(self):
# Issue 1637: http://foo.com?query is legal
self.assertEqual(urllib.parse.urlparse("http://example.com?blahblah=/foo"),
('http', 'example.com', '', '', 'blahblah=/foo', ''))
self.assertEqual(urllib.parse.urlparse(b"http://example.com?blahblah=/foo"),
(b'http', b'example.com', b'', b'', b'blahblah=/foo', b''))
def test_withoutscheme(self):
# Test urlparse without scheme
# Issue 754016: urlparse goes wrong with IP:port without scheme
# RFC 1808 specifies that netloc should start with //, urlparse expects
# the same, otherwise it classifies the portion of url as path.
self.assertEqual(urllib.parse.urlparse("path"),
('','','path','','',''))
self.assertEqual(urllib.parse.urlparse("//www.python.org:80"),
('','www.python.org:80','','','',''))
self.assertEqual(urllib.parse.urlparse("http://www.python.org:80"),
('http','www.python.org:80','','','',''))
# Repeat for bytes input
self.assertEqual(urllib.parse.urlparse(b"path"),
(b'',b'',b'path',b'',b'',b''))
self.assertEqual(urllib.parse.urlparse(b"//www.python.org:80"),
(b'',b'www.python.org:80',b'',b'',b'',b''))
self.assertEqual(urllib.parse.urlparse(b"http://www.python.org:80"),
(b'http',b'www.python.org:80',b'',b'',b'',b''))
def test_portseparator(self):
# Issue 754016 makes changes for port separator ':' from scheme separator
self.assertEqual(urllib.parse.urlparse("path:80"),
('','','path:80','','',''))
self.assertEqual(urllib.parse.urlparse("http:"),('http','','','','',''))
self.assertEqual(urllib.parse.urlparse("https:"),('https','','','','',''))
self.assertEqual(urllib.parse.urlparse("http://www.python.org:80"),
('http','www.python.org:80','','','',''))
# As usual, need to check bytes input as well
self.assertEqual(urllib.parse.urlparse(b"path:80"),
(b'',b'',b'path:80',b'',b'',b''))
self.assertEqual(urllib.parse.urlparse(b"http:"),(b'http',b'',b'',b'',b'',b''))
self.assertEqual(urllib.parse.urlparse(b"https:"),(b'https',b'',b'',b'',b'',b''))
self.assertEqual(urllib.parse.urlparse(b"http://www.python.org:80"),
(b'http',b'www.python.org:80',b'',b'',b'',b''))
def test_usingsys(self):
# Issue 3314: sys module is used in the error
self.assertRaises(TypeError, urllib.parse.urlencode, "foo")
def test_anyscheme(self):
# Issue 7904: s3://foo.com/stuff has netloc "foo.com".
self.assertEqual(urllib.parse.urlparse("s3://foo.com/stuff"),
('s3', 'foo.com', '/stuff', '', '', ''))
self.assertEqual(urllib.parse.urlparse("x-newscheme://foo.com/stuff"),
('x-newscheme', 'foo.com', '/stuff', '', '', ''))
self.assertEqual(urllib.parse.urlparse("x-newscheme://foo.com/stuff?query#fragment"),
('x-newscheme', 'foo.com', '/stuff', '', 'query', 'fragment'))
self.assertEqual(urllib.parse.urlparse("x-newscheme://foo.com/stuff?query"),
('x-newscheme', 'foo.com', '/stuff', '', 'query', ''))
# And for bytes...
self.assertEqual(urllib.parse.urlparse(b"s3://foo.com/stuff"),
(b's3', b'foo.com', b'/stuff', b'', b'', b''))
self.assertEqual(urllib.parse.urlparse(b"x-newscheme://foo.com/stuff"),
(b'x-newscheme', b'foo.com', b'/stuff', b'', b'', b''))
self.assertEqual(urllib.parse.urlparse(b"x-newscheme://foo.com/stuff?query#fragment"),
(b'x-newscheme', b'foo.com', b'/stuff', b'', b'query', b'fragment'))
self.assertEqual(urllib.parse.urlparse(b"x-newscheme://foo.com/stuff?query"),
(b'x-newscheme', b'foo.com', b'/stuff', b'', b'query', b''))
def test_default_scheme(self):
# Exercise the scheme parameter of urlparse() and urlsplit()
for func in (urllib.parse.urlparse, urllib.parse.urlsplit):
with self.subTest(function=func):
result = func("http://example.net/", "ftp")
self.assertEqual(result.scheme, "http")
result = func(b"http://example.net/", b"ftp")
self.assertEqual(result.scheme, b"http")
self.assertEqual(func("path", "ftp").scheme, "ftp")
self.assertEqual(func("path", scheme="ftp").scheme, "ftp")
self.assertEqual(func(b"path", scheme=b"ftp").scheme, b"ftp")
self.assertEqual(func("path").scheme, "")
self.assertEqual(func(b"path").scheme, b"")
self.assertEqual(func(b"path", "").scheme, b"")
def test_parse_fragments(self):
# Exercise the allow_fragments parameter of urlparse() and urlsplit()
tests = (
("http:#frag", "path", "frag"),
("//example.net#frag", "path", "frag"),
("index.html#frag", "path", "frag"),
(";a=b#frag", "params", "frag"),
("?a=b#frag", "query", "frag"),
("#frag", "path", "frag"),
("abc#@frag", "path", "@frag"),
("//abc#@frag", "path", "@frag"),
("//abc:80#@frag", "path", "@frag"),
("//abc#@frag:80", "path", "@frag:80"),
)
for url, attr, expected_frag in tests:
for func in (urllib.parse.urlparse, urllib.parse.urlsplit):
if attr == "params" and func is urllib.parse.urlsplit:
attr = "path"
with self.subTest(url=url, function=func):
result = func(url, allow_fragments=False)
self.assertEqual(result.fragment, "")
self.assertTrue(
getattr(result, attr).endswith("#" + expected_frag))
self.assertEqual(func(url, "", False).fragment, "")
result = func(url, allow_fragments=True)
self.assertEqual(result.fragment, expected_frag)
self.assertFalse(
getattr(result, attr).endswith(expected_frag))
self.assertEqual(func(url, "", True).fragment,
expected_frag)
self.assertEqual(func(url).fragment, expected_frag)
def test_mixed_types_rejected(self):
# Several functions that process either strings or ASCII encoded bytes
# accept multiple arguments. Check they reject mixed type input
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlparse("www.python.org", b"http")
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlparse(b"www.python.org", "http")
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlsplit("www.python.org", b"http")
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlsplit(b"www.python.org", "http")
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlunparse(( b"http", "www.python.org","","","",""))
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlunparse(("http", b"www.python.org","","","",""))
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlunsplit((b"http", "www.python.org","","",""))
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlunsplit(("http", b"www.python.org","","",""))
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urljoin("http://python.org", b"http://python.org")
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urljoin(b"http://python.org", "http://python.org")
def _check_result_type(self, str_type):
num_args = len(str_type._fields)
bytes_type = str_type._encoded_counterpart
self.assertIs(bytes_type._decoded_counterpart, str_type)
str_args = ('',) * num_args
bytes_args = (b'',) * num_args
str_result = str_type(*str_args)
bytes_result = bytes_type(*bytes_args)
encoding = 'ascii'
errors = 'strict'
self.assertEqual(str_result, str_args)
self.assertEqual(bytes_result.decode(), str_args)
self.assertEqual(bytes_result.decode(), str_result)
self.assertEqual(bytes_result.decode(encoding), str_args)
self.assertEqual(bytes_result.decode(encoding), str_result)
self.assertEqual(bytes_result.decode(encoding, errors), str_args)
self.assertEqual(bytes_result.decode(encoding, errors), str_result)
self.assertEqual(bytes_result, bytes_args)
self.assertEqual(str_result.encode(), bytes_args)
self.assertEqual(str_result.encode(), bytes_result)
self.assertEqual(str_result.encode(encoding), bytes_args)
self.assertEqual(str_result.encode(encoding), bytes_result)
self.assertEqual(str_result.encode(encoding, errors), bytes_args)
self.assertEqual(str_result.encode(encoding, errors), bytes_result)
def test_result_pairs(self):
# Check encoding and decoding between result pairs
result_types = [
urllib.parse.DefragResult,
urllib.parse.SplitResult,
urllib.parse.ParseResult,
]
for result_type in result_types:
self._check_result_type(result_type)
def test_parse_qs_encoding(self):
result = urllib.parse.parse_qs("key=\u0141%E9", encoding="latin-1")
self.assertEqual(result, {'key': ['\u0141\xE9']})
result = urllib.parse.parse_qs("key=\u0141%C3%A9", encoding="utf-8")
self.assertEqual(result, {'key': ['\u0141\xE9']})
result = urllib.parse.parse_qs("key=\u0141%C3%A9", encoding="ascii")
self.assertEqual(result, {'key': ['\u0141\ufffd\ufffd']})
result = urllib.parse.parse_qs("key=\u0141%E9-", encoding="ascii")
self.assertEqual(result, {'key': ['\u0141\ufffd-']})
result = urllib.parse.parse_qs("key=\u0141%E9-", encoding="ascii",
errors="ignore")
self.assertEqual(result, {'key': ['\u0141-']})
def test_parse_qsl_encoding(self):
result = urllib.parse.parse_qsl("key=\u0141%E9", encoding="latin-1")
self.assertEqual(result, [('key', '\u0141\xE9')])
result = urllib.parse.parse_qsl("key=\u0141%C3%A9", encoding="utf-8")
self.assertEqual(result, [('key', '\u0141\xE9')])
result = urllib.parse.parse_qsl("key=\u0141%C3%A9", encoding="ascii")
self.assertEqual(result, [('key', '\u0141\ufffd\ufffd')])
result = urllib.parse.parse_qsl("key=\u0141%E9-", encoding="ascii")
self.assertEqual(result, [('key', '\u0141\ufffd-')])
result = urllib.parse.parse_qsl("key=\u0141%E9-", encoding="ascii",
errors="ignore")
self.assertEqual(result, [('key', '\u0141-')])
def test_parse_qsl_max_num_fields(self):
with self.assertRaises(ValueError):
urllib.parse.parse_qs('&'.join(['a=a']*11), max_num_fields=10)
urllib.parse.parse_qs('&'.join(['a=a']*10), max_num_fields=10)
def test_parse_qs_separator(self):
parse_qs_semicolon_cases = [
(";", {}),
(";;", {}),
(";a=b", {'a': ['b']}),
("a=a+b;b=b+c", {'a': ['a b'], 'b': ['b c']}),
("a=1;a=2", {'a': ['1', '2']}),
(b";", {}),
(b";;", {}),
(b";a=b", {b'a': [b'b']}),
(b"a=a+b;b=b+c", {b'a': [b'a b'], b'b': [b'b c']}),
(b"a=1;a=2", {b'a': [b'1', b'2']}),
]
for orig, expect in parse_qs_semicolon_cases:
with self.subTest(f"Original: {orig!r}, Expected: {expect!r}"):
result = urllib.parse.parse_qs(orig, separator=';')
self.assertEqual(result, expect, "Error parsing %r" % orig)
def test_parse_qsl_separator(self):
parse_qsl_semicolon_cases = [
(";", []),
(";;", []),
(";a=b", [('a', 'b')]),
("a=a+b;b=b+c", [('a', 'a b'), ('b', 'b c')]),
("a=1;a=2", [('a', '1'), ('a', '2')]),
(b";", []),
(b";;", []),
(b";a=b", [(b'a', b'b')]),
(b"a=a+b;b=b+c", [(b'a', b'a b'), (b'b', b'b c')]),
(b"a=1;a=2", [(b'a', b'1'), (b'a', b'2')]),
]
for orig, expect in parse_qsl_semicolon_cases:
with self.subTest(f"Original: {orig!r}, Expected: {expect!r}"):
result = urllib.parse.parse_qsl(orig, separator=';')
self.assertEqual(result, expect, "Error parsing %r" % orig)
def test_urlencode_sequences(self):
# Other tests incidentally urlencode things; test non-covered cases:
# Sequence and object values.
result = urllib.parse.urlencode({'a': [1, 2], 'b': (3, 4, 5)}, True)
# we cannot rely on ordering here
assert set(result.split('&')) == {'a=1', 'a=2', 'b=3', 'b=4', 'b=5'}
class Trivial:
def __str__(self):
return 'trivial'
result = urllib.parse.urlencode({'a': Trivial()}, True)
self.assertEqual(result, 'a=trivial')
def test_urlencode_quote_via(self):
result = urllib.parse.urlencode({'a': 'some value'})
self.assertEqual(result, "a=some+value")
result = urllib.parse.urlencode({'a': 'some value/another'},
quote_via=urllib.parse.quote)
self.assertEqual(result, "a=some%20value%2Fanother")
result = urllib.parse.urlencode({'a': 'some value/another'},
safe='/', quote_via=urllib.parse.quote)
self.assertEqual(result, "a=some%20value/another")
def test_quote_from_bytes(self):
self.assertRaises(TypeError, urllib.parse.quote_from_bytes, 'foo')
result = urllib.parse.quote_from_bytes(b'archaeological arcana')
self.assertEqual(result, 'archaeological%20arcana')
result = urllib.parse.quote_from_bytes(b'')
self.assertEqual(result, '')
def test_unquote_to_bytes(self):
result = urllib.parse.unquote_to_bytes('abc%20def')
self.assertEqual(result, b'abc def')
result = urllib.parse.unquote_to_bytes('')
self.assertEqual(result, b'')
def test_quote_errors(self):
self.assertRaises(TypeError, urllib.parse.quote, b'foo',
encoding='utf-8')
self.assertRaises(TypeError, urllib.parse.quote, b'foo', errors='strict')
def test_issue14072(self):
p1 = urllib.parse.urlsplit('tel:+31-641044153')
self.assertEqual(p1.scheme, 'tel')
self.assertEqual(p1.path, '+31-641044153')
p2 = urllib.parse.urlsplit('tel:+31641044153')
self.assertEqual(p2.scheme, 'tel')
self.assertEqual(p2.path, '+31641044153')
# assert the behavior for urlparse
p1 = urllib.parse.urlparse('tel:+31-641044153')
self.assertEqual(p1.scheme, 'tel')
self.assertEqual(p1.path, '+31-641044153')
p2 = urllib.parse.urlparse('tel:+31641044153')
self.assertEqual(p2.scheme, 'tel')
self.assertEqual(p2.path, '+31641044153')
def test_telurl_params(self):
p1 = urllib.parse.urlparse('tel:123-4;phone-context=+1-650-516')
self.assertEqual(p1.scheme, 'tel')
self.assertEqual(p1.path, '123-4')
self.assertEqual(p1.params, 'phone-context=+1-650-516')
p1 = urllib.parse.urlparse('tel:+1-201-555-0123')
self.assertEqual(p1.scheme, 'tel')
self.assertEqual(p1.path, '+1-201-555-0123')
self.assertEqual(p1.params, '')
p1 = urllib.parse.urlparse('tel:7042;phone-context=example.com')
self.assertEqual(p1.scheme, 'tel')
self.assertEqual(p1.path, '7042')
self.assertEqual(p1.params, 'phone-context=example.com')
p1 = urllib.parse.urlparse('tel:863-1234;phone-context=+1-914-555')
self.assertEqual(p1.scheme, 'tel')
self.assertEqual(p1.path, '863-1234')
self.assertEqual(p1.params, 'phone-context=+1-914-555')
def test_Quoter_repr(self):
quoter = urllib.parse.Quoter(urllib.parse._ALWAYS_SAFE)
self.assertIn('Quoter', repr(quoter))
def test_all(self):
expected = []
undocumented = {
'splitattr', 'splithost', 'splitnport', 'splitpasswd',
'splitport', 'splitquery', 'splittag', 'splittype', 'splituser',
'splitvalue',
'Quoter', 'ResultBase', 'clear_cache', 'to_bytes', 'unwrap',
}
for name in dir(urllib.parse):
if name.startswith('_') or name in undocumented:
continue
object = getattr(urllib.parse, name)
if getattr(object, '__module__', None) == 'urllib.parse':
expected.append(name)
self.assertCountEqual(urllib.parse.__all__, expected)
def test_urlsplit_normalization(self):
# Certain characters should never occur in the netloc,
# including under normalization.
# Ensure that ALL of them are detected and cause an error
illegal_chars = '/:#?@'
hex_chars = {'{:04X}'.format(ord(c)) for c in illegal_chars}
denorm_chars = [
c for c in map(chr, range(128, sys.maxunicode))
if (hex_chars & set(unicodedata.decomposition(c).split()))
and c not in illegal_chars
]
# Sanity check that we found at least one such character
self.assertIn('\u2100', denorm_chars)
self.assertIn('\uFF03', denorm_chars)
# bpo-36742: Verify port separators are ignored when they
# existed prior to decomposition
urllib.parse.urlsplit('http://\u30d5\u309a:80')
with self.assertRaises(ValueError):
urllib.parse.urlsplit('http://\u30d5\u309a\ufe1380')
for scheme in ["http", "https", "ftp"]:
for netloc in ["netloc{}false.netloc", "n{}user@netloc"]:
for c in denorm_chars:
url = "{}://{}/path".format(scheme, netloc.format(c))
with self.subTest(url=url, char='{:04X}'.format(ord(c))):
with self.assertRaises(ValueError):
urllib.parse.urlsplit(url)
class Utility_Tests(unittest.TestCase):
"""Testcase to test the various utility functions in the urllib."""
# In Python 2 this test class was in test_urllib.
def test_splittype(self):
splittype = urllib.parse.splittype
self.assertEqual(splittype('type:opaquestring'), ('type', 'opaquestring'))
self.assertEqual(splittype('opaquestring'), (None, 'opaquestring'))
self.assertEqual(splittype(':opaquestring'), (None, ':opaquestring'))
self.assertEqual(splittype('type:'), ('type', ''))
self.assertEqual(splittype('type:opaque:string'), ('type', 'opaque:string'))
def test_splithost(self):
splithost = urllib.parse.splithost
self.assertEqual(splithost('//www.example.org:80/foo/bar/baz.html'),
('www.example.org:80', '/foo/bar/baz.html'))
self.assertEqual(splithost('//www.example.org:80'),
('www.example.org:80', ''))
self.assertEqual(splithost('/foo/bar/baz.html'),
(None, '/foo/bar/baz.html'))
# bpo-30500: # starts a fragment.
self.assertEqual(splithost('//127.0.0.1#@host.com'),
('127.0.0.1', '/#@host.com'))
self.assertEqual(splithost('//127.0.0.1#@host.com:80'),
('127.0.0.1', '/#@host.com:80'))
self.assertEqual(splithost('//127.0.0.1:80#@host.com'),
('127.0.0.1:80', '/#@host.com'))
# Empty host is returned as empty string.
self.assertEqual(splithost("///file"),
('', '/file'))
# Trailing semicolon, question mark and hash symbol are kept.
self.assertEqual(splithost("//example.net/file;"),
('example.net', '/file;'))
self.assertEqual(splithost("//example.net/file?"),
('example.net', '/file?'))
self.assertEqual(splithost("//example.net/file#"),
('example.net', '/file#'))
def test_splituser(self):
splituser = urllib.parse.splituser
self.assertEqual(splituser('User:[email protected]:080'),
('User:Pass', 'www.python.org:080'))
self.assertEqual(splituser('@www.python.org:080'),
('', 'www.python.org:080'))
self.assertEqual(splituser('www.python.org:080'),
(None, 'www.python.org:080'))
self.assertEqual(splituser('User:Pass@'),
('User:Pass', ''))
self.assertEqual(splituser('[email protected]:[email protected]:080'),
('[email protected]:Pass', 'www.python.org:080'))
def test_splitpasswd(self):
# Some of the password examples are not sensible, but it is added to
# confirming to RFC2617 and addressing issue4675.
splitpasswd = urllib.parse.splitpasswd
self.assertEqual(splitpasswd('user:ab'), ('user', 'ab'))
self.assertEqual(splitpasswd('user:a\nb'), ('user', 'a\nb'))
self.assertEqual(splitpasswd('user:a\tb'), ('user', 'a\tb'))
self.assertEqual(splitpasswd('user:a\rb'), ('user', 'a\rb'))
self.assertEqual(splitpasswd('user:a\fb'), ('user', 'a\fb'))
self.assertEqual(splitpasswd('user:a\vb'), ('user', 'a\vb'))
self.assertEqual(splitpasswd('user:a:b'), ('user', 'a:b'))
self.assertEqual(splitpasswd('user:a b'), ('user', 'a b'))
self.assertEqual(splitpasswd('user 2:ab'), ('user 2', 'ab'))
self.assertEqual(splitpasswd('user+1:a+b'), ('user+1', 'a+b'))
self.assertEqual(splitpasswd('user:'), ('user', ''))
self.assertEqual(splitpasswd('user'), ('user', None))
self.assertEqual(splitpasswd(':ab'), ('', 'ab'))
def test_splitport(self):
splitport = urllib.parse.splitport
self.assertEqual(splitport('parrot:88'), ('parrot', '88'))
self.assertEqual(splitport('parrot'), ('parrot', None))
self.assertEqual(splitport('parrot:'), ('parrot', None))
self.assertEqual(splitport('127.0.0.1'), ('127.0.0.1', None))
self.assertEqual(splitport('parrot:cheese'), ('parrot:cheese', None))
self.assertEqual(splitport('[::1]:88'), ('[::1]', '88'))
self.assertEqual(splitport('[::1]'), ('[::1]', None))
self.assertEqual(splitport(':88'), ('', '88'))
def test_splitnport(self):
splitnport = urllib.parse.splitnport
self.assertEqual(splitnport('parrot:88'), ('parrot', 88))
self.assertEqual(splitnport('parrot'), ('parrot', -1))
self.assertEqual(splitnport('parrot', 55), ('parrot', 55))
self.assertEqual(splitnport('parrot:'), ('parrot', -1))
self.assertEqual(splitnport('parrot:', 55), ('parrot', 55))
self.assertEqual(splitnport('127.0.0.1'), ('127.0.0.1', -1))
self.assertEqual(splitnport('127.0.0.1', 55), ('127.0.0.1', 55))
self.assertEqual(splitnport('parrot:cheese'), ('parrot', None))
self.assertEqual(splitnport('parrot:cheese', 55), ('parrot', None))
def test_splitquery(self):
# Normal cases are exercised by other tests; ensure that we also
# catch cases with no port specified (testcase ensuring coverage)
splitquery = urllib.parse.splitquery
self.assertEqual(splitquery('http://python.org/fake?foo=bar'),
('http://python.org/fake', 'foo=bar'))
self.assertEqual(splitquery('http://python.org/fake?foo=bar?'),
('http://python.org/fake?foo=bar', ''))
self.assertEqual(splitquery('http://python.org/fake'),
('http://python.org/fake', None))
self.assertEqual(splitquery('?foo=bar'), ('', 'foo=bar'))
def test_splittag(self):
splittag = urllib.parse.splittag
self.assertEqual(splittag('http://example.com?foo=bar#baz'),
('http://example.com?foo=bar', 'baz'))
self.assertEqual(splittag('http://example.com?foo=bar#'),
('http://example.com?foo=bar', ''))
self.assertEqual(splittag('#baz'), ('', 'baz'))
self.assertEqual(splittag('http://example.com?foo=bar'),
('http://example.com?foo=bar', None))
self.assertEqual(splittag('http://example.com?foo=bar#baz#boo'),
('http://example.com?foo=bar#baz', 'boo'))
def test_splitattr(self):
splitattr = urllib.parse.splitattr
self.assertEqual(splitattr('/path;attr1=value1;attr2=value2'),
('/path', ['attr1=value1', 'attr2=value2']))
self.assertEqual(splitattr('/path;'), ('/path', ['']))
self.assertEqual(splitattr(';attr1=value1;attr2=value2'),
('', ['attr1=value1', 'attr2=value2']))
self.assertEqual(splitattr('/path'), ('/path', []))
def test_splitvalue(self):
# Normal cases are exercised by other tests; test pathological cases
# with no key/value pairs. (testcase ensuring coverage)
splitvalue = urllib.parse.splitvalue
self.assertEqual(splitvalue('foo=bar'), ('foo', 'bar'))
self.assertEqual(splitvalue('foo='), ('foo', ''))
self.assertEqual(splitvalue('=bar'), ('', 'bar'))
self.assertEqual(splitvalue('foobar'), ('foobar', None))
self.assertEqual(splitvalue('foo=bar=baz'), ('foo', 'bar=baz'))
def test_to_bytes(self):
result = urllib.parse.to_bytes('http://www.python.org')
self.assertEqual(result, 'http://www.python.org')
self.assertRaises(UnicodeError, urllib.parse.to_bytes,
'http://www.python.org/medi\u00e6val')
def test_unwrap(self):
url = urllib.parse.unwrap('<URL:type://host/path>')
self.assertEqual(url, 'type://host/path')
if __name__ == "__main__":
unittest.main()
| 61,969 | 1,241 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_unittest.py | import unittest.test
from test import support
def test_main():
# used by regrtest
support.run_unittest(unittest.test.suite())
support.reap_children()
def load_tests(*_):
# used by unittest
return unittest.test.suite()
if __name__ == "__main__":
test_main()
| 286 | 17 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_unicode.py | """ Test script for the Unicode implementation.
Written by Marc-Andre Lemburg ([email protected]).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""
import _string
import codecs
import itertools
import operator
import struct
import string
import sys
import unittest
import warnings
from test import support, string_tests
from encodings import (
aliases,
base64_codec,
big5,
big5hkscs,
bz2_codec,
charmap,
cp037,
cp1006,
cp1026,
cp1125,
cp1140,
cp1250,
cp1251,
cp1252,
cp1253,
cp1254,
cp1255,
cp1256,
cp1257,
cp1258,
cp273,
cp424,
cp437,
cp500,
cp720,
cp737,
cp775,
cp850,
cp852,
cp855,
cp856,
cp857,
cp858,
cp860,
cp861,
cp862,
cp863,
cp864,
cp865,
cp866,
cp869,
cp874,
cp875,
cp932,
cp949,
cp950,
euc_jis_2004,
euc_jisx0213,
euc_jp,
euc_kr,
gb18030,
gb2312,
gbk,
hex_codec,
hp_roman8,
hz,
idna,
iso2022_jp,
iso2022_jp_1,
iso2022_jp_2,
iso2022_jp_2004,
iso2022_jp_3,
iso2022_jp_ext,
iso2022_kr,
iso8859_1,
iso8859_10,
iso8859_11,
iso8859_13,
iso8859_14,
iso8859_15,
iso8859_16,
iso8859_2,
iso8859_3,
iso8859_4,
iso8859_5,
iso8859_6,
iso8859_7,
iso8859_8,
iso8859_9,
johab,
koi8_r,
koi8_t,
koi8_u,
kz1048,
latin_1,
mac_arabic,
mac_centeuro,
mac_croatian,
mac_cyrillic,
mac_farsi,
mac_greek,
mac_iceland,
mac_latin2,
mac_roman,
mac_romanian,
mac_turkish,
palmos,
ptcp154,
punycode,
quopri_codec,
raw_unicode_escape,
rot_13,
shift_jis,
shift_jis_2004,
shift_jisx0213,
tis_620,
undefined,
unicode_escape,
unicode_internal,
utf_16,
utf_16_be,
utf_16_le,
utf_32,
utf_32_be,
utf_32_le,
utf_7,
utf_8,
utf_8_sig,
uu_codec,
zlib_codec,
)
# Error handling (bad decoder return)
def search_function(encoding):
def decode1(input, errors="strict"):
return 42 # not a tuple
def encode1(input, errors="strict"):
return 42 # not a tuple
def encode2(input, errors="strict"):
return (42, 42) # no unicode
def decode2(input, errors="strict"):
return (42, 42) # no unicode
if encoding=="test.unicode1":
return (encode1, decode1, None, None)
elif encoding=="test.unicode2":
return (encode2, decode2, None, None)
else:
return None
codecs.register(search_function)
def duplicate_string(text):
"""
Try to get a fresh clone of the specified text:
new object with a reference count of 1.
This is a best-effort: latin1 single letters and the empty
string ('') are singletons and cannot be cloned.
"""
return text.encode().decode()
class StrSubclass(str):
pass
class UnicodeTest(string_tests.CommonTest,
string_tests.MixinStrUnicodeUserStringTest,
string_tests.MixinStrUnicodeTest,
unittest.TestCase):
type2test = str
def checkequalnofix(self, result, object, methodname, *args):
method = getattr(object, methodname)
realresult = method(*args)
self.assertEqual(realresult, result)
self.assertTrue(type(realresult) is type(result))
# if the original is returned make sure that
# this doesn't happen with subclasses
if realresult is object:
class usub(str):
def __repr__(self):
return 'usub(%r)' % str.__repr__(self)
object = usub(object)
method = getattr(object, methodname)
realresult = method(*args)
self.assertEqual(realresult, result)
self.assertTrue(object is not realresult)
def test_literals(self):
self.assertEqual('\xff', '\u00ff')
self.assertEqual('\uffff', '\U0000ffff')
self.assertRaises(SyntaxError, eval, '\'\\Ufffffffe\'')
self.assertRaises(SyntaxError, eval, '\'\\Uffffffff\'')
self.assertRaises(SyntaxError, eval, '\'\\U%08x\'' % 0x110000)
# raw strings should not have unicode escapes
self.assertNotEqual(r"\u0020", " ")
def test_ascii(self):
if not sys.platform.startswith('java'):
# Test basic sanity of repr()
self.assertEqual(ascii('abc'), "'abc'")
self.assertEqual(ascii('ab\\c'), "'ab\\\\c'")
self.assertEqual(ascii('ab\\'), "'ab\\\\'")
self.assertEqual(ascii('\\c'), "'\\\\c'")
self.assertEqual(ascii('\\'), "'\\\\'")
self.assertEqual(ascii('\n'), "'\\n'")
self.assertEqual(ascii('\r'), "'\\r'")
self.assertEqual(ascii('\t'), "'\\t'")
self.assertEqual(ascii('\b'), "'\\x08'")
self.assertEqual(ascii("'\""), """'\\'"'""")
self.assertEqual(ascii("'\""), """'\\'"'""")
self.assertEqual(ascii("'"), '''"'"''')
self.assertEqual(ascii('"'), """'"'""")
latin1repr = (
"'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
"\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
"\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
"JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
"\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
"\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
"\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9"
"\\xaa\\xab\\xac\\xad\\xae\\xaf\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7"
"\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5"
"\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3"
"\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1"
"\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef"
"\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd"
"\\xfe\\xff'")
testrepr = ascii(''.join(map(chr, range(256))))
self.assertEqual(testrepr, latin1repr)
# Test ascii works on wide unicode escapes without overflow.
self.assertEqual(ascii("\U00010000" * 39 + "\uffff" * 4096),
ascii("\U00010000" * 39 + "\uffff" * 4096))
class WrongRepr:
def __repr__(self):
return b'byte-repr'
self.assertRaises(TypeError, ascii, WrongRepr())
def test_repr(self):
if not sys.platform.startswith('java'):
# Test basic sanity of repr()
self.assertEqual(repr('abc'), "'abc'")
self.assertEqual(repr('ab\\c'), "'ab\\\\c'")
self.assertEqual(repr('ab\\'), "'ab\\\\'")
self.assertEqual(repr('\\c'), "'\\\\c'")
self.assertEqual(repr('\\'), "'\\\\'")
self.assertEqual(repr('\n'), "'\\n'")
self.assertEqual(repr('\r'), "'\\r'")
self.assertEqual(repr('\t'), "'\\t'")
self.assertEqual(repr('\b'), "'\\x08'")
self.assertEqual(repr("'\""), """'\\'"'""")
self.assertEqual(repr("'\""), """'\\'"'""")
self.assertEqual(repr("'"), '''"'"''')
self.assertEqual(repr('"'), """'"'""")
latin1repr = (
"'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
"\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
"\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
"JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
"\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
"\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
"\\x9c\\x9d\\x9e\\x9f\\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9"
"\xaa\xab\xac\\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7"
"\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5"
"\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3"
"\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1"
"\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef"
"\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd"
"\xfe\xff'")
testrepr = repr(''.join(map(chr, range(256))))
self.assertEqual(testrepr, latin1repr)
# Test repr works on wide unicode escapes without overflow.
self.assertEqual(repr("\U00010000" * 39 + "\uffff" * 4096),
repr("\U00010000" * 39 + "\uffff" * 4096))
class WrongRepr:
def __repr__(self):
return b'byte-repr'
self.assertRaises(TypeError, repr, WrongRepr())
def test_iterators(self):
# Make sure unicode objects have an __iter__ method
it = "\u1111\u2222\u3333".__iter__()
self.assertEqual(next(it), "\u1111")
self.assertEqual(next(it), "\u2222")
self.assertEqual(next(it), "\u3333")
self.assertRaises(StopIteration, next, it)
def test_count(self):
string_tests.CommonTest.test_count(self)
# check mixed argument types
self.checkequalnofix(3, 'aaa', 'count', 'a')
self.checkequalnofix(0, 'aaa', 'count', 'b')
self.checkequalnofix(3, 'aaa', 'count', 'a')
self.checkequalnofix(0, 'aaa', 'count', 'b')
self.checkequalnofix(0, 'aaa', 'count', 'b')
self.checkequalnofix(1, 'aaa', 'count', 'a', -1)
self.checkequalnofix(3, 'aaa', 'count', 'a', -10)
self.checkequalnofix(2, 'aaa', 'count', 'a', 0, -1)
self.checkequalnofix(0, 'aaa', 'count', 'a', 0, -10)
# test mixed kinds
self.checkequal(10, '\u0102' + 'a' * 10, 'count', 'a')
self.checkequal(10, '\U00100304' + 'a' * 10, 'count', 'a')
self.checkequal(10, '\U00100304' + '\u0102' * 10, 'count', '\u0102')
self.checkequal(0, 'a' * 10, 'count', '\u0102')
self.checkequal(0, 'a' * 10, 'count', '\U00100304')
self.checkequal(0, '\u0102' * 10, 'count', '\U00100304')
self.checkequal(10, '\u0102' + 'a_' * 10, 'count', 'a_')
self.checkequal(10, '\U00100304' + 'a_' * 10, 'count', 'a_')
self.checkequal(10, '\U00100304' + '\u0102_' * 10, 'count', '\u0102_')
self.checkequal(0, 'a' * 10, 'count', 'a\u0102')
self.checkequal(0, 'a' * 10, 'count', 'a\U00100304')
self.checkequal(0, '\u0102' * 10, 'count', '\u0102\U00100304')
def test_find(self):
string_tests.CommonTest.test_find(self)
# test implementation details of the memchr fast path
self.checkequal(100, 'a' * 100 + '\u0102', 'find', '\u0102')
self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0201')
self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0120')
self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0220')
self.checkequal(100, 'a' * 100 + '\U00100304', 'find', '\U00100304')
self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00100204')
self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00102004')
# check mixed argument types
self.checkequalnofix(0, 'abcdefghiabc', 'find', 'abc')
self.checkequalnofix(9, 'abcdefghiabc', 'find', 'abc', 1)
self.checkequalnofix(-1, 'abcdefghiabc', 'find', 'def', 4)
self.assertRaises(TypeError, 'hello'.find)
self.assertRaises(TypeError, 'hello'.find, 42)
# test mixed kinds
self.checkequal(100, '\u0102' * 100 + 'a', 'find', 'a')
self.checkequal(100, '\U00100304' * 100 + 'a', 'find', 'a')
self.checkequal(100, '\U00100304' * 100 + '\u0102', 'find', '\u0102')
self.checkequal(-1, 'a' * 100, 'find', '\u0102')
self.checkequal(-1, 'a' * 100, 'find', '\U00100304')
self.checkequal(-1, '\u0102' * 100, 'find', '\U00100304')
self.checkequal(100, '\u0102' * 100 + 'a_', 'find', 'a_')
self.checkequal(100, '\U00100304' * 100 + 'a_', 'find', 'a_')
self.checkequal(100, '\U00100304' * 100 + '\u0102_', 'find', '\u0102_')
self.checkequal(-1, 'a' * 100, 'find', 'a\u0102')
self.checkequal(-1, 'a' * 100, 'find', 'a\U00100304')
self.checkequal(-1, '\u0102' * 100, 'find', '\u0102\U00100304')
def test_rfind(self):
string_tests.CommonTest.test_rfind(self)
# test implementation details of the memrchr fast path
self.checkequal(0, '\u0102' + 'a' * 100 , 'rfind', '\u0102')
self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0201')
self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0120')
self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0220')
self.checkequal(0, '\U00100304' + 'a' * 100, 'rfind', '\U00100304')
self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00100204')
self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00102004')
# check mixed argument types
self.checkequalnofix(9, 'abcdefghiabc', 'rfind', 'abc')
self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
# test mixed kinds
self.checkequal(0, 'a' + '\u0102' * 100, 'rfind', 'a')
self.checkequal(0, 'a' + '\U00100304' * 100, 'rfind', 'a')
self.checkequal(0, '\u0102' + '\U00100304' * 100, 'rfind', '\u0102')
self.checkequal(-1, 'a' * 100, 'rfind', '\u0102')
self.checkequal(-1, 'a' * 100, 'rfind', '\U00100304')
self.checkequal(-1, '\u0102' * 100, 'rfind', '\U00100304')
self.checkequal(0, '_a' + '\u0102' * 100, 'rfind', '_a')
self.checkequal(0, '_a' + '\U00100304' * 100, 'rfind', '_a')
self.checkequal(0, '_\u0102' + '\U00100304' * 100, 'rfind', '_\u0102')
self.checkequal(-1, 'a' * 100, 'rfind', '\u0102a')
self.checkequal(-1, 'a' * 100, 'rfind', '\U00100304a')
self.checkequal(-1, '\u0102' * 100, 'rfind', '\U00100304\u0102')
def test_index(self):
string_tests.CommonTest.test_index(self)
self.checkequalnofix(0, 'abcdefghiabc', 'index', '')
self.checkequalnofix(3, 'abcdefghiabc', 'index', 'def')
self.checkequalnofix(0, 'abcdefghiabc', 'index', 'abc')
self.checkequalnofix(9, 'abcdefghiabc', 'index', 'abc', 1)
self.assertRaises(ValueError, 'abcdefghiabc'.index, 'hib')
self.assertRaises(ValueError, 'abcdefghiab'.index, 'abc', 1)
self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', 8)
self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', -1)
# test mixed kinds
self.checkequal(100, '\u0102' * 100 + 'a', 'index', 'a')
self.checkequal(100, '\U00100304' * 100 + 'a', 'index', 'a')
self.checkequal(100, '\U00100304' * 100 + '\u0102', 'index', '\u0102')
self.assertRaises(ValueError, ('a' * 100).index, '\u0102')
self.assertRaises(ValueError, ('a' * 100).index, '\U00100304')
self.assertRaises(ValueError, ('\u0102' * 100).index, '\U00100304')
self.checkequal(100, '\u0102' * 100 + 'a_', 'index', 'a_')
self.checkequal(100, '\U00100304' * 100 + 'a_', 'index', 'a_')
self.checkequal(100, '\U00100304' * 100 + '\u0102_', 'index', '\u0102_')
self.assertRaises(ValueError, ('a' * 100).index, 'a\u0102')
self.assertRaises(ValueError, ('a' * 100).index, 'a\U00100304')
self.assertRaises(ValueError, ('\u0102' * 100).index, '\u0102\U00100304')
def test_rindex(self):
string_tests.CommonTest.test_rindex(self)
self.checkequalnofix(12, 'abcdefghiabc', 'rindex', '')
self.checkequalnofix(3, 'abcdefghiabc', 'rindex', 'def')
self.checkequalnofix(9, 'abcdefghiabc', 'rindex', 'abc')
self.checkequalnofix(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
self.assertRaises(ValueError, 'abcdefghiabc'.rindex, 'hib')
self.assertRaises(ValueError, 'defghiabc'.rindex, 'def', 1)
self.assertRaises(ValueError, 'defghiabc'.rindex, 'abc', 0, -1)
self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, 8)
self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, -1)
# test mixed kinds
self.checkequal(0, 'a' + '\u0102' * 100, 'rindex', 'a')
self.checkequal(0, 'a' + '\U00100304' * 100, 'rindex', 'a')
self.checkequal(0, '\u0102' + '\U00100304' * 100, 'rindex', '\u0102')
self.assertRaises(ValueError, ('a' * 100).rindex, '\u0102')
self.assertRaises(ValueError, ('a' * 100).rindex, '\U00100304')
self.assertRaises(ValueError, ('\u0102' * 100).rindex, '\U00100304')
self.checkequal(0, '_a' + '\u0102' * 100, 'rindex', '_a')
self.checkequal(0, '_a' + '\U00100304' * 100, 'rindex', '_a')
self.checkequal(0, '_\u0102' + '\U00100304' * 100, 'rindex', '_\u0102')
self.assertRaises(ValueError, ('a' * 100).rindex, '\u0102a')
self.assertRaises(ValueError, ('a' * 100).rindex, '\U00100304a')
self.assertRaises(ValueError, ('\u0102' * 100).rindex, '\U00100304\u0102')
def test_maketrans_translate(self):
# these work with plain translate()
self.checkequalnofix('bbbc', 'abababc', 'translate',
{ord('a'): None})
self.checkequalnofix('iiic', 'abababc', 'translate',
{ord('a'): None, ord('b'): ord('i')})
self.checkequalnofix('iiix', 'abababc', 'translate',
{ord('a'): None, ord('b'): ord('i'), ord('c'): 'x'})
self.checkequalnofix('c', 'abababc', 'translate',
{ord('a'): None, ord('b'): ''})
self.checkequalnofix('xyyx', 'xzx', 'translate',
{ord('z'): 'yy'})
# this needs maketrans()
self.checkequalnofix('abababc', 'abababc', 'translate',
{'b': '<i>'})
tbl = self.type2test.maketrans({'a': None, 'b': '<i>'})
self.checkequalnofix('<i><i><i>c', 'abababc', 'translate', tbl)
# test alternative way of calling maketrans()
tbl = self.type2test.maketrans('abc', 'xyz', 'd')
self.checkequalnofix('xyzzy', 'abdcdcbdddd', 'translate', tbl)
# various tests switching from ASCII to latin1 or the opposite;
# same length, remove a letter, or replace with a longer string.
self.assertEqual("[a]".translate(str.maketrans('a', 'X')),
"[X]")
self.assertEqual("[a]".translate(str.maketrans({'a': 'X'})),
"[X]")
self.assertEqual("[a]".translate(str.maketrans({'a': None})),
"[]")
self.assertEqual("[a]".translate(str.maketrans({'a': 'XXX'})),
"[XXX]")
self.assertEqual("[a]".translate(str.maketrans({'a': '\xe9'})),
"[\xe9]")
self.assertEqual('axb'.translate(str.maketrans({'a': None, 'b': '123'})),
"x123")
self.assertEqual('axb'.translate(str.maketrans({'a': None, 'b': '\xe9'})),
"x\xe9")
# test non-ASCII (don't take the fast-path)
self.assertEqual("[a]".translate(str.maketrans({'a': '<\xe9>'})),
"[<\xe9>]")
self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': 'a'})),
"[a]")
self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': None})),
"[]")
self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': '123'})),
"[123]")
self.assertEqual("[a\xe9]".translate(str.maketrans({'a': '<\u20ac>'})),
"[<\u20ac>\xe9]")
# invalid Unicode characters
invalid_char = 0x10ffff+1
for before in "a\xe9\u20ac\U0010ffff":
mapping = str.maketrans({before: invalid_char})
text = "[%s]" % before
self.assertRaises(ValueError, text.translate, mapping)
# errors
self.assertRaises(TypeError, self.type2test.maketrans)
self.assertRaises(ValueError, self.type2test.maketrans, 'abc', 'defg')
self.assertRaises(TypeError, self.type2test.maketrans, 2, 'def')
self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 2)
self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 'def', 2)
self.assertRaises(ValueError, self.type2test.maketrans, {'xy': 2})
self.assertRaises(TypeError, self.type2test.maketrans, {(1,): 2})
self.assertRaises(TypeError, 'hello'.translate)
self.assertRaises(TypeError, 'abababc'.translate, 'abc', 'xyz')
def test_split(self):
string_tests.CommonTest.test_split(self)
# test mixed kinds
for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
left *= 9
right *= 9
for delim in ('c', '\u0102', '\U00010302'):
self.checkequal([left + right],
left + right, 'split', delim)
self.checkequal([left, right],
left + delim + right, 'split', delim)
self.checkequal([left + right],
left + right, 'split', delim * 2)
self.checkequal([left, right],
left + delim * 2 + right, 'split', delim *2)
def test_rsplit(self):
string_tests.CommonTest.test_rsplit(self)
# test mixed kinds
for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
left *= 9
right *= 9
for delim in ('c', '\u0102', '\U00010302'):
self.checkequal([left + right],
left + right, 'rsplit', delim)
self.checkequal([left, right],
left + delim + right, 'rsplit', delim)
self.checkequal([left + right],
left + right, 'rsplit', delim * 2)
self.checkequal([left, right],
left + delim * 2 + right, 'rsplit', delim *2)
def test_partition(self):
string_tests.MixinStrUnicodeUserStringTest.test_partition(self)
# test mixed kinds
self.checkequal(('ABCDEFGH', '', ''), 'ABCDEFGH', 'partition', '\u4200')
for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
left *= 9
right *= 9
for delim in ('c', '\u0102', '\U00010302'):
self.checkequal((left + right, '', ''),
left + right, 'partition', delim)
self.checkequal((left, delim, right),
left + delim + right, 'partition', delim)
self.checkequal((left + right, '', ''),
left + right, 'partition', delim * 2)
self.checkequal((left, delim * 2, right),
left + delim * 2 + right, 'partition', delim * 2)
def test_rpartition(self):
string_tests.MixinStrUnicodeUserStringTest.test_rpartition(self)
# test mixed kinds
self.checkequal(('', '', 'ABCDEFGH'), 'ABCDEFGH', 'rpartition', '\u4200')
for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
left *= 9
right *= 9
for delim in ('c', '\u0102', '\U00010302'):
self.checkequal(('', '', left + right),
left + right, 'rpartition', delim)
self.checkequal((left, delim, right),
left + delim + right, 'rpartition', delim)
self.checkequal(('', '', left + right),
left + right, 'rpartition', delim * 2)
self.checkequal((left, delim * 2, right),
left + delim * 2 + right, 'rpartition', delim * 2)
def test_join(self):
string_tests.MixinStrUnicodeUserStringTest.test_join(self)
class MyWrapper:
def __init__(self, sval): self.sval = sval
def __str__(self): return self.sval
# mixed arguments
self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
self.checkraises(TypeError, ' ', 'join', ['1', '2', MyWrapper('foo')])
self.checkraises(TypeError, ' ', 'join', ['1', '2', '3', bytes()])
self.checkraises(TypeError, ' ', 'join', [1, 2, 3])
self.checkraises(TypeError, ' ', 'join', ['1', '2', 3])
@unittest.skipIf(sys.maxsize > 2**32,
'needs too much memory on a 64-bit platform')
def test_join_overflow(self):
size = int(sys.maxsize**0.5) + 1
seq = ('A' * size,) * size
self.assertRaises(OverflowError, ''.join, seq)
def test_replace(self):
string_tests.CommonTest.test_replace(self)
# method call forwarded from str implementation because of unicode argument
self.checkequalnofix('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
self.assertRaises(TypeError, 'replace'.replace, "r", 42)
# test mixed kinds
for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
left *= 9
right *= 9
for delim in ('c', '\u0102', '\U00010302'):
for repl in ('d', '\u0103', '\U00010303'):
self.checkequal(left + right,
left + right, 'replace', delim, repl)
self.checkequal(left + repl + right,
left + delim + right,
'replace', delim, repl)
self.checkequal(left + right,
left + right, 'replace', delim * 2, repl)
self.checkequal(left + repl + right,
left + delim * 2 + right,
'replace', delim * 2, repl)
@support.cpython_only
def test_replace_id(self):
pattern = 'abc'
text = 'abc def'
self.assertIs(text.replace(pattern, pattern), text)
def test_bytes_comparison(self):
with support.check_warnings():
warnings.simplefilter('ignore', BytesWarning)
self.assertEqual('abc' == b'abc', False)
self.assertEqual('abc' != b'abc', True)
self.assertEqual('abc' == bytearray(b'abc'), False)
self.assertEqual('abc' != bytearray(b'abc'), True)
def test_comparison(self):
# Comparisons:
self.assertEqual('abc', 'abc')
self.assertTrue('abcd' > 'abc')
self.assertTrue('abc' < 'abcd')
if 0:
# Move these tests to a Unicode collation module test...
# Testing UTF-16 code point order comparisons...
# No surrogates, no fixup required.
self.assertTrue('\u0061' < '\u20ac')
# Non surrogate below surrogate value, no fixup required
self.assertTrue('\u0061' < '\ud800\udc02')
# Non surrogate above surrogate value, fixup required
def test_lecmp(s, s2):
self.assertTrue(s < s2)
def test_fixup(s):
s2 = '\ud800\udc01'
test_lecmp(s, s2)
s2 = '\ud900\udc01'
test_lecmp(s, s2)
s2 = '\uda00\udc01'
test_lecmp(s, s2)
s2 = '\udb00\udc01'
test_lecmp(s, s2)
s2 = '\ud800\udd01'
test_lecmp(s, s2)
s2 = '\ud900\udd01'
test_lecmp(s, s2)
s2 = '\uda00\udd01'
test_lecmp(s, s2)
s2 = '\udb00\udd01'
test_lecmp(s, s2)
s2 = '\ud800\ude01'
test_lecmp(s, s2)
s2 = '\ud900\ude01'
test_lecmp(s, s2)
s2 = '\uda00\ude01'
test_lecmp(s, s2)
s2 = '\udb00\ude01'
test_lecmp(s, s2)
s2 = '\ud800\udfff'
test_lecmp(s, s2)
s2 = '\ud900\udfff'
test_lecmp(s, s2)
s2 = '\uda00\udfff'
test_lecmp(s, s2)
s2 = '\udb00\udfff'
test_lecmp(s, s2)
test_fixup('\ue000')
test_fixup('\uff61')
# Surrogates on both sides, no fixup required
self.assertTrue('\ud800\udc02' < '\ud84d\udc56')
def test_islower(self):
super().test_islower()
self.checkequalnofix(False, '\u1FFc', 'islower')
self.assertFalse('\u2167'.islower())
self.assertTrue('\u2177'.islower())
# non-BMP, uppercase
self.assertFalse('\U00010401'.islower())
self.assertFalse('\U00010427'.islower())
# non-BMP, lowercase
self.assertTrue('\U00010429'.islower())
self.assertTrue('\U0001044E'.islower())
# non-BMP, non-cased
self.assertFalse('\U0001F40D'.islower())
self.assertFalse('\U0001F46F'.islower())
def test_isupper(self):
super().test_isupper()
if not sys.platform.startswith('java'):
self.checkequalnofix(False, '\u1FFc', 'isupper')
self.assertTrue('\u2167'.isupper())
self.assertFalse('\u2177'.isupper())
# non-BMP, uppercase
self.assertTrue('\U00010401'.isupper())
self.assertTrue('\U00010427'.isupper())
# non-BMP, lowercase
self.assertFalse('\U00010429'.isupper())
self.assertFalse('\U0001044E'.isupper())
# non-BMP, non-cased
self.assertFalse('\U0001F40D'.isupper())
self.assertFalse('\U0001F46F'.isupper())
def test_istitle(self):
super().test_istitle()
self.checkequalnofix(True, '\u1FFc', 'istitle')
self.checkequalnofix(True, 'Greek \u1FFcitlecases ...', 'istitle')
# non-BMP, uppercase + lowercase
self.assertTrue('\U00010401\U00010429'.istitle())
self.assertTrue('\U00010427\U0001044E'.istitle())
# apparently there are no titlecased (Lt) non-BMP chars in Unicode 6
for ch in ['\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F']:
self.assertFalse(ch.istitle(), '{!a} is not title'.format(ch))
def test_isspace(self):
super().test_isspace()
self.checkequalnofix(True, '\u2000', 'isspace')
self.checkequalnofix(True, '\u200a', 'isspace')
self.checkequalnofix(False, '\u2014', 'isspace')
# apparently there are no non-BMP spaces chars in Unicode 6
for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
'\U0001F40D', '\U0001F46F']:
self.assertFalse(ch.isspace(), '{!a} is not space.'.format(ch))
def test_isalnum(self):
super().test_isalnum()
for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
'\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
self.assertTrue(ch.isalnum(), '{!a} is alnum.'.format(ch))
def test_isalpha(self):
super().test_isalpha()
self.checkequalnofix(True, '\u1FFc', 'isalpha')
# non-BMP, cased
self.assertTrue('\U00010401'.isalpha())
self.assertTrue('\U00010427'.isalpha())
self.assertTrue('\U00010429'.isalpha())
self.assertTrue('\U0001044E'.isalpha())
# non-BMP, non-cased
self.assertFalse('\U0001F40D'.isalpha())
self.assertFalse('\U0001F46F'.isalpha())
def test_isdecimal(self):
self.checkequalnofix(False, '', 'isdecimal')
self.checkequalnofix(False, 'a', 'isdecimal')
self.checkequalnofix(True, '0', 'isdecimal')
self.checkequalnofix(False, '\u2460', 'isdecimal') # CIRCLED DIGIT ONE
self.checkequalnofix(False, '\xbc', 'isdecimal') # VULGAR FRACTION ONE QUARTER
self.checkequalnofix(True, '\u0660', 'isdecimal') # ARABIC-INDIC DIGIT ZERO
self.checkequalnofix(True, '0123456789', 'isdecimal')
self.checkequalnofix(False, '0123456789a', 'isdecimal')
self.checkraises(TypeError, 'abc', 'isdecimal', 42)
for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
'\U0001F40D', '\U0001F46F', '\U00011065', '\U0001F107']:
self.assertFalse(ch.isdecimal(), '{!a} is not decimal.'.format(ch))
for ch in ['\U0001D7F6', '\U00011066', '\U000104A0']:
self.assertTrue(ch.isdecimal(), '{!a} is decimal.'.format(ch))
def test_isdigit(self):
super().test_isdigit()
self.checkequalnofix(True, '\u2460', 'isdigit')
self.checkequalnofix(False, '\xbc', 'isdigit')
self.checkequalnofix(True, '\u0660', 'isdigit')
for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
'\U0001F40D', '\U0001F46F', '\U00011065']:
self.assertFalse(ch.isdigit(), '{!a} is not a digit.'.format(ch))
for ch in ['\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
self.assertTrue(ch.isdigit(), '{!a} is a digit.'.format(ch))
def test_isnumeric(self):
self.checkequalnofix(False, '', 'isnumeric')
self.checkequalnofix(False, 'a', 'isnumeric')
self.checkequalnofix(True, '0', 'isnumeric')
self.checkequalnofix(True, '\u2460', 'isnumeric')
self.checkequalnofix(True, '\xbc', 'isnumeric')
self.checkequalnofix(True, '\u0660', 'isnumeric')
self.checkequalnofix(True, '0123456789', 'isnumeric')
self.checkequalnofix(False, '0123456789a', 'isnumeric')
self.assertRaises(TypeError, "abc".isnumeric, 42)
for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
'\U0001F40D', '\U0001F46F']:
self.assertFalse(ch.isnumeric(), '{!a} is not numeric.'.format(ch))
for ch in ['\U00011065', '\U0001D7F6', '\U00011066',
'\U000104A0', '\U0001F107']:
self.assertTrue(ch.isnumeric(), '{!a} is numeric.'.format(ch))
def test_isidentifier(self):
self.assertTrue("a".isidentifier())
self.assertTrue("Z".isidentifier())
self.assertTrue("_".isidentifier())
self.assertTrue("b0".isidentifier())
self.assertTrue("bc".isidentifier())
self.assertTrue("b_".isidentifier())
self.assertTrue("µ".isidentifier())
self.assertTrue("ðð«ð¦ð ð¬ð¡ð¢".isidentifier())
self.assertFalse(" ".isidentifier())
self.assertFalse("[".isidentifier())
self.assertFalse("©".isidentifier())
self.assertFalse("0".isidentifier())
def test_isprintable(self):
self.assertTrue("".isprintable())
self.assertTrue(" ".isprintable())
self.assertTrue("abcdefg".isprintable())
self.assertFalse("abcdefg\n".isprintable())
# some defined Unicode character
self.assertTrue("\u0374".isprintable())
# undefined character
self.assertFalse("\u0378".isprintable())
# single surrogate character
self.assertFalse("\ud800".isprintable())
self.assertTrue('\U0001F46F'.isprintable())
self.assertFalse('\U000E0020'.isprintable())
def test_surrogates(self):
for s in ('a\uD800b\uDFFF', 'a\uDFFFb\uD800',
'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
self.assertTrue(s.islower())
self.assertFalse(s.isupper())
self.assertFalse(s.istitle())
for s in ('A\uD800B\uDFFF', 'A\uDFFFB\uD800',
'A\uD800B\uDFFFA', 'A\uDFFFB\uD800A'):
self.assertFalse(s.islower())
self.assertTrue(s.isupper())
self.assertTrue(s.istitle())
for meth_name in ('islower', 'isupper', 'istitle'):
meth = getattr(str, meth_name)
for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF'):
self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
for meth_name in ('isalpha', 'isalnum', 'isdigit', 'isspace',
'isdecimal', 'isnumeric',
'isidentifier', 'isprintable'):
meth = getattr(str, meth_name)
for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF',
'a\uD800b\uDFFF', 'a\uDFFFb\uD800',
'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
def test_lower(self):
string_tests.CommonTest.test_lower(self)
self.assertEqual('\U00010427'.lower(), '\U0001044F')
self.assertEqual('\U00010427\U00010427'.lower(),
'\U0001044F\U0001044F')
self.assertEqual('\U00010427\U0001044F'.lower(),
'\U0001044F\U0001044F')
self.assertEqual('X\U00010427x\U0001044F'.lower(),
'x\U0001044Fx\U0001044F')
self.assertEqual('ï¬'.lower(), 'ï¬')
self.assertEqual('\u0130'.lower(), '\u0069\u0307')
# Special case for GREEK CAPITAL LETTER SIGMA U+03A3
self.assertEqual('\u03a3'.lower(), '\u03c3')
self.assertEqual('\u0345\u03a3'.lower(), '\u0345\u03c3')
self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
self.assertEqual('A\u0345\u03a3a'.lower(), 'a\u0345\u03c3a')
self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
self.assertEqual('A\u03a3\u0345'.lower(), 'a\u03c2\u0345')
self.assertEqual('\u03a3\u0345 '.lower(), '\u03c3\u0345 ')
self.assertEqual('\U0008fffe'.lower(), '\U0008fffe')
self.assertEqual('\u2177'.lower(), '\u2177')
def test_casefold(self):
self.assertEqual('hello'.casefold(), 'hello')
self.assertEqual('hELlo'.casefold(), 'hello')
self.assertEqual('Ã'.casefold(), 'ss')
self.assertEqual('ï¬'.casefold(), 'fi')
self.assertEqual('\u03a3'.casefold(), '\u03c3')
self.assertEqual('A\u0345\u03a3'.casefold(), 'a\u03b9\u03c3')
self.assertEqual('\u00b5'.casefold(), '\u03bc')
def test_upper(self):
string_tests.CommonTest.test_upper(self)
self.assertEqual('\U0001044F'.upper(), '\U00010427')
self.assertEqual('\U0001044F\U0001044F'.upper(),
'\U00010427\U00010427')
self.assertEqual('\U00010427\U0001044F'.upper(),
'\U00010427\U00010427')
self.assertEqual('X\U00010427x\U0001044F'.upper(),
'X\U00010427X\U00010427')
self.assertEqual('ï¬'.upper(), 'FI')
self.assertEqual('\u0130'.upper(), '\u0130')
self.assertEqual('\u03a3'.upper(), '\u03a3')
self.assertEqual('Ã'.upper(), 'SS')
self.assertEqual('\u1fd2'.upper(), '\u0399\u0308\u0300')
self.assertEqual('\U0008fffe'.upper(), '\U0008fffe')
self.assertEqual('\u2177'.upper(), '\u2167')
def test_capitalize(self):
string_tests.CommonTest.test_capitalize(self)
self.assertEqual('\U0001044F'.capitalize(), '\U00010427')
self.assertEqual('\U0001044F\U0001044F'.capitalize(),
'\U00010427\U0001044F')
self.assertEqual('\U00010427\U0001044F'.capitalize(),
'\U00010427\U0001044F')
self.assertEqual('\U0001044F\U00010427'.capitalize(),
'\U00010427\U0001044F')
self.assertEqual('X\U00010427x\U0001044F'.capitalize(),
'X\U0001044Fx\U0001044F')
self.assertEqual('h\u0130'.capitalize(), 'H\u0069\u0307')
exp = '\u0399\u0308\u0300\u0069\u0307'
self.assertEqual('\u1fd2\u0130'.capitalize(), exp)
self.assertEqual('ï¬nnish'.capitalize(), 'FInnish')
self.assertEqual('A\u0345\u03a3'.capitalize(), 'A\u0345\u03c2')
def test_title(self):
super().test_title()
self.assertEqual('\U0001044F'.title(), '\U00010427')
self.assertEqual('\U0001044F\U0001044F'.title(),
'\U00010427\U0001044F')
self.assertEqual('\U0001044F\U0001044F \U0001044F\U0001044F'.title(),
'\U00010427\U0001044F \U00010427\U0001044F')
self.assertEqual('\U00010427\U0001044F \U00010427\U0001044F'.title(),
'\U00010427\U0001044F \U00010427\U0001044F')
self.assertEqual('\U0001044F\U00010427 \U0001044F\U00010427'.title(),
'\U00010427\U0001044F \U00010427\U0001044F')
self.assertEqual('X\U00010427x\U0001044F X\U00010427x\U0001044F'.title(),
'X\U0001044Fx\U0001044F X\U0001044Fx\U0001044F')
self.assertEqual('ï¬NNISH'.title(), 'Finnish')
self.assertEqual('A\u03a3 \u1fa1xy'.title(), 'A\u03c2 \u1fa9xy')
self.assertEqual('A\u03a3A'.title(), 'A\u03c3a')
def test_swapcase(self):
string_tests.CommonTest.test_swapcase(self)
self.assertEqual('\U0001044F'.swapcase(), '\U00010427')
self.assertEqual('\U00010427'.swapcase(), '\U0001044F')
self.assertEqual('\U0001044F\U0001044F'.swapcase(),
'\U00010427\U00010427')
self.assertEqual('\U00010427\U0001044F'.swapcase(),
'\U0001044F\U00010427')
self.assertEqual('\U0001044F\U00010427'.swapcase(),
'\U00010427\U0001044F')
self.assertEqual('X\U00010427x\U0001044F'.swapcase(),
'x\U0001044FX\U00010427')
self.assertEqual('ï¬'.swapcase(), 'FI')
self.assertEqual('\u0130'.swapcase(), '\u0069\u0307')
# Special case for GREEK CAPITAL LETTER SIGMA U+03A3
self.assertEqual('\u03a3'.swapcase(), '\u03c3')
self.assertEqual('\u0345\u03a3'.swapcase(), '\u0399\u03c3')
self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
self.assertEqual('A\u0345\u03a3a'.swapcase(), 'a\u0399\u03c3A')
self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
self.assertEqual('A\u03a3\u0345'.swapcase(), 'a\u03c2\u0399')
self.assertEqual('\u03a3\u0345 '.swapcase(), '\u03c3\u0399 ')
self.assertEqual('\u03a3'.swapcase(), '\u03c3')
self.assertEqual('Ã'.swapcase(), 'SS')
self.assertEqual('\u1fd2'.swapcase(), '\u0399\u0308\u0300')
def test_center(self):
string_tests.CommonTest.test_center(self)
self.assertEqual('x'.center(2, '\U0010FFFF'),
'x\U0010FFFF')
self.assertEqual('x'.center(3, '\U0010FFFF'),
'\U0010FFFFx\U0010FFFF')
self.assertEqual('x'.center(4, '\U0010FFFF'),
'\U0010FFFFx\U0010FFFF\U0010FFFF')
@unittest.skipUnless(sys.maxsize == 2**31 - 1, "requires 32-bit system")
@support.cpython_only
def test_case_operation_overflow(self):
# Issue #22643
size = 2**32//12 + 1
try:
s = "ü" * size
except MemoryError:
self.skipTest('no enough memory (%.0f MiB required)' % (size / 2**20))
try:
self.assertRaises(OverflowError, s.upper)
finally:
del s
def test_contains(self):
# Testing Unicode contains method
self.assertIn('a', 'abdb')
self.assertIn('a', 'bdab')
self.assertIn('a', 'bdaba')
self.assertIn('a', 'bdba')
self.assertNotIn('a', 'bdb')
self.assertIn('a', 'bdba')
self.assertIn('a', ('a',1,None))
self.assertIn('a', (1,None,'a'))
self.assertIn('a', ('a',1,None))
self.assertIn('a', (1,None,'a'))
self.assertNotIn('a', ('x',1,'y'))
self.assertNotIn('a', ('x',1,None))
self.assertNotIn('abcd', 'abcxxxx')
self.assertIn('ab', 'abcd')
self.assertIn('ab', 'abc')
self.assertIn('ab', (1,None,'ab'))
self.assertIn('', 'abc')
self.assertIn('', '')
self.assertIn('', 'abc')
self.assertNotIn('\0', 'abc')
self.assertIn('\0', '\0abc')
self.assertIn('\0', 'abc\0')
self.assertIn('a', '\0abc')
self.assertIn('asdf', 'asdf')
self.assertNotIn('asdf', 'asd')
self.assertNotIn('asdf', '')
self.assertRaises(TypeError, "abc".__contains__)
# test mixed kinds
for fill in ('a', '\u0100', '\U00010300'):
fill *= 9
for delim in ('c', '\u0102', '\U00010302'):
self.assertNotIn(delim, fill)
self.assertIn(delim, fill + delim)
self.assertNotIn(delim * 2, fill)
self.assertIn(delim * 2, fill + delim * 2)
def test_issue18183(self):
'\U00010000\U00100000'.lower()
'\U00010000\U00100000'.casefold()
'\U00010000\U00100000'.upper()
'\U00010000\U00100000'.capitalize()
'\U00010000\U00100000'.title()
'\U00010000\U00100000'.swapcase()
'\U00100000'.center(3, '\U00010000')
'\U00100000'.ljust(3, '\U00010000')
'\U00100000'.rjust(3, '\U00010000')
def test_format(self):
self.assertEqual(''.format(), '')
self.assertEqual('a'.format(), 'a')
self.assertEqual('ab'.format(), 'ab')
self.assertEqual('a{{'.format(), 'a{')
self.assertEqual('a}}'.format(), 'a}')
self.assertEqual('{{b'.format(), '{b')
self.assertEqual('}}b'.format(), '}b')
self.assertEqual('a{{b'.format(), 'a{b')
# examples from the PEP:
import datetime
self.assertEqual("My name is {0}".format('Fred'), "My name is Fred")
self.assertEqual("My name is {0[name]}".format(dict(name='Fred')),
"My name is Fred")
self.assertEqual("My name is {0} :-{{}}".format('Fred'),
"My name is Fred :-{}")
d = datetime.date(2007, 8, 18)
self.assertEqual("The year is {0.year}".format(d),
"The year is 2007")
# classes we'll use for testing
class C:
def __init__(self, x=100):
self._x = x
def __format__(self, spec):
return spec
class D:
def __init__(self, x):
self.x = x
def __format__(self, spec):
return str(self.x)
# class with __str__, but no __format__
class E:
def __init__(self, x):
self.x = x
def __str__(self):
return 'E(' + self.x + ')'
# class with __repr__, but no __format__ or __str__
class F:
def __init__(self, x):
self.x = x
def __repr__(self):
return 'F(' + self.x + ')'
# class with __format__ that forwards to string, for some format_spec's
class G:
def __init__(self, x):
self.x = x
def __str__(self):
return "string is " + self.x
def __format__(self, format_spec):
if format_spec == 'd':
return 'G(' + self.x + ')'
return object.__format__(self, format_spec)
class I(datetime.date):
def __format__(self, format_spec):
return self.strftime(format_spec)
class J(int):
def __format__(self, format_spec):
return int.__format__(self * 2, format_spec)
class M:
def __init__(self, x):
self.x = x
def __repr__(self):
return 'M(' + self.x + ')'
__str__ = None
class N:
def __init__(self, x):
self.x = x
def __repr__(self):
return 'N(' + self.x + ')'
__format__ = None
self.assertEqual(''.format(), '')
self.assertEqual('abc'.format(), 'abc')
self.assertEqual('{0}'.format('abc'), 'abc')
self.assertEqual('{0:}'.format('abc'), 'abc')
# self.assertEqual('{ 0 }'.format('abc'), 'abc')
self.assertEqual('X{0}'.format('abc'), 'Xabc')
self.assertEqual('{0}X'.format('abc'), 'abcX')
self.assertEqual('X{0}Y'.format('abc'), 'XabcY')
self.assertEqual('{1}'.format(1, 'abc'), 'abc')
self.assertEqual('X{1}'.format(1, 'abc'), 'Xabc')
self.assertEqual('{1}X'.format(1, 'abc'), 'abcX')
self.assertEqual('X{1}Y'.format(1, 'abc'), 'XabcY')
self.assertEqual('{0}'.format(-15), '-15')
self.assertEqual('{0}{1}'.format(-15, 'abc'), '-15abc')
self.assertEqual('{0}X{1}'.format(-15, 'abc'), '-15Xabc')
self.assertEqual('{{'.format(), '{')
self.assertEqual('}}'.format(), '}')
self.assertEqual('{{}}'.format(), '{}')
self.assertEqual('{{x}}'.format(), '{x}')
self.assertEqual('{{{0}}}'.format(123), '{123}')
self.assertEqual('{{{{0}}}}'.format(), '{{0}}')
self.assertEqual('}}{{'.format(), '}{')
self.assertEqual('}}x{{'.format(), '}x{')
# weird field names
self.assertEqual("{0[foo-bar]}".format({'foo-bar':'baz'}), 'baz')
self.assertEqual("{0[foo bar]}".format({'foo bar':'baz'}), 'baz')
self.assertEqual("{0[ ]}".format({' ':3}), '3')
self.assertEqual('{foo._x}'.format(foo=C(20)), '20')
self.assertEqual('{1}{0}'.format(D(10), D(20)), '2010')
self.assertEqual('{0._x.x}'.format(C(D('abc'))), 'abc')
self.assertEqual('{0[0]}'.format(['abc', 'def']), 'abc')
self.assertEqual('{0[1]}'.format(['abc', 'def']), 'def')
self.assertEqual('{0[1][0]}'.format(['abc', ['def']]), 'def')
self.assertEqual('{0[1][0].x}'.format(['abc', [D('def')]]), 'def')
# strings
self.assertEqual('{0:.3s}'.format('abc'), 'abc')
self.assertEqual('{0:.3s}'.format('ab'), 'ab')
self.assertEqual('{0:.3s}'.format('abcdef'), 'abc')
self.assertEqual('{0:.0s}'.format('abcdef'), '')
self.assertEqual('{0:3.3s}'.format('abc'), 'abc')
self.assertEqual('{0:2.3s}'.format('abc'), 'abc')
self.assertEqual('{0:2.2s}'.format('abc'), 'ab')
self.assertEqual('{0:3.2s}'.format('abc'), 'ab ')
self.assertEqual('{0:x<0s}'.format('result'), 'result')
self.assertEqual('{0:x<5s}'.format('result'), 'result')
self.assertEqual('{0:x<6s}'.format('result'), 'result')
self.assertEqual('{0:x<7s}'.format('result'), 'resultx')
self.assertEqual('{0:x<8s}'.format('result'), 'resultxx')
self.assertEqual('{0: <7s}'.format('result'), 'result ')
self.assertEqual('{0:<7s}'.format('result'), 'result ')
self.assertEqual('{0:>7s}'.format('result'), ' result')
self.assertEqual('{0:>8s}'.format('result'), ' result')
self.assertEqual('{0:^8s}'.format('result'), ' result ')
self.assertEqual('{0:^9s}'.format('result'), ' result ')
self.assertEqual('{0:^10s}'.format('result'), ' result ')
self.assertEqual('{0:10000}'.format('a'), 'a' + ' ' * 9999)
self.assertEqual('{0:10000}'.format(''), ' ' * 10000)
self.assertEqual('{0:10000000}'.format(''), ' ' * 10000000)
# issue 12546: use \x00 as a fill character
self.assertEqual('{0:\x00<6s}'.format('foo'), 'foo\x00\x00\x00')
self.assertEqual('{0:\x01<6s}'.format('foo'), 'foo\x01\x01\x01')
self.assertEqual('{0:\x00^6s}'.format('foo'), '\x00foo\x00\x00')
self.assertEqual('{0:^6s}'.format('foo'), ' foo ')
self.assertEqual('{0:\x00<6}'.format(3), '3\x00\x00\x00\x00\x00')
self.assertEqual('{0:\x01<6}'.format(3), '3\x01\x01\x01\x01\x01')
self.assertEqual('{0:\x00^6}'.format(3), '\x00\x003\x00\x00\x00')
self.assertEqual('{0:<6}'.format(3), '3 ')
self.assertEqual('{0:\x00<6}'.format(3.14), '3.14\x00\x00')
self.assertEqual('{0:\x01<6}'.format(3.14), '3.14\x01\x01')
self.assertEqual('{0:\x00^6}'.format(3.14), '\x003.14\x00')
self.assertEqual('{0:^6}'.format(3.14), ' 3.14 ')
self.assertEqual('{0:\x00<12}'.format(3+2.0j), '(3+2j)\x00\x00\x00\x00\x00\x00')
self.assertEqual('{0:\x01<12}'.format(3+2.0j), '(3+2j)\x01\x01\x01\x01\x01\x01')
self.assertEqual('{0:\x00^12}'.format(3+2.0j), '\x00\x00\x00(3+2j)\x00\x00\x00')
self.assertEqual('{0:^12}'.format(3+2.0j), ' (3+2j) ')
# format specifiers for user defined type
self.assertEqual('{0:abc}'.format(C()), 'abc')
# !r, !s and !a coercions
self.assertEqual('{0!s}'.format('Hello'), 'Hello')
self.assertEqual('{0!s:}'.format('Hello'), 'Hello')
self.assertEqual('{0!s:15}'.format('Hello'), 'Hello ')
self.assertEqual('{0!s:15s}'.format('Hello'), 'Hello ')
self.assertEqual('{0!r}'.format('Hello'), "'Hello'")
self.assertEqual('{0!r:}'.format('Hello'), "'Hello'")
self.assertEqual('{0!r}'.format(F('Hello')), 'F(Hello)')
self.assertEqual('{0!r}'.format('\u0378'), "'\\u0378'") # nonprintable
self.assertEqual('{0!r}'.format('\u0374'), "'\u0374'") # printable
self.assertEqual('{0!r}'.format(F('\u0374')), 'F(\u0374)')
self.assertEqual('{0!a}'.format('Hello'), "'Hello'")
self.assertEqual('{0!a}'.format('\u0378'), "'\\u0378'") # nonprintable
self.assertEqual('{0!a}'.format('\u0374'), "'\\u0374'") # printable
self.assertEqual('{0!a:}'.format('Hello'), "'Hello'")
self.assertEqual('{0!a}'.format(F('Hello')), 'F(Hello)')
self.assertEqual('{0!a}'.format(F('\u0374')), 'F(\\u0374)')
# test fallback to object.__format__
self.assertEqual('{0}'.format({}), '{}')
self.assertEqual('{0}'.format([]), '[]')
self.assertEqual('{0}'.format([1]), '[1]')
self.assertEqual('{0:d}'.format(G('data')), 'G(data)')
self.assertEqual('{0!s}'.format(G('data')), 'string is data')
self.assertRaises(TypeError, '{0:^10}'.format, E('data'))
self.assertRaises(TypeError, '{0:^10s}'.format, E('data'))
self.assertRaises(TypeError, '{0:>15s}'.format, G('data'))
self.assertEqual("{0:date: %Y-%m-%d}".format(I(year=2007,
month=8,
day=27)),
"date: 2007-08-27")
# test deriving from a builtin type and overriding __format__
self.assertEqual("{0}".format(J(10)), "20")
# string format specifiers
self.assertEqual('{0:}'.format('a'), 'a')
# computed format specifiers
self.assertEqual("{0:.{1}}".format('hello world', 5), 'hello')
self.assertEqual("{0:.{1}s}".format('hello world', 5), 'hello')
self.assertEqual("{0:.{precision}s}".format('hello world', precision=5), 'hello')
self.assertEqual("{0:{width}.{precision}s}".format('hello world', width=10, precision=5), 'hello ')
self.assertEqual("{0:{width}.{precision}s}".format('hello world', width='10', precision='5'), 'hello ')
# test various errors
self.assertRaises(ValueError, '{'.format)
self.assertRaises(ValueError, '}'.format)
self.assertRaises(ValueError, 'a{'.format)
self.assertRaises(ValueError, 'a}'.format)
self.assertRaises(ValueError, '{a'.format)
self.assertRaises(ValueError, '}a'.format)
self.assertRaises(IndexError, '{0}'.format)
self.assertRaises(IndexError, '{1}'.format, 'abc')
self.assertRaises(KeyError, '{x}'.format)
self.assertRaises(ValueError, "}{".format)
self.assertRaises(ValueError, "abc{0:{}".format)
self.assertRaises(ValueError, "{0".format)
self.assertRaises(IndexError, "{0.}".format)
self.assertRaises(ValueError, "{0.}".format, 0)
self.assertRaises(ValueError, "{0[}".format)
self.assertRaises(ValueError, "{0[}".format, [])
self.assertRaises(KeyError, "{0]}".format)
self.assertRaises(ValueError, "{0.[]}".format, 0)
self.assertRaises(ValueError, "{0..foo}".format, 0)
self.assertRaises(ValueError, "{0[0}".format, 0)
self.assertRaises(ValueError, "{0[0:foo}".format, 0)
self.assertRaises(KeyError, "{c]}".format)
self.assertRaises(ValueError, "{{ {{{0}}".format, 0)
self.assertRaises(ValueError, "{0}}".format, 0)
self.assertRaises(KeyError, "{foo}".format, bar=3)
self.assertRaises(ValueError, "{0!x}".format, 3)
self.assertRaises(ValueError, "{0!}".format, 0)
self.assertRaises(ValueError, "{0!rs}".format, 0)
self.assertRaises(ValueError, "{!}".format)
self.assertRaises(IndexError, "{:}".format)
self.assertRaises(IndexError, "{:s}".format)
self.assertRaises(IndexError, "{}".format)
big = "23098475029384702983476098230754973209482573"
self.assertRaises(ValueError, ("{" + big + "}").format)
self.assertRaises(ValueError, ("{[" + big + "]}").format, [0])
# issue 6089
self.assertRaises(ValueError, "{0[0]x}".format, [None])
self.assertRaises(ValueError, "{0[0](10)}".format, [None])
# can't have a replacement on the field name portion
self.assertRaises(TypeError, '{0[{1}]}'.format, 'abcdefg', 4)
# exceed maximum recursion depth
self.assertRaises(ValueError, "{0:{1:{2}}}".format, 'abc', 's', '')
self.assertRaises(ValueError, "{0:{1:{2:{3:{4:{5:{6}}}}}}}".format,
0, 1, 2, 3, 4, 5, 6, 7)
# string format spec errors
self.assertRaises(ValueError, "{0:-s}".format, '')
self.assertRaises(ValueError, format, "", "-")
self.assertRaises(ValueError, "{0:=s}".format, '')
# Alternate formatting is not supported
self.assertRaises(ValueError, format, '', '#')
self.assertRaises(ValueError, format, '', '#20')
# Non-ASCII
self.assertEqual("{0:s}{1:s}".format("ABC", "\u0410\u0411\u0412"),
'ABC\u0410\u0411\u0412')
self.assertEqual("{0:.3s}".format("ABC\u0410\u0411\u0412"),
'ABC')
self.assertEqual("{0:.0s}".format("ABC\u0410\u0411\u0412"),
'')
self.assertEqual("{[{}]}".format({"{}": 5}), "5")
self.assertEqual("{[{}]}".format({"{}" : "a"}), "a")
self.assertEqual("{[{]}".format({"{" : "a"}), "a")
self.assertEqual("{[}]}".format({"}" : "a"}), "a")
self.assertEqual("{[[]}".format({"[" : "a"}), "a")
self.assertEqual("{[!]}".format({"!" : "a"}), "a")
self.assertRaises(ValueError, "{a{}b}".format, 42)
self.assertRaises(ValueError, "{a{b}".format, 42)
self.assertRaises(ValueError, "{[}".format, 42)
self.assertEqual("0x{:0{:d}X}".format(0x0,16), "0x0000000000000000")
# Blocking fallback
m = M('data')
self.assertEqual("{!r}".format(m), 'M(data)')
self.assertRaises(TypeError, "{!s}".format, m)
self.assertRaises(TypeError, "{}".format, m)
n = N('data')
self.assertEqual("{!r}".format(n), 'N(data)')
self.assertEqual("{!s}".format(n), 'N(data)')
self.assertRaises(TypeError, "{}".format, n)
def test_format_map(self):
self.assertEqual(''.format_map({}), '')
self.assertEqual('a'.format_map({}), 'a')
self.assertEqual('ab'.format_map({}), 'ab')
self.assertEqual('a{{'.format_map({}), 'a{')
self.assertEqual('a}}'.format_map({}), 'a}')
self.assertEqual('{{b'.format_map({}), '{b')
self.assertEqual('}}b'.format_map({}), '}b')
self.assertEqual('a{{b'.format_map({}), 'a{b')
# using mappings
class Mapping(dict):
def __missing__(self, key):
return key
self.assertEqual('{hello}'.format_map(Mapping()), 'hello')
self.assertEqual('{a} {world}'.format_map(Mapping(a='hello')), 'hello world')
class InternalMapping:
def __init__(self):
self.mapping = {'a': 'hello'}
def __getitem__(self, key):
return self.mapping[key]
self.assertEqual('{a}'.format_map(InternalMapping()), 'hello')
class C:
def __init__(self, x=100):
self._x = x
def __format__(self, spec):
return spec
self.assertEqual('{foo._x}'.format_map({'foo': C(20)}), '20')
# test various errors
self.assertRaises(TypeError, ''.format_map)
self.assertRaises(TypeError, 'a'.format_map)
self.assertRaises(ValueError, '{'.format_map, {})
self.assertRaises(ValueError, '}'.format_map, {})
self.assertRaises(ValueError, 'a{'.format_map, {})
self.assertRaises(ValueError, 'a}'.format_map, {})
self.assertRaises(ValueError, '{a'.format_map, {})
self.assertRaises(ValueError, '}a'.format_map, {})
# issue #12579: can't supply positional params to format_map
self.assertRaises(ValueError, '{}'.format_map, {'a' : 2})
self.assertRaises(ValueError, '{}'.format_map, 'a')
self.assertRaises(ValueError, '{a} {}'.format_map, {"a" : 2, "b" : 1})
class BadMapping:
def __getitem__(self, key):
return 1/0
self.assertRaises(KeyError, '{a}'.format_map, {})
self.assertRaises(TypeError, '{a}'.format_map, [])
self.assertRaises(ZeroDivisionError, '{a}'.format_map, BadMapping())
def test_format_huge_precision(self):
format_string = ".{}f".format(sys.maxsize + 1)
with self.assertRaises(ValueError):
result = format(2.34, format_string)
def test_format_huge_width(self):
format_string = "{}f".format(sys.maxsize + 1)
with self.assertRaises(ValueError):
result = format(2.34, format_string)
def test_format_huge_item_number(self):
format_string = "{{{}:.6f}}".format(sys.maxsize + 1)
with self.assertRaises(ValueError):
result = format_string.format(2.34)
def test_format_auto_numbering(self):
class C:
def __init__(self, x=100):
self._x = x
def __format__(self, spec):
return spec
self.assertEqual('{}'.format(10), '10')
self.assertEqual('{:5}'.format('s'), 's ')
self.assertEqual('{!r}'.format('s'), "'s'")
self.assertEqual('{._x}'.format(C(10)), '10')
self.assertEqual('{[1]}'.format([1, 2]), '2')
self.assertEqual('{[a]}'.format({'a':4, 'b':2}), '4')
self.assertEqual('a{}b{}c'.format(0, 1), 'a0b1c')
self.assertEqual('a{:{}}b'.format('x', '^10'), 'a x b')
self.assertEqual('a{:{}x}b'.format(20, '#'), 'a0x14b')
# can't mix and match numbering and auto-numbering
self.assertRaises(ValueError, '{}{1}'.format, 1, 2)
self.assertRaises(ValueError, '{1}{}'.format, 1, 2)
self.assertRaises(ValueError, '{:{1}}'.format, 1, 2)
self.assertRaises(ValueError, '{0:{}}'.format, 1, 2)
# can mix and match auto-numbering and named
self.assertEqual('{f}{}'.format(4, f='test'), 'test4')
self.assertEqual('{}{f}'.format(4, f='test'), '4test')
self.assertEqual('{:{f}}{g}{}'.format(1, 3, g='g', f=2), ' 1g3')
self.assertEqual('{f:{}}{}{g}'.format(2, 4, f=1, g='g'), ' 14g')
def test_formatting(self):
string_tests.MixinStrUnicodeUserStringTest.test_formatting(self)
# Testing Unicode formatting strings...
self.assertEqual("%s, %s" % ("abc", "abc"), 'abc, abc')
self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, 2, 3), 'abc, abc, 1, 2.000000, 3.00')
self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, -2, 3), 'abc, abc, 1, -2.000000, 3.00')
self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.5), 'abc, abc, -1, -2.000000, 3.50')
self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.57), 'abc, abc, -1, -2.000000, 3.57')
self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 1003.57), 'abc, abc, -1, -2.000000, 1003.57')
if not sys.platform.startswith('java'):
self.assertEqual("%r, %r" % (b"abc", "abc"), "b'abc', 'abc'")
self.assertEqual("%r" % ("\u1234",), "'\u1234'")
self.assertEqual("%a" % ("\u1234",), "'\\u1234'")
self.assertEqual("%(x)s, %(y)s" % {'x':"abc", 'y':"def"}, 'abc, def')
self.assertEqual("%(x)s, %(\xfc)s" % {'x':"abc", '\xfc':"def"}, 'abc, def')
self.assertEqual('%c' % 0x1234, '\u1234')
self.assertEqual('%c' % 0x21483, '\U00021483')
self.assertRaises(OverflowError, "%c".__mod__, (0x110000,))
self.assertEqual('%c' % '\U00021483', '\U00021483')
self.assertRaises(TypeError, "%c".__mod__, "aa")
self.assertRaises(ValueError, "%.1\u1032f".__mod__, (1.0/3))
self.assertRaises(TypeError, "%i".__mod__, "aa")
# formatting jobs delegated from the string implementation:
self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
self.assertEqual('...%s...%s...%s...%s...' % (1,2,3,"abc"), '...1...2...3...abc...')
self.assertEqual('...%%...%%s...%s...%s...%s...%s...' % (1,2,3,"abc"), '...%...%s...1...2...3...abc...')
self.assertEqual('...%s...' % "abc", '...abc...')
self.assertEqual('%*s' % (5,'abc',), ' abc')
self.assertEqual('%*s' % (-5,'abc',), 'abc ')
self.assertEqual('%*.*s' % (5,2,'abc',), ' ab')
self.assertEqual('%*.*s' % (5,3,'abc',), ' abc')
self.assertEqual('%i %*.*s' % (10, 5,3,'abc',), '10 abc')
self.assertEqual('%i%s %*.*s' % (10, 3, 5, 3, 'abc',), '103 abc')
self.assertEqual('%c' % 'a', 'a')
class Wrapper:
def __str__(self):
return '\u1234'
self.assertEqual('%s' % Wrapper(), '\u1234')
# issue 3382
NAN = float('nan')
INF = float('inf')
self.assertEqual('%f' % NAN, 'nan')
self.assertEqual('%F' % NAN, 'NAN')
self.assertEqual('%f' % INF, 'inf')
self.assertEqual('%F' % INF, 'INF')
# PEP 393
self.assertEqual('%.1s' % "a\xe9\u20ac", 'a')
self.assertEqual('%.2s' % "a\xe9\u20ac", 'a\xe9')
#issue 19995
class PseudoInt:
def __init__(self, value):
self.value = int(value)
def __int__(self):
return self.value
def __index__(self):
return self.value
class PseudoFloat:
def __init__(self, value):
self.value = float(value)
def __int__(self):
return int(self.value)
pi = PseudoFloat(3.1415)
letter_m = PseudoInt(109)
self.assertEqual('%x' % 42, '2a')
self.assertEqual('%X' % 15, 'F')
self.assertEqual('%o' % 9, '11')
self.assertEqual('%c' % 109, 'm')
self.assertEqual('%x' % letter_m, '6d')
self.assertEqual('%X' % letter_m, '6D')
self.assertEqual('%o' % letter_m, '155')
self.assertEqual('%c' % letter_m, 'm')
self.assertRaisesRegex(TypeError, '%x format: an integer is required, not float', operator.mod, '%x', 3.14),
self.assertRaisesRegex(TypeError, '%X format: an integer is required, not float', operator.mod, '%X', 2.11),
self.assertRaisesRegex(TypeError, '%o format: an integer is required, not float', operator.mod, '%o', 1.79),
self.assertRaisesRegex(TypeError, '%x format: an integer is required, not PseudoFloat', operator.mod, '%x', pi),
self.assertRaises(TypeError, operator.mod, '%c', pi),
def test_formatting_with_enum(self):
# issue18780
import enum
class Float(float, enum.Enum):
PI = 3.1415926
class Int(enum.IntEnum):
IDES = 15
class Str(str, enum.Enum):
ABC = 'abc'
# Testing Unicode formatting strings...
self.assertEqual("%s, %s" % (Str.ABC, Str.ABC),
'Str.ABC, Str.ABC')
self.assertEqual("%s, %s, %d, %i, %u, %f, %5.2f" %
(Str.ABC, Str.ABC,
Int.IDES, Int.IDES, Int.IDES,
Float.PI, Float.PI),
'Str.ABC, Str.ABC, 15, 15, 15, 3.141593, 3.14')
# formatting jobs delegated from the string implementation:
self.assertEqual('...%(foo)s...' % {'foo':Str.ABC},
'...Str.ABC...')
self.assertEqual('...%(foo)s...' % {'foo':Int.IDES},
'...Int.IDES...')
self.assertEqual('...%(foo)i...' % {'foo':Int.IDES},
'...15...')
self.assertEqual('...%(foo)d...' % {'foo':Int.IDES},
'...15...')
self.assertEqual('...%(foo)u...' % {'foo':Int.IDES, 'def':Float.PI},
'...15...')
self.assertEqual('...%(foo)f...' % {'foo':Float.PI,'def':123},
'...3.141593...')
def test_formatting_huge_precision(self):
format_string = "%.{}f".format(sys.maxsize + 1)
with self.assertRaises(ValueError):
result = format_string % 2.34
def test_issue28598_strsubclass_rhs(self):
# A subclass of str with an __rmod__ method should be able to hook
# into the % operator
class SubclassedStr(str):
def __rmod__(self, other):
return 'Success, self.__rmod__({!r}) was called'.format(other)
self.assertEqual('lhs %% %r' % SubclassedStr('rhs'),
"Success, self.__rmod__('lhs %% %r') was called")
@support.cpython_only
def test_formatting_huge_precision_c_limits(self):
from _testcapi import INT_MAX
format_string = "%.{}f".format(INT_MAX + 1)
with self.assertRaises(ValueError):
result = format_string % 2.34
def test_formatting_huge_width(self):
format_string = "%{}f".format(sys.maxsize + 1)
with self.assertRaises(ValueError):
result = format_string % 2.34
def test_startswith_endswith_errors(self):
for meth in ('foo'.startswith, 'foo'.endswith):
with self.assertRaises(TypeError) as cm:
meth(['f'])
exc = str(cm.exception)
self.assertIn('str', exc)
self.assertIn('tuple', exc)
@support.run_with_locale('LC_ALL', 'de_DE', 'fr_FR')
def test_format_float(self):
# should not format with a comma, but always with C locale
self.assertEqual('1.0', '%.1f' % 1.0)
def test_constructor(self):
# unicode(obj) tests (this maps to PyObject_Unicode() at C level)
self.assertEqual(
str('unicode remains unicode'),
'unicode remains unicode'
)
for text in ('ascii', '\xe9', '\u20ac', '\U0010FFFF'):
subclass = StrSubclass(text)
self.assertEqual(str(subclass), text)
self.assertEqual(len(subclass), len(text))
if text == 'ascii':
self.assertEqual(subclass.encode('ascii'), b'ascii')
self.assertEqual(subclass.encode('utf-8'), b'ascii')
self.assertEqual(
str('strings are converted to unicode'),
'strings are converted to unicode'
)
class StringCompat:
def __init__(self, x):
self.x = x
def __str__(self):
return self.x
self.assertEqual(
str(StringCompat('__str__ compatible objects are recognized')),
'__str__ compatible objects are recognized'
)
# unicode(obj) is compatible to str():
o = StringCompat('unicode(obj) is compatible to str()')
self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
for obj in (123, 123.45, 123):
self.assertEqual(str(obj), str(str(obj)))
# unicode(obj, encoding, error) tests (this maps to
# PyUnicode_FromEncodedObject() at C level)
if not sys.platform.startswith('java'):
self.assertRaises(
TypeError,
str,
'decoding unicode is not supported',
'utf-8',
'strict'
)
self.assertEqual(
str(b'strings are decoded to unicode', 'utf-8', 'strict'),
'strings are decoded to unicode'
)
if not sys.platform.startswith('java'):
self.assertEqual(
str(
memoryview(b'character buffers are decoded to unicode'),
'utf-8',
'strict'
),
'character buffers are decoded to unicode'
)
self.assertRaises(TypeError, str, 42, 42, 42)
def test_constructor_keyword_args(self):
"""Pass various keyword argument combinations to the constructor."""
# The object argument can be passed as a keyword.
self.assertEqual(str(object='foo'), 'foo')
self.assertEqual(str(object=b'foo', encoding='utf-8'), 'foo')
# The errors argument without encoding triggers "decode" mode.
self.assertEqual(str(b'foo', errors='strict'), 'foo') # not "b'foo'"
self.assertEqual(str(object=b'foo', errors='strict'), 'foo')
def test_constructor_defaults(self):
"""Check the constructor argument defaults."""
# The object argument defaults to '' or b''.
self.assertEqual(str(), '')
self.assertEqual(str(errors='strict'), '')
utf8_cent = '¢'.encode('utf-8')
# The encoding argument defaults to utf-8.
self.assertEqual(str(utf8_cent, errors='strict'), '¢')
# The errors argument defaults to strict.
self.assertRaises(UnicodeDecodeError, str, utf8_cent, encoding='ascii')
def test_codecs_utf7(self):
utfTests = [
('A\u2262\u0391.', b'A+ImIDkQ.'), # RFC2152 example
('Hi Mom -\u263a-!', b'Hi Mom -+Jjo--!'), # RFC2152 example
('\u65E5\u672C\u8A9E', b'+ZeVnLIqe-'), # RFC2152 example
('Item 3 is \u00a31.', b'Item 3 is +AKM-1.'), # RFC2152 example
('+', b'+-'),
('+-', b'+--'),
('+?', b'+-?'),
(r'\?', b'+AFw?'),
('+?', b'+-?'),
(r'\\?', b'+AFwAXA?'),
(r'\\\?', b'+AFwAXABc?'),
(r'++--', b'+-+---'),
('\U000abcde', b'+2m/c3g-'), # surrogate pairs
('/', b'/'),
]
for (x, y) in utfTests:
self.assertEqual(x.encode('utf-7'), y)
# Unpaired surrogates are passed through
self.assertEqual('\uD801'.encode('utf-7'), b'+2AE-')
self.assertEqual('\uD801x'.encode('utf-7'), b'+2AE-x')
self.assertEqual('\uDC01'.encode('utf-7'), b'+3AE-')
self.assertEqual('\uDC01x'.encode('utf-7'), b'+3AE-x')
self.assertEqual(b'+2AE-'.decode('utf-7'), '\uD801')
self.assertEqual(b'+2AE-x'.decode('utf-7'), '\uD801x')
self.assertEqual(b'+3AE-'.decode('utf-7'), '\uDC01')
self.assertEqual(b'+3AE-x'.decode('utf-7'), '\uDC01x')
self.assertEqual('\uD801\U000abcde'.encode('utf-7'), b'+2AHab9ze-')
self.assertEqual(b'+2AHab9ze-'.decode('utf-7'), '\uD801\U000abcde')
# Issue #2242: crash on some Windows/MSVC versions
self.assertEqual(b'+\xc1'.decode('utf-7', 'ignore'), '')
# Direct encoded characters
set_d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'(),-./:?"
# Optional direct characters
set_o = '!"#$%&*;<=>@[]^_`{|}'
for c in set_d:
self.assertEqual(c.encode('utf7'), c.encode('ascii'))
self.assertEqual(c.encode('ascii').decode('utf7'), c)
for c in set_o:
self.assertEqual(c.encode('ascii').decode('utf7'), c)
def test_codecs_utf8(self):
self.assertEqual(''.encode('utf-8'), b'')
self.assertEqual('\u20ac'.encode('utf-8'), b'\xe2\x82\xac')
self.assertEqual('\U00010002'.encode('utf-8'), b'\xf0\x90\x80\x82')
self.assertEqual('\U00023456'.encode('utf-8'), b'\xf0\xa3\x91\x96')
self.assertEqual('\ud800'.encode('utf-8', 'surrogatepass'), b'\xed\xa0\x80')
self.assertEqual('\udc00'.encode('utf-8', 'surrogatepass'), b'\xed\xb0\x80')
self.assertEqual(('\U00010002'*10).encode('utf-8'),
b'\xf0\x90\x80\x82'*10)
self.assertEqual(
'\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f'
'\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00'
'\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c'
'\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067'
'\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das'
' Nunstuck git und'.encode('utf-8'),
b'\xe6\xad\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8\x80\xe3\x81'
b'\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3\xe3\x81\xaf\xe3'
b'\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe'
b'\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
b'\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8'
b'\xaa\x9e\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81'
b'\xe3\x81\x82\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81'
b'\x9f\xe3\x82\x89\xe3\x82\x81\xe3\x81\xa7\xe3\x81\x99\xe3'
b'\x80\x82\xe5\xae\x9f\xe9\x9a\x9b\xe3\x81\xab\xe3\x81\xaf'
b'\xe3\x80\x8cWenn ist das Nunstuck git und'
)
# UTF-8 specific decoding tests
self.assertEqual(str(b'\xf0\xa3\x91\x96', 'utf-8'), '\U00023456' )
self.assertEqual(str(b'\xf0\x90\x80\x82', 'utf-8'), '\U00010002' )
self.assertEqual(str(b'\xe2\x82\xac', 'utf-8'), '\u20ac' )
# Other possible utf-8 test cases:
# * strict decoding testing for all of the
# UTF8_ERROR cases in PyUnicode_DecodeUTF8
def test_utf8_decode_valid_sequences(self):
sequences = [
# single byte
(b'\x00', '\x00'), (b'a', 'a'), (b'\x7f', '\x7f'),
# 2 bytes
(b'\xc2\x80', '\x80'), (b'\xdf\xbf', '\u07ff'),
# 3 bytes
(b'\xe0\xa0\x80', '\u0800'), (b'\xed\x9f\xbf', '\ud7ff'),
(b'\xee\x80\x80', '\uE000'), (b'\xef\xbf\xbf', '\uffff'),
# 4 bytes
(b'\xF0\x90\x80\x80', '\U00010000'),
(b'\xf4\x8f\xbf\xbf', '\U0010FFFF')
]
for seq, res in sequences:
self.assertEqual(seq.decode('utf-8'), res)
def test_utf8_decode_invalid_sequences(self):
# continuation bytes in a sequence of 2, 3, or 4 bytes
continuation_bytes = [bytes([x]) for x in range(0x80, 0xC0)]
# start bytes of a 2-byte sequence equivalent to code points < 0x7F
invalid_2B_seq_start_bytes = [bytes([x]) for x in range(0xC0, 0xC2)]
# start bytes of a 4-byte sequence equivalent to code points > 0x10FFFF
invalid_4B_seq_start_bytes = [bytes([x]) for x in range(0xF5, 0xF8)]
invalid_start_bytes = (
continuation_bytes + invalid_2B_seq_start_bytes +
invalid_4B_seq_start_bytes + [bytes([x]) for x in range(0xF7, 0x100)]
)
for byte in invalid_start_bytes:
self.assertRaises(UnicodeDecodeError, byte.decode, 'utf-8')
for sb in invalid_2B_seq_start_bytes:
for cb in continuation_bytes:
self.assertRaises(UnicodeDecodeError, (sb+cb).decode, 'utf-8')
for sb in invalid_4B_seq_start_bytes:
for cb1 in continuation_bytes[:3]:
for cb3 in continuation_bytes[:3]:
self.assertRaises(UnicodeDecodeError,
(sb+cb1+b'\x80'+cb3).decode, 'utf-8')
for cb in [bytes([x]) for x in range(0x80, 0xA0)]:
self.assertRaises(UnicodeDecodeError,
(b'\xE0'+cb+b'\x80').decode, 'utf-8')
self.assertRaises(UnicodeDecodeError,
(b'\xE0'+cb+b'\xBF').decode, 'utf-8')
# surrogates
for cb in [bytes([x]) for x in range(0xA0, 0xC0)]:
self.assertRaises(UnicodeDecodeError,
(b'\xED'+cb+b'\x80').decode, 'utf-8')
self.assertRaises(UnicodeDecodeError,
(b'\xED'+cb+b'\xBF').decode, 'utf-8')
for cb in [bytes([x]) for x in range(0x80, 0x90)]:
self.assertRaises(UnicodeDecodeError,
(b'\xF0'+cb+b'\x80\x80').decode, 'utf-8')
self.assertRaises(UnicodeDecodeError,
(b'\xF0'+cb+b'\xBF\xBF').decode, 'utf-8')
for cb in [bytes([x]) for x in range(0x90, 0xC0)]:
self.assertRaises(UnicodeDecodeError,
(b'\xF4'+cb+b'\x80\x80').decode, 'utf-8')
self.assertRaises(UnicodeDecodeError,
(b'\xF4'+cb+b'\xBF\xBF').decode, 'utf-8')
def test_issue8271(self):
# Issue #8271: during the decoding of an invalid UTF-8 byte sequence,
# only the start byte and the continuation byte(s) are now considered
# invalid, instead of the number of bytes specified by the start byte.
# See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf (page 95,
# table 3-8, Row 2) for more information about the algorithm used.
FFFD = '\ufffd'
sequences = [
# invalid start bytes
(b'\x80', FFFD), # continuation byte
(b'\x80\x80', FFFD*2), # 2 continuation bytes
(b'\xc0', FFFD),
(b'\xc0\xc0', FFFD*2),
(b'\xc1', FFFD),
(b'\xc1\xc0', FFFD*2),
(b'\xc0\xc1', FFFD*2),
# with start byte of a 2-byte sequence
(b'\xc2', FFFD), # only the start byte
(b'\xc2\xc2', FFFD*2), # 2 start bytes
(b'\xc2\xc2\xc2', FFFD*3), # 3 start bytes
(b'\xc2\x41', FFFD+'A'), # invalid continuation byte
# with start byte of a 3-byte sequence
(b'\xe1', FFFD), # only the start byte
(b'\xe1\xe1', FFFD*2), # 2 start bytes
(b'\xe1\xe1\xe1', FFFD*3), # 3 start bytes
(b'\xe1\xe1\xe1\xe1', FFFD*4), # 4 start bytes
(b'\xe1\x80', FFFD), # only 1 continuation byte
(b'\xe1\x41', FFFD+'A'), # invalid continuation byte
(b'\xe1\x41\x80', FFFD+'A'+FFFD), # invalid cb followed by valid cb
(b'\xe1\x41\x41', FFFD+'AA'), # 2 invalid continuation bytes
(b'\xe1\x80\x41', FFFD+'A'), # only 1 valid continuation byte
(b'\xe1\x80\xe1\x41', FFFD*2+'A'), # 1 valid and the other invalid
(b'\xe1\x41\xe1\x80', FFFD+'A'+FFFD), # 1 invalid and the other valid
# with start byte of a 4-byte sequence
(b'\xf1', FFFD), # only the start byte
(b'\xf1\xf1', FFFD*2), # 2 start bytes
(b'\xf1\xf1\xf1', FFFD*3), # 3 start bytes
(b'\xf1\xf1\xf1\xf1', FFFD*4), # 4 start bytes
(b'\xf1\xf1\xf1\xf1\xf1', FFFD*5), # 5 start bytes
(b'\xf1\x80', FFFD), # only 1 continuation bytes
(b'\xf1\x80\x80', FFFD), # only 2 continuation bytes
(b'\xf1\x80\x41', FFFD+'A'), # 1 valid cb and 1 invalid
(b'\xf1\x80\x41\x41', FFFD+'AA'), # 1 valid cb and 1 invalid
(b'\xf1\x80\x80\x41', FFFD+'A'), # 2 valid cb and 1 invalid
(b'\xf1\x41\x80', FFFD+'A'+FFFD), # 1 invalid cv and 1 valid
(b'\xf1\x41\x80\x80', FFFD+'A'+FFFD*2), # 1 invalid cb and 2 invalid
(b'\xf1\x41\x80\x41', FFFD+'A'+FFFD+'A'), # 2 invalid cb and 1 invalid
(b'\xf1\x41\x41\x80', FFFD+'AA'+FFFD), # 1 valid cb and 1 invalid
(b'\xf1\x41\xf1\x80', FFFD+'A'+FFFD),
(b'\xf1\x41\x80\xf1', FFFD+'A'+FFFD*2),
(b'\xf1\xf1\x80\x41', FFFD*2+'A'),
(b'\xf1\x41\xf1\xf1', FFFD+'A'+FFFD*2),
# with invalid start byte of a 4-byte sequence (rfc2279)
(b'\xf5', FFFD), # only the start byte
(b'\xf5\xf5', FFFD*2), # 2 start bytes
(b'\xf5\x80', FFFD*2), # only 1 continuation byte
(b'\xf5\x80\x80', FFFD*3), # only 2 continuation byte
(b'\xf5\x80\x80\x80', FFFD*4), # 3 continuation bytes
(b'\xf5\x80\x41', FFFD*2+'A'), # 1 valid cb and 1 invalid
(b'\xf5\x80\x41\xf5', FFFD*2+'A'+FFFD),
(b'\xf5\x41\x80\x80\x41', FFFD+'A'+FFFD*2+'A'),
# with invalid start byte of a 5-byte sequence (rfc2279)
(b'\xf8', FFFD), # only the start byte
(b'\xf8\xf8', FFFD*2), # 2 start bytes
(b'\xf8\x80', FFFD*2), # only one continuation byte
(b'\xf8\x80\x41', FFFD*2 + 'A'), # 1 valid cb and 1 invalid
(b'\xf8\x80\x80\x80\x80', FFFD*5), # invalid 5 bytes seq with 5 bytes
# with invalid start byte of a 6-byte sequence (rfc2279)
(b'\xfc', FFFD), # only the start byte
(b'\xfc\xfc', FFFD*2), # 2 start bytes
(b'\xfc\x80\x80', FFFD*3), # only 2 continuation bytes
(b'\xfc\x80\x80\x80\x80\x80', FFFD*6), # 6 continuation bytes
# invalid start byte
(b'\xfe', FFFD),
(b'\xfe\x80\x80', FFFD*3),
# other sequences
(b'\xf1\x80\x41\x42\x43', '\ufffd\x41\x42\x43'),
(b'\xf1\x80\xff\x42\x43', '\ufffd\ufffd\x42\x43'),
(b'\xf1\x80\xc2\x81\x43', '\ufffd\x81\x43'),
(b'\x61\xF1\x80\x80\xE1\x80\xC2\x62\x80\x63\x80\xBF\x64',
'\x61\uFFFD\uFFFD\uFFFD\x62\uFFFD\x63\uFFFD\uFFFD\x64'),
]
for n, (seq, res) in enumerate(sequences):
self.assertRaises(UnicodeDecodeError, seq.decode, 'utf-8', 'strict')
self.assertEqual(seq.decode('utf-8', 'replace'), res)
self.assertEqual((seq+b'b').decode('utf-8', 'replace'), res+'b')
self.assertEqual(seq.decode('utf-8', 'ignore'),
res.replace('\uFFFD', ''))
def to_bytestring(self, seq):
return bytes(int(c, 16) for c in seq.split())
def assertCorrectUTF8Decoding(self, seq, res, err):
"""
Check that an invalid UTF-8 sequence raises a UnicodeDecodeError when
'strict' is used, returns res when 'replace' is used, and that doesn't
return anything when 'ignore' is used.
"""
with self.assertRaises(UnicodeDecodeError) as cm:
seq.decode('utf-8')
exc = cm.exception
self.assertIn(err, str(exc))
self.assertEqual(seq.decode('utf-8', 'replace'), res)
self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'replace'),
'aaaa' + res + 'bbbb')
res = res.replace('\ufffd', '')
self.assertEqual(seq.decode('utf-8', 'ignore'), res)
self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'ignore'),
'aaaa' + res + 'bbbb')
def test_invalid_start_byte(self):
"""
Test that an 'invalid start byte' error is raised when the first byte
is not in the ASCII range or is not a valid start byte of a 2-, 3-, or
4-bytes sequence. The invalid start byte is replaced with a single
U+FFFD when errors='replace'.
E.g. <80> is a continuation byte and can appear only after a start byte.
"""
FFFD = '\ufffd'
for byte in b'\x80\xA0\x9F\xBF\xC0\xC1\xF5\xFF':
self.assertCorrectUTF8Decoding(bytes([byte]), '\ufffd',
'invalid start byte')
def test_unexpected_end_of_data(self):
"""
Test that an 'unexpected end of data' error is raised when the string
ends after a start byte of a 2-, 3-, or 4-bytes sequence without having
enough continuation bytes. The incomplete sequence is replaced with a
single U+FFFD when errors='replace'.
E.g. in the sequence <F3 80 80>, F3 is the start byte of a 4-bytes
sequence, but it's followed by only 2 valid continuation bytes and the
last continuation bytes is missing.
Note: the continuation bytes must be all valid, if one of them is
invalid another error will be raised.
"""
sequences = [
'C2', 'DF',
'E0 A0', 'E0 BF', 'E1 80', 'E1 BF', 'EC 80', 'EC BF',
'ED 80', 'ED 9F', 'EE 80', 'EE BF', 'EF 80', 'EF BF',
'F0 90', 'F0 BF', 'F0 90 80', 'F0 90 BF', 'F0 BF 80', 'F0 BF BF',
'F1 80', 'F1 BF', 'F1 80 80', 'F1 80 BF', 'F1 BF 80', 'F1 BF BF',
'F3 80', 'F3 BF', 'F3 80 80', 'F3 80 BF', 'F3 BF 80', 'F3 BF BF',
'F4 80', 'F4 8F', 'F4 80 80', 'F4 80 BF', 'F4 8F 80', 'F4 8F BF'
]
FFFD = '\ufffd'
for seq in sequences:
self.assertCorrectUTF8Decoding(self.to_bytestring(seq), '\ufffd',
'unexpected end of data')
def test_invalid_cb_for_2bytes_seq(self):
"""
Test that an 'invalid continuation byte' error is raised when the
continuation byte of a 2-bytes sequence is invalid. The start byte
is replaced by a single U+FFFD and the second byte is handled
separately when errors='replace'.
E.g. in the sequence <C2 41>, C2 is the start byte of a 2-bytes
sequence, but 41 is not a valid continuation byte because it's the
ASCII letter 'A'.
"""
FFFD = '\ufffd'
FFFDx2 = FFFD * 2
sequences = [
('C2 00', FFFD+'\x00'), ('C2 7F', FFFD+'\x7f'),
('C2 C0', FFFDx2), ('C2 FF', FFFDx2),
('DF 00', FFFD+'\x00'), ('DF 7F', FFFD+'\x7f'),
('DF C0', FFFDx2), ('DF FF', FFFDx2),
]
for seq, res in sequences:
self.assertCorrectUTF8Decoding(self.to_bytestring(seq), res,
'invalid continuation byte')
def test_invalid_cb_for_3bytes_seq(self):
"""
Test that an 'invalid continuation byte' error is raised when the
continuation byte(s) of a 3-bytes sequence are invalid. When
errors='replace', if the first continuation byte is valid, the first
two bytes (start byte + 1st cb) are replaced by a single U+FFFD and the
third byte is handled separately, otherwise only the start byte is
replaced with a U+FFFD and the other continuation bytes are handled
separately.
E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
sequence, 80 is a valid continuation byte, but 41 is not a valid cb
because it's the ASCII letter 'A'.
Note: when the start byte is E0 or ED, the valid ranges for the first
continuation byte are limited to A0..BF and 80..9F respectively.
Python 2 used to consider all the bytes in range 80..BF valid when the
start byte was ED. This is fixed in Python 3.
"""
FFFD = '\ufffd'
FFFDx2 = FFFD * 2
sequences = [
('E0 00', FFFD+'\x00'), ('E0 7F', FFFD+'\x7f'), ('E0 80', FFFDx2),
('E0 9F', FFFDx2), ('E0 C0', FFFDx2), ('E0 FF', FFFDx2),
('E0 A0 00', FFFD+'\x00'), ('E0 A0 7F', FFFD+'\x7f'),
('E0 A0 C0', FFFDx2), ('E0 A0 FF', FFFDx2),
('E0 BF 00', FFFD+'\x00'), ('E0 BF 7F', FFFD+'\x7f'),
('E0 BF C0', FFFDx2), ('E0 BF FF', FFFDx2), ('E1 00', FFFD+'\x00'),
('E1 7F', FFFD+'\x7f'), ('E1 C0', FFFDx2), ('E1 FF', FFFDx2),
('E1 80 00', FFFD+'\x00'), ('E1 80 7F', FFFD+'\x7f'),
('E1 80 C0', FFFDx2), ('E1 80 FF', FFFDx2),
('E1 BF 00', FFFD+'\x00'), ('E1 BF 7F', FFFD+'\x7f'),
('E1 BF C0', FFFDx2), ('E1 BF FF', FFFDx2), ('EC 00', FFFD+'\x00'),
('EC 7F', FFFD+'\x7f'), ('EC C0', FFFDx2), ('EC FF', FFFDx2),
('EC 80 00', FFFD+'\x00'), ('EC 80 7F', FFFD+'\x7f'),
('EC 80 C0', FFFDx2), ('EC 80 FF', FFFDx2),
('EC BF 00', FFFD+'\x00'), ('EC BF 7F', FFFD+'\x7f'),
('EC BF C0', FFFDx2), ('EC BF FF', FFFDx2), ('ED 00', FFFD+'\x00'),
('ED 7F', FFFD+'\x7f'),
('ED A0', FFFDx2), ('ED BF', FFFDx2), # see note ^
('ED C0', FFFDx2), ('ED FF', FFFDx2), ('ED 80 00', FFFD+'\x00'),
('ED 80 7F', FFFD+'\x7f'), ('ED 80 C0', FFFDx2),
('ED 80 FF', FFFDx2), ('ED 9F 00', FFFD+'\x00'),
('ED 9F 7F', FFFD+'\x7f'), ('ED 9F C0', FFFDx2),
('ED 9F FF', FFFDx2), ('EE 00', FFFD+'\x00'),
('EE 7F', FFFD+'\x7f'), ('EE C0', FFFDx2), ('EE FF', FFFDx2),
('EE 80 00', FFFD+'\x00'), ('EE 80 7F', FFFD+'\x7f'),
('EE 80 C0', FFFDx2), ('EE 80 FF', FFFDx2),
('EE BF 00', FFFD+'\x00'), ('EE BF 7F', FFFD+'\x7f'),
('EE BF C0', FFFDx2), ('EE BF FF', FFFDx2), ('EF 00', FFFD+'\x00'),
('EF 7F', FFFD+'\x7f'), ('EF C0', FFFDx2), ('EF FF', FFFDx2),
('EF 80 00', FFFD+'\x00'), ('EF 80 7F', FFFD+'\x7f'),
('EF 80 C0', FFFDx2), ('EF 80 FF', FFFDx2),
('EF BF 00', FFFD+'\x00'), ('EF BF 7F', FFFD+'\x7f'),
('EF BF C0', FFFDx2), ('EF BF FF', FFFDx2),
]
for seq, res in sequences:
self.assertCorrectUTF8Decoding(self.to_bytestring(seq), res,
'invalid continuation byte')
def test_invalid_cb_for_4bytes_seq(self):
"""
Test that an 'invalid continuation byte' error is raised when the
continuation byte(s) of a 4-bytes sequence are invalid. When
errors='replace',the start byte and all the following valid
continuation bytes are replaced with a single U+FFFD, and all the bytes
starting from the first invalid continuation bytes (included) are
handled separately.
E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
sequence, 80 is a valid continuation byte, but 41 is not a valid cb
because it's the ASCII letter 'A'.
Note: when the start byte is E0 or ED, the valid ranges for the first
continuation byte are limited to A0..BF and 80..9F respectively.
However, when the start byte is ED, Python 2 considers all the bytes
in range 80..BF valid. This is fixed in Python 3.
"""
FFFD = '\ufffd'
FFFDx2 = FFFD * 2
sequences = [
('F0 00', FFFD+'\x00'), ('F0 7F', FFFD+'\x7f'), ('F0 80', FFFDx2),
('F0 8F', FFFDx2), ('F0 C0', FFFDx2), ('F0 FF', FFFDx2),
('F0 90 00', FFFD+'\x00'), ('F0 90 7F', FFFD+'\x7f'),
('F0 90 C0', FFFDx2), ('F0 90 FF', FFFDx2),
('F0 BF 00', FFFD+'\x00'), ('F0 BF 7F', FFFD+'\x7f'),
('F0 BF C0', FFFDx2), ('F0 BF FF', FFFDx2),
('F0 90 80 00', FFFD+'\x00'), ('F0 90 80 7F', FFFD+'\x7f'),
('F0 90 80 C0', FFFDx2), ('F0 90 80 FF', FFFDx2),
('F0 90 BF 00', FFFD+'\x00'), ('F0 90 BF 7F', FFFD+'\x7f'),
('F0 90 BF C0', FFFDx2), ('F0 90 BF FF', FFFDx2),
('F0 BF 80 00', FFFD+'\x00'), ('F0 BF 80 7F', FFFD+'\x7f'),
('F0 BF 80 C0', FFFDx2), ('F0 BF 80 FF', FFFDx2),
('F0 BF BF 00', FFFD+'\x00'), ('F0 BF BF 7F', FFFD+'\x7f'),
('F0 BF BF C0', FFFDx2), ('F0 BF BF FF', FFFDx2),
('F1 00', FFFD+'\x00'), ('F1 7F', FFFD+'\x7f'), ('F1 C0', FFFDx2),
('F1 FF', FFFDx2), ('F1 80 00', FFFD+'\x00'),
('F1 80 7F', FFFD+'\x7f'), ('F1 80 C0', FFFDx2),
('F1 80 FF', FFFDx2), ('F1 BF 00', FFFD+'\x00'),
('F1 BF 7F', FFFD+'\x7f'), ('F1 BF C0', FFFDx2),
('F1 BF FF', FFFDx2), ('F1 80 80 00', FFFD+'\x00'),
('F1 80 80 7F', FFFD+'\x7f'), ('F1 80 80 C0', FFFDx2),
('F1 80 80 FF', FFFDx2), ('F1 80 BF 00', FFFD+'\x00'),
('F1 80 BF 7F', FFFD+'\x7f'), ('F1 80 BF C0', FFFDx2),
('F1 80 BF FF', FFFDx2), ('F1 BF 80 00', FFFD+'\x00'),
('F1 BF 80 7F', FFFD+'\x7f'), ('F1 BF 80 C0', FFFDx2),
('F1 BF 80 FF', FFFDx2), ('F1 BF BF 00', FFFD+'\x00'),
('F1 BF BF 7F', FFFD+'\x7f'), ('F1 BF BF C0', FFFDx2),
('F1 BF BF FF', FFFDx2), ('F3 00', FFFD+'\x00'),
('F3 7F', FFFD+'\x7f'), ('F3 C0', FFFDx2), ('F3 FF', FFFDx2),
('F3 80 00', FFFD+'\x00'), ('F3 80 7F', FFFD+'\x7f'),
('F3 80 C0', FFFDx2), ('F3 80 FF', FFFDx2),
('F3 BF 00', FFFD+'\x00'), ('F3 BF 7F', FFFD+'\x7f'),
('F3 BF C0', FFFDx2), ('F3 BF FF', FFFDx2),
('F3 80 80 00', FFFD+'\x00'), ('F3 80 80 7F', FFFD+'\x7f'),
('F3 80 80 C0', FFFDx2), ('F3 80 80 FF', FFFDx2),
('F3 80 BF 00', FFFD+'\x00'), ('F3 80 BF 7F', FFFD+'\x7f'),
('F3 80 BF C0', FFFDx2), ('F3 80 BF FF', FFFDx2),
('F3 BF 80 00', FFFD+'\x00'), ('F3 BF 80 7F', FFFD+'\x7f'),
('F3 BF 80 C0', FFFDx2), ('F3 BF 80 FF', FFFDx2),
('F3 BF BF 00', FFFD+'\x00'), ('F3 BF BF 7F', FFFD+'\x7f'),
('F3 BF BF C0', FFFDx2), ('F3 BF BF FF', FFFDx2),
('F4 00', FFFD+'\x00'), ('F4 7F', FFFD+'\x7f'), ('F4 90', FFFDx2),
('F4 BF', FFFDx2), ('F4 C0', FFFDx2), ('F4 FF', FFFDx2),
('F4 80 00', FFFD+'\x00'), ('F4 80 7F', FFFD+'\x7f'),
('F4 80 C0', FFFDx2), ('F4 80 FF', FFFDx2),
('F4 8F 00', FFFD+'\x00'), ('F4 8F 7F', FFFD+'\x7f'),
('F4 8F C0', FFFDx2), ('F4 8F FF', FFFDx2),
('F4 80 80 00', FFFD+'\x00'), ('F4 80 80 7F', FFFD+'\x7f'),
('F4 80 80 C0', FFFDx2), ('F4 80 80 FF', FFFDx2),
('F4 80 BF 00', FFFD+'\x00'), ('F4 80 BF 7F', FFFD+'\x7f'),
('F4 80 BF C0', FFFDx2), ('F4 80 BF FF', FFFDx2),
('F4 8F 80 00', FFFD+'\x00'), ('F4 8F 80 7F', FFFD+'\x7f'),
('F4 8F 80 C0', FFFDx2), ('F4 8F 80 FF', FFFDx2),
('F4 8F BF 00', FFFD+'\x00'), ('F4 8F BF 7F', FFFD+'\x7f'),
('F4 8F BF C0', FFFDx2), ('F4 8F BF FF', FFFDx2)
]
for seq, res in sequences:
self.assertCorrectUTF8Decoding(self.to_bytestring(seq), res,
'invalid continuation byte')
def test_codecs_idna(self):
# Test whether trailing dot is preserved
self.assertEqual("www.python.org.".encode("idna"), b"www.python.org.")
def test_codecs_errors(self):
# Error handling (encoding)
self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii')
self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii','strict')
self.assertEqual('Andr\202 x'.encode('ascii','ignore'), b"Andr x")
self.assertEqual('Andr\202 x'.encode('ascii','replace'), b"Andr? x")
self.assertEqual('Andr\202 x'.encode('ascii', 'replace'),
'Andr\202 x'.encode('ascii', errors='replace'))
self.assertEqual('Andr\202 x'.encode('ascii', 'ignore'),
'Andr\202 x'.encode(encoding='ascii', errors='ignore'))
# Error handling (decoding)
self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii')
self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii', 'strict')
self.assertEqual(str(b'Andr\202 x', 'ascii', 'ignore'), "Andr x")
self.assertEqual(str(b'Andr\202 x', 'ascii', 'replace'), 'Andr\uFFFD x')
self.assertEqual(str(b'\202 x', 'ascii', 'replace'), '\uFFFD x')
# Error handling (unknown character names)
self.assertEqual(b"\\N{foo}xx".decode("unicode-escape", "ignore"), "xx")
# Error handling (truncated escape sequence)
self.assertRaises(UnicodeError, b"\\".decode, "unicode-escape")
self.assertRaises(TypeError, b"hello".decode, "test.unicode1")
self.assertRaises(TypeError, str, b"hello", "test.unicode2")
self.assertRaises(TypeError, "hello".encode, "test.unicode1")
self.assertRaises(TypeError, "hello".encode, "test.unicode2")
# Error handling (wrong arguments)
self.assertRaises(TypeError, "hello".encode, 42, 42, 42)
# Error handling (lone surrogate in PyUnicode_TransformDecimalToASCII())
self.assertRaises(UnicodeError, float, "\ud800")
self.assertRaises(UnicodeError, float, "\udf00")
self.assertRaises(UnicodeError, complex, "\ud800")
self.assertRaises(UnicodeError, complex, "\udf00")
def test_codecs(self):
# Encoding
self.assertEqual('hello'.encode('ascii'), b'hello')
self.assertEqual('hello'.encode('utf-7'), b'hello')
self.assertEqual('hello'.encode('utf-8'), b'hello')
self.assertEqual('hello'.encode('utf-8'), b'hello')
self.assertEqual('hello'.encode('utf-16-le'), b'h\000e\000l\000l\000o\000')
self.assertEqual('hello'.encode('utf-16-be'), b'\000h\000e\000l\000l\000o')
self.assertEqual('hello'.encode('latin-1'), b'hello')
# Default encoding is utf-8
self.assertEqual('\u2603'.encode(), b'\xe2\x98\x83')
# Roundtrip safety for BMP (just the first 1024 chars)
for c in range(1024):
u = chr(c)
for encoding in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le',
'utf-16-be', 'raw_unicode_escape',
'unicode_escape', 'unicode_internal'):
with warnings.catch_warnings():
# unicode-internal has been deprecated
warnings.simplefilter("ignore", DeprecationWarning)
self.assertEqual(str(u.encode(encoding),encoding), u)
# Roundtrip safety for BMP (just the first 256 chars)
for c in range(256):
u = chr(c)
for encoding in ('latin-1',):
self.assertEqual(str(u.encode(encoding),encoding), u)
# Roundtrip safety for BMP (just the first 128 chars)
for c in range(128):
u = chr(c)
for encoding in ('ascii',):
self.assertEqual(str(u.encode(encoding),encoding), u)
# Roundtrip safety for non-BMP (just a few chars)
with warnings.catch_warnings():
# unicode-internal has been deprecated
warnings.simplefilter("ignore", DeprecationWarning)
u = '\U00010001\U00020002\U00030003\U00040004\U00050005'
for encoding in ('utf-8', 'utf-16', 'utf-16-le', 'utf-16-be',
'raw_unicode_escape',
'unicode_escape', 'unicode_internal'):
self.assertEqual(str(u.encode(encoding),encoding), u)
# UTF-8 must be roundtrip safe for all code points
# (except surrogates, which are forbidden).
u = ''.join(map(chr, list(range(0, 0xd800)) +
list(range(0xe000, 0x110000))))
for encoding in ('utf-8',):
self.assertEqual(str(u.encode(encoding),encoding), u)
def test_codecs_charmap(self):
# 0-127
s = bytes(range(128))
for encoding in (
'cp037', 'cp1026', 'cp273',
'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
'cp863', 'cp865', 'cp866', 'cp1125',
'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6',
'iso8859_7', 'iso8859_9',
'koi8_r', 'koi8_t', 'koi8_u', 'kz1048', 'latin_1',
'mac_cyrillic', 'mac_latin2',
'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
'cp1256', 'cp1257', 'cp1258',
'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
'cp1006', 'iso8859_8',
### These have undefined mappings:
#'cp424',
### These fail the round-trip:
#'cp875'
):
self.assertEqual(str(s, encoding).encode(encoding), s)
# 128-255
s = bytes(range(128, 256))
for encoding in (
'cp037', 'cp1026', 'cp273',
'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
'cp863', 'cp865', 'cp866', 'cp1125',
'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
'iso8859_2', 'iso8859_4', 'iso8859_5',
'iso8859_9', 'koi8_r', 'koi8_u', 'latin_1',
'mac_cyrillic', 'mac_latin2',
### These have undefined mappings:
#'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
#'cp1256', 'cp1257', 'cp1258',
#'cp424', 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
#'iso8859_3', 'iso8859_6', 'iso8859_7', 'koi8_t', 'kz1048',
#'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
### These fail the round-trip:
#'cp1006', 'cp875', 'iso8859_8',
):
self.assertEqual(str(s, encoding).encode(encoding), s)
def test_concatenation(self):
self.assertEqual(("abc" "def"), "abcdef")
self.assertEqual(("abc" "def"), "abcdef")
self.assertEqual(("abc" "def"), "abcdef")
self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
def test_printing(self):
class BitBucket:
def write(self, text):
pass
out = BitBucket()
print('abc', file=out)
print('abc', 'def', file=out)
print('abc', 'def', file=out)
print('abc', 'def', file=out)
print('abc\n', file=out)
print('abc\n', end=' ', file=out)
print('abc\n', end=' ', file=out)
print('def\n', file=out)
print('def\n', file=out)
def test_ucs4(self):
x = '\U00100000'
y = x.encode("raw-unicode-escape").decode("raw-unicode-escape")
self.assertEqual(x, y)
y = br'\U00100000'
x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
self.assertEqual(x, y)
y = br'\U00010000'
x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
self.assertEqual(x, y)
try:
br'\U11111111'.decode("raw-unicode-escape")
except UnicodeDecodeError as e:
self.assertEqual(e.start, 0)
self.assertEqual(e.end, 10)
else:
self.fail("Should have raised UnicodeDecodeError")
def test_conversion(self):
# Make sure __str__() works properly
class ObjectToStr:
def __str__(self):
return "foo"
class StrSubclassToStr(str):
def __str__(self):
return "foo"
class StrSubclassToStrSubclass(str):
def __new__(cls, content=""):
return str.__new__(cls, 2*content)
def __str__(self):
return self
self.assertEqual(str(ObjectToStr()), "foo")
self.assertEqual(str(StrSubclassToStr("bar")), "foo")
s = str(StrSubclassToStrSubclass("foo"))
self.assertEqual(s, "foofoo")
self.assertIs(type(s), StrSubclassToStrSubclass)
s = StrSubclass(StrSubclassToStrSubclass("foo"))
self.assertEqual(s, "foofoo")
self.assertIs(type(s), StrSubclass)
def test_unicode_repr(self):
class s1:
def __repr__(self):
return '\\n'
class s2:
def __repr__(self):
return '\\n'
self.assertEqual(repr(s1()), '\\n')
self.assertEqual(repr(s2()), '\\n')
def test_printable_repr(self):
self.assertEqual(repr('\U00010000'), "'%c'" % (0x10000,)) # printable
self.assertEqual(repr('\U00014000'), "'\\U00014000'") # nonprintable
# This test only affects 32-bit platforms because expandtabs can only take
# an int as the max value, not a 64-bit C long. If expandtabs is changed
# to take a 64-bit long, this test should apply to all platforms.
@unittest.skipIf(sys.maxsize > (1 << 32) or struct.calcsize('P') != 4,
'only applies to 32-bit platforms')
def test_expandtabs_overflows_gracefully(self):
self.assertRaises(OverflowError, 't\tt\t'.expandtabs, sys.maxsize)
@support.cpython_only
def test_expandtabs_optimization(self):
s = 'abc'
self.assertIs(s.expandtabs(), s)
def test_raiseMemError(self):
if struct.calcsize('P') == 8:
# 64 bits pointers
ascii_struct_size = 48
compact_struct_size = 72
else:
# 32 bits pointers
ascii_struct_size = 24
compact_struct_size = 36
for char in ('a', '\xe9', '\u20ac', '\U0010ffff'):
code = ord(char)
if code < 0x100:
char_size = 1 # sizeof(Py_UCS1)
struct_size = ascii_struct_size
elif code < 0x10000:
char_size = 2 # sizeof(Py_UCS2)
struct_size = compact_struct_size
else:
char_size = 4 # sizeof(Py_UCS4)
struct_size = compact_struct_size
# Note: sys.maxsize is half of the actual max allocation because of
# the signedness of Py_ssize_t. Strings of maxlen-1 should in principle
# be allocatable, given enough memory.
maxlen = ((sys.maxsize - struct_size) // char_size)
alloc = lambda: char * maxlen
self.assertRaises(MemoryError, alloc)
self.assertRaises(MemoryError, alloc)
def test_format_subclass(self):
class S(str):
def __str__(self):
return '__str__ overridden'
s = S('xxx')
self.assertEqual("%s" % s, '__str__ overridden')
self.assertEqual("{}".format(s), '__str__ overridden')
def test_subclass_add(self):
class S(str):
def __add__(self, o):
return "3"
self.assertEqual(S("4") + S("5"), "3")
class S(str):
def __iadd__(self, o):
return "3"
s = S("1")
s += "4"
self.assertEqual(s, "3")
def test_getnewargs(self):
text = 'abc'
args = text.__getnewargs__()
self.assertIsNot(args[0], text)
self.assertEqual(args[0], text)
self.assertEqual(len(args), 1)
def test_resize(self):
for length in range(1, 100, 7):
# generate a fresh string (refcount=1)
text = 'a' * length + 'b'
with support.check_warnings(('unicode_internal codec has been '
'deprecated', DeprecationWarning)):
# fill wstr internal field
abc = text.encode('unicode_internal')
self.assertEqual(abc.decode('unicode_internal'), text)
# resize text: wstr field must be cleared and then recomputed
text += 'c'
abcdef = text.encode('unicode_internal')
self.assertNotEqual(abc, abcdef)
self.assertEqual(abcdef.decode('unicode_internal'), text)
def test_compare(self):
# Issue #17615
N = 10
ascii = 'a' * N
ascii2 = 'z' * N
latin = '\x80' * N
latin2 = '\xff' * N
bmp = '\u0100' * N
bmp2 = '\uffff' * N
astral = '\U00100000' * N
astral2 = '\U0010ffff' * N
strings = (
ascii, ascii2,
latin, latin2,
bmp, bmp2,
astral, astral2)
for text1, text2 in itertools.combinations(strings, 2):
equal = (text1 is text2)
self.assertEqual(text1 == text2, equal)
self.assertEqual(text1 != text2, not equal)
if equal:
self.assertTrue(text1 <= text2)
self.assertTrue(text1 >= text2)
# text1 is text2: duplicate strings to skip the "str1 == str2"
# optimization in unicode_compare_eq() and really compare
# character per character
copy1 = duplicate_string(text1)
copy2 = duplicate_string(text2)
self.assertIsNot(copy1, copy2)
self.assertTrue(copy1 == copy2)
self.assertFalse(copy1 != copy2)
self.assertTrue(copy1 <= copy2)
self.assertTrue(copy2 >= copy2)
self.assertTrue(ascii < ascii2)
self.assertTrue(ascii < latin)
self.assertTrue(ascii < bmp)
self.assertTrue(ascii < astral)
self.assertFalse(ascii >= ascii2)
self.assertFalse(ascii >= latin)
self.assertFalse(ascii >= bmp)
self.assertFalse(ascii >= astral)
self.assertFalse(latin < ascii)
self.assertTrue(latin < latin2)
self.assertTrue(latin < bmp)
self.assertTrue(latin < astral)
self.assertTrue(latin >= ascii)
self.assertFalse(latin >= latin2)
self.assertFalse(latin >= bmp)
self.assertFalse(latin >= astral)
self.assertFalse(bmp < ascii)
self.assertFalse(bmp < latin)
self.assertTrue(bmp < bmp2)
self.assertTrue(bmp < astral)
self.assertTrue(bmp >= ascii)
self.assertTrue(bmp >= latin)
self.assertFalse(bmp >= bmp2)
self.assertFalse(bmp >= astral)
self.assertFalse(astral < ascii)
self.assertFalse(astral < latin)
self.assertFalse(astral < bmp2)
self.assertTrue(astral < astral2)
self.assertTrue(astral >= ascii)
self.assertTrue(astral >= latin)
self.assertTrue(astral >= bmp2)
self.assertFalse(astral >= astral2)
def test_free_after_iterating(self):
support.check_free_after_iterating(self, iter, str)
support.check_free_after_iterating(self, reversed, str)
class CAPITest(unittest.TestCase):
# Test PyUnicode_FromFormat()
def test_from_format(self):
support.import_module('ctypes')
# from ctypes import (
# pythonapi, py_object, sizeof,
# c_int, c_long, c_longlong, c_ssize_t,
# c_uint, c_ulong, c_ulonglong, c_size_t, c_void_p)
name = "PyUnicode_FromFormat"
_PyUnicode_FromFormat = getattr(pythonapi, name)
_PyUnicode_FromFormat.restype = py_object
def PyUnicode_FromFormat(format, *args):
cargs = tuple(
py_object(arg) if isinstance(arg, str) else arg
for arg in args)
return _PyUnicode_FromFormat(format, *cargs)
def check_format(expected, format, *args):
text = PyUnicode_FromFormat(format, *args)
self.assertEqual(expected, text)
# ascii format, non-ascii argument
check_format('ascii\x7f=unicode\xe9',
b'ascii\x7f=%U', 'unicode\xe9')
# non-ascii format, ascii argument: ensure that PyUnicode_FromFormatV()
# raises an error
self.assertRaisesRegex(ValueError,
r'^PyUnicode_FromFormatV\(\) expects an ASCII-encoded format '
'string, got a non-ASCII byte: 0xe9$',
PyUnicode_FromFormat, b'unicode\xe9=%s', 'ascii')
# test "%c"
check_format('\uabcd',
b'%c', c_int(0xabcd))
check_format('\U0010ffff',
b'%c', c_int(0x10ffff))
with self.assertRaises(OverflowError):
PyUnicode_FromFormat(b'%c', c_int(0x110000))
# Issue #18183
check_format('\U00010000\U00100000',
b'%c%c', c_int(0x10000), c_int(0x100000))
# test "%"
check_format('%',
b'%')
check_format('%',
b'%%')
check_format('%s',
b'%%s')
check_format('[%]',
b'[%%]')
check_format('%abc',
b'%%%s', b'abc')
# truncated string
check_format('abc',
b'%.3s', b'abcdef')
check_format('abc[\ufffd',
b'%.5s', 'abc[\u20ac]'.encode('utf8'))
check_format("'\\u20acABC'",
b'%A', '\u20acABC')
check_format("'\\u20",
b'%.5A', '\u20acABCDEF')
check_format("'\u20acABC'",
b'%R', '\u20acABC')
check_format("'\u20acA",
b'%.3R', '\u20acABCDEF')
check_format('\u20acAB',
b'%.3S', '\u20acABCDEF')
check_format('\u20acAB',
b'%.3U', '\u20acABCDEF')
check_format('\u20acAB',
b'%.3V', '\u20acABCDEF', None)
check_format('abc[\ufffd',
b'%.5V', None, 'abc[\u20ac]'.encode('utf8'))
# following tests comes from #7330
# test width modifier and precision modifier with %S
check_format("repr= abc",
b'repr=%5S', 'abc')
check_format("repr=ab",
b'repr=%.2S', 'abc')
check_format("repr= ab",
b'repr=%5.2S', 'abc')
# test width modifier and precision modifier with %R
check_format("repr= 'abc'",
b'repr=%8R', 'abc')
check_format("repr='ab",
b'repr=%.3R', 'abc')
check_format("repr= 'ab",
b'repr=%5.3R', 'abc')
# test width modifier and precision modifier with %A
check_format("repr= 'abc'",
b'repr=%8A', 'abc')
check_format("repr='ab",
b'repr=%.3A', 'abc')
check_format("repr= 'ab",
b'repr=%5.3A', 'abc')
# test width modifier and precision modifier with %s
check_format("repr= abc",
b'repr=%5s', b'abc')
check_format("repr=ab",
b'repr=%.2s', b'abc')
check_format("repr= ab",
b'repr=%5.2s', b'abc')
# test width modifier and precision modifier with %U
check_format("repr= abc",
b'repr=%5U', 'abc')
check_format("repr=ab",
b'repr=%.2U', 'abc')
check_format("repr= ab",
b'repr=%5.2U', 'abc')
# test width modifier and precision modifier with %V
check_format("repr= abc",
b'repr=%5V', 'abc', b'123')
check_format("repr=ab",
b'repr=%.2V', 'abc', b'123')
check_format("repr= ab",
b'repr=%5.2V', 'abc', b'123')
check_format("repr= 123",
b'repr=%5V', None, b'123')
check_format("repr=12",
b'repr=%.2V', None, b'123')
check_format("repr= 12",
b'repr=%5.2V', None, b'123')
# test integer formats (%i, %d, %u)
check_format('010',
b'%03i', c_int(10))
check_format('0010',
b'%0.4i', c_int(10))
check_format('-123',
b'%i', c_int(-123))
check_format('-123',
b'%li', c_long(-123))
check_format('-123',
b'%lli', c_longlong(-123))
check_format('-123',
b'%zi', c_ssize_t(-123))
check_format('-123',
b'%d', c_int(-123))
check_format('-123',
b'%ld', c_long(-123))
check_format('-123',
b'%lld', c_longlong(-123))
check_format('-123',
b'%zd', c_ssize_t(-123))
check_format('123',
b'%u', c_uint(123))
check_format('123',
b'%lu', c_ulong(123))
check_format('123',
b'%llu', c_ulonglong(123))
check_format('123',
b'%zu', c_size_t(123))
# test long output
min_longlong = -(2 ** (8 * sizeof(c_longlong) - 1))
max_longlong = -min_longlong - 1
check_format(str(min_longlong),
b'%lld', c_longlong(min_longlong))
check_format(str(max_longlong),
b'%lld', c_longlong(max_longlong))
max_ulonglong = 2 ** (8 * sizeof(c_ulonglong)) - 1
check_format(str(max_ulonglong),
b'%llu', c_ulonglong(max_ulonglong))
PyUnicode_FromFormat(b'%p', c_void_p(-1))
# test padding (width and/or precision)
check_format('123'.rjust(10, '0'),
b'%010i', c_int(123))
check_format('123'.rjust(100),
b'%100i', c_int(123))
check_format('123'.rjust(100, '0'),
b'%.100i', c_int(123))
check_format('123'.rjust(80, '0').rjust(100),
b'%100.80i', c_int(123))
check_format('123'.rjust(10, '0'),
b'%010u', c_uint(123))
check_format('123'.rjust(100),
b'%100u', c_uint(123))
check_format('123'.rjust(100, '0'),
b'%.100u', c_uint(123))
check_format('123'.rjust(80, '0').rjust(100),
b'%100.80u', c_uint(123))
check_format('123'.rjust(10, '0'),
b'%010x', c_int(0x123))
check_format('123'.rjust(100),
b'%100x', c_int(0x123))
check_format('123'.rjust(100, '0'),
b'%.100x', c_int(0x123))
check_format('123'.rjust(80, '0').rjust(100),
b'%100.80x', c_int(0x123))
# test %A
check_format(r"%A:'abc\xe9\uabcd\U0010ffff'",
b'%%A:%A', 'abc\xe9\uabcd\U0010ffff')
# test %V
check_format('repr=abc',
b'repr=%V', 'abc', b'xyz')
# Test string decode from parameter of %s using utf-8.
# b'\xe4\xba\xba\xe6\xb0\x91' is utf-8 encoded byte sequence of
# '\u4eba\u6c11'
check_format('repr=\u4eba\u6c11',
b'repr=%V', None, b'\xe4\xba\xba\xe6\xb0\x91')
#Test replace error handler.
check_format('repr=abc\ufffd',
b'repr=%V', None, b'abc\xff')
# not supported: copy the raw format string. these tests are just here
# to check for crashes and should not be considered as specifications
check_format('%s',
b'%1%s', b'abc')
check_format('%1abc',
b'%1abc')
check_format('%+i',
b'%+i', c_int(10))
check_format('%.%s',
b'%.%s', b'abc')
# Test PyUnicode_AsWideChar()
@support.cpython_only
def test_aswidechar(self):
from _testcapi import unicode_aswidechar
support.import_module('ctypes')
# from ctypes import c_wchar, sizeof
wchar, size = unicode_aswidechar('abcdef', 2)
self.assertEqual(size, 2)
self.assertEqual(wchar, 'ab')
wchar, size = unicode_aswidechar('abc', 3)
self.assertEqual(size, 3)
self.assertEqual(wchar, 'abc')
wchar, size = unicode_aswidechar('abc', 4)
self.assertEqual(size, 3)
self.assertEqual(wchar, 'abc\0')
wchar, size = unicode_aswidechar('abc', 10)
self.assertEqual(size, 3)
self.assertEqual(wchar, 'abc\0')
wchar, size = unicode_aswidechar('abc\0def', 20)
self.assertEqual(size, 7)
self.assertEqual(wchar, 'abc\0def\0')
nonbmp = chr(0x10ffff)
if sizeof(c_wchar) == 2:
buflen = 3
nchar = 2
else: # sizeof(c_wchar) == 4
buflen = 2
nchar = 1
wchar, size = unicode_aswidechar(nonbmp, buflen)
self.assertEqual(size, nchar)
self.assertEqual(wchar, nonbmp + '\0')
# Test PyUnicode_AsWideCharString()
@support.cpython_only
def test_aswidecharstring(self):
from _testcapi import unicode_aswidecharstring
support.import_module('ctypes')
# from ctypes import c_wchar, sizeof
wchar, size = unicode_aswidecharstring('abc')
self.assertEqual(size, 3)
self.assertEqual(wchar, 'abc\0')
wchar, size = unicode_aswidecharstring('abc\0def')
self.assertEqual(size, 7)
self.assertEqual(wchar, 'abc\0def\0')
nonbmp = chr(0x10ffff)
if sizeof(c_wchar) == 2:
nchar = 2
else: # sizeof(c_wchar) == 4
nchar = 1
wchar, size = unicode_aswidecharstring(nonbmp)
self.assertEqual(size, nchar)
self.assertEqual(wchar, nonbmp + '\0')
# Test PyUnicode_AsUCS4()
@support.cpython_only
def test_asucs4(self):
from _testcapi import unicode_asucs4
for s in ['abc', '\xa1\xa2', '\u4f60\u597d', 'a\U0001f600',
'a\ud800b\udfffc', '\ud834\udd1e']:
l = len(s)
self.assertEqual(unicode_asucs4(s, l, 1), s+'\0')
self.assertEqual(unicode_asucs4(s, l, 0), s+'\uffff')
self.assertEqual(unicode_asucs4(s, l+1, 1), s+'\0\uffff')
self.assertEqual(unicode_asucs4(s, l+1, 0), s+'\0\uffff')
self.assertRaises(SystemError, unicode_asucs4, s, l-1, 1)
self.assertRaises(SystemError, unicode_asucs4, s, l-2, 0)
s = '\0'.join([s, s])
self.assertEqual(unicode_asucs4(s, len(s), 1), s+'\0')
self.assertEqual(unicode_asucs4(s, len(s), 0), s+'\uffff')
# Test PyUnicode_CopyCharacters()
@support.cpython_only
def test_copycharacters(self):
from _testcapi import unicode_copycharacters
strings = [
'abcde', '\xa1\xa2\xa3\xa4\xa5',
'\u4f60\u597d\u4e16\u754c\uff01',
'\U0001f600\U0001f601\U0001f602\U0001f603\U0001f604'
]
for idx, from_ in enumerate(strings):
# wide -> narrow: exceed maxchar limitation
for to in strings[:idx]:
self.assertRaises(
SystemError,
unicode_copycharacters, to, 0, from_, 0, 5
)
# same kind
for from_start in range(5):
self.assertEqual(
unicode_copycharacters(from_, 0, from_, from_start, 5),
(from_[from_start:from_start+5].ljust(5, '\0'),
5-from_start)
)
for to_start in range(5):
self.assertEqual(
unicode_copycharacters(from_, to_start, from_, to_start, 5),
(from_[to_start:to_start+5].rjust(5, '\0'),
5-to_start)
)
# narrow -> wide
# Tests omitted since this creates invalid strings.
s = strings[0]
self.assertRaises(IndexError, unicode_copycharacters, s, 6, s, 0, 5)
self.assertRaises(IndexError, unicode_copycharacters, s, -1, s, 0, 5)
self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, 6, 5)
self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, -1, 5)
self.assertRaises(SystemError, unicode_copycharacters, s, 1, s, 0, 5)
self.assertRaises(SystemError, unicode_copycharacters, s, 0, s, 0, -1)
self.assertRaises(SystemError, unicode_copycharacters, s, 0, b'', 0, 0)
@support.cpython_only
def test_encode_decimal(self):
from _testcapi import unicode_encodedecimal
self.assertEqual(unicode_encodedecimal('123'),
b'123')
self.assertEqual(unicode_encodedecimal('\u0663.\u0661\u0664'),
b'3.14')
self.assertEqual(unicode_encodedecimal("\N{EM SPACE}3.14\N{EN SPACE}"),
b' 3.14 ')
self.assertRaises(UnicodeEncodeError,
unicode_encodedecimal, "123\u20ac", "strict")
self.assertRaisesRegex(
ValueError,
"^'decimal' codec can't encode character",
unicode_encodedecimal, "123\u20ac", "replace")
@support.cpython_only
def test_transform_decimal(self):
from _testcapi import unicode_transformdecimaltoascii as transform_decimal
self.assertEqual(transform_decimal('123'),
'123')
self.assertEqual(transform_decimal('\u0663.\u0661\u0664'),
'3.14')
self.assertEqual(transform_decimal("\N{EM SPACE}3.14\N{EN SPACE}"),
"\N{EM SPACE}3.14\N{EN SPACE}")
self.assertEqual(transform_decimal('123\u20ac'),
'123\u20ac')
@support.cpython_only
def test_pep393_utf8_caching_bug(self):
# Issue #25709: Problem with string concatenation and utf-8 cache
from _testcapi import getargs_s_hash
for k in 0x24, 0xa4, 0x20ac, 0x1f40d:
s = ''
for i in range(5):
# Due to CPython specific optimization the 's' string can be
# resized in-place.
s += chr(k)
# Parsing with the "s#" format code calls indirectly
# PyUnicode_AsUTF8AndSize() which creates the UTF-8
# encoded string cached in the Unicode object.
self.assertEqual(getargs_s_hash(s), chr(k).encode() * (i + 1))
# Check that the second call returns the same result
self.assertEqual(getargs_s_hash(s), chr(k).encode() * (i + 1))
class StringModuleTest(unittest.TestCase):
def test_formatter_parser(self):
def parse(format):
return list(_string.formatter_parser(format))
formatter = parse("prefix {2!s}xxx{0:^+10.3f}{obj.attr!s} {z[0]!s:10}")
self.assertEqual(formatter, [
('prefix ', '2', '', 's'),
('xxx', '0', '^+10.3f', None),
('', 'obj.attr', '', 's'),
(' ', 'z[0]', '10', 's'),
])
formatter = parse("prefix {} suffix")
self.assertEqual(formatter, [
('prefix ', '', '', None),
(' suffix', None, None, None),
])
formatter = parse("str")
self.assertEqual(formatter, [
('str', None, None, None),
])
formatter = parse("")
self.assertEqual(formatter, [])
formatter = parse("{0}")
self.assertEqual(formatter, [
('', '0', '', None),
])
self.assertRaises(TypeError, _string.formatter_parser, 1)
def test_formatter_field_name_split(self):
def split(name):
items = list(_string.formatter_field_name_split(name))
items[1] = list(items[1])
return items
self.assertEqual(split("obj"), ["obj", []])
self.assertEqual(split("obj.arg"), ["obj", [(True, 'arg')]])
self.assertEqual(split("obj[key]"), ["obj", [(False, 'key')]])
self.assertEqual(split("obj.arg[key1][key2]"), [
"obj",
[(True, 'arg'),
(False, 'key1'),
(False, 'key2'),
]])
self.assertRaises(TypeError, _string.formatter_field_name_split, 1)
if __name__ == "__main__":
unittest.main()
| 133,215 | 3,018 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_xml_dom_minicompat.py | # Tests for xml.dom.minicompat
import copy
import pickle
import unittest
import xml.dom
from xml.dom.minicompat import *
class EmptyNodeListTestCase(unittest.TestCase):
"""Tests for the EmptyNodeList class."""
def test_emptynodelist_item(self):
# Test item access on an EmptyNodeList.
node_list = EmptyNodeList()
self.assertIsNone(node_list.item(0))
self.assertIsNone(node_list.item(-1)) # invalid item
with self.assertRaises(IndexError):
node_list[0]
with self.assertRaises(IndexError):
node_list[-1]
def test_emptynodelist_length(self):
node_list = EmptyNodeList()
# Reading
self.assertEqual(node_list.length, 0)
# Writing
with self.assertRaises(xml.dom.NoModificationAllowedErr):
node_list.length = 111
def test_emptynodelist___add__(self):
node_list = EmptyNodeList() + NodeList()
self.assertEqual(node_list, NodeList())
def test_emptynodelist___radd__(self):
node_list = [1,2] + EmptyNodeList()
self.assertEqual(node_list, [1,2])
class NodeListTestCase(unittest.TestCase):
"""Tests for the NodeList class."""
def test_nodelist_item(self):
# Test items access on a NodeList.
# First, use an empty NodeList.
node_list = NodeList()
self.assertIsNone(node_list.item(0))
self.assertIsNone(node_list.item(-1))
with self.assertRaises(IndexError):
node_list[0]
with self.assertRaises(IndexError):
node_list[-1]
# Now, use a NodeList with items.
node_list.append(111)
node_list.append(999)
self.assertEqual(node_list.item(0), 111)
self.assertIsNone(node_list.item(-1)) # invalid item
self.assertEqual(node_list[0], 111)
self.assertEqual(node_list[-1], 999)
def test_nodelist_length(self):
node_list = NodeList([1, 2])
# Reading
self.assertEqual(node_list.length, 2)
# Writing
with self.assertRaises(xml.dom.NoModificationAllowedErr):
node_list.length = 111
def test_nodelist___add__(self):
node_list = NodeList([3, 4]) + [1, 2]
self.assertEqual(node_list, NodeList([3, 4, 1, 2]))
def test_nodelist___radd__(self):
node_list = [1, 2] + NodeList([3, 4])
self.assertEqual(node_list, NodeList([1, 2, 3, 4]))
def test_nodelist_pickle_roundtrip(self):
# Test pickling and unpickling of a NodeList.
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
# Empty NodeList.
node_list = NodeList()
pickled = pickle.dumps(node_list, proto)
unpickled = pickle.loads(pickled)
self.assertIsNot(unpickled, node_list)
self.assertEqual(unpickled, node_list)
# Non-empty NodeList.
node_list.append(1)
node_list.append(2)
pickled = pickle.dumps(node_list, proto)
unpickled = pickle.loads(pickled)
self.assertIsNot(unpickled, node_list)
self.assertEqual(unpickled, node_list)
def test_nodelist_copy(self):
# Empty NodeList.
node_list = NodeList()
copied = copy.copy(node_list)
self.assertIsNot(copied, node_list)
self.assertEqual(copied, node_list)
# Non-empty NodeList.
node_list.append([1])
node_list.append([2])
copied = copy.copy(node_list)
self.assertIsNot(copied, node_list)
self.assertEqual(copied, node_list)
for x, y in zip(copied, node_list):
self.assertIs(x, y)
def test_nodelist_deepcopy(self):
# Empty NodeList.
node_list = NodeList()
copied = copy.deepcopy(node_list)
self.assertIsNot(copied, node_list)
self.assertEqual(copied, node_list)
# Non-empty NodeList.
node_list.append([1])
node_list.append([2])
copied = copy.deepcopy(node_list)
self.assertIsNot(copied, node_list)
self.assertEqual(copied, node_list)
for x, y in zip(copied, node_list):
self.assertIsNot(x, y)
self.assertEqual(x, y)
if __name__ == '__main__':
unittest.main()
| 4,282 | 139 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/ssltests.py | # Convenience test module to run all of the OpenSSL-related tests in the
# standard library.
import ssl
import sys
import subprocess
TESTS = [
'test_asyncio', 'test_ensurepip.py', 'test_ftplib', 'test_hashlib',
'test_hmac', 'test_httplib', 'test_imaplib', 'test_nntplib',
'test_poplib', 'test_ssl', 'test_smtplib', 'test_smtpnet',
'test_urllib2_localnet', 'test_venv', 'test_xmlrpc'
]
def run_regrtests(*extra_args):
print(ssl.OPENSSL_VERSION)
args = [
sys.executable,
'-Werror', '-bb', # turn warnings into exceptions
'-m', 'test',
]
if not extra_args:
args.extend([
'-r', # randomize
'-w', # re-run failed tests with -v
'-u', 'network', # use network
'-u', 'urlfetch', # download test vectors
'-j', '0' # use multiple CPUs
])
else:
args.extend(extra_args)
args.extend(TESTS)
result = subprocess.call(args)
sys.exit(result)
if __name__ == '__main__':
run_regrtests(*sys.argv[1:])
| 1,051 | 38 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/audiotests.py | from test.support import findfile, TESTFN, unlink
import array
import io
import pickle
class UnseekableIO(io.FileIO):
def tell(self):
raise io.UnsupportedOperation
def seek(self, *args, **kwargs):
raise io.UnsupportedOperation
class AudioTests:
close_fd = False
def setUp(self):
self.f = self.fout = None
def tearDown(self):
if self.f is not None:
self.f.close()
if self.fout is not None:
self.fout.close()
unlink(TESTFN)
def check_params(self, f, nchannels, sampwidth, framerate, nframes,
comptype, compname):
self.assertEqual(f.getnchannels(), nchannels)
self.assertEqual(f.getsampwidth(), sampwidth)
self.assertEqual(f.getframerate(), framerate)
self.assertEqual(f.getnframes(), nframes)
self.assertEqual(f.getcomptype(), comptype)
self.assertEqual(f.getcompname(), compname)
params = f.getparams()
self.assertEqual(params,
(nchannels, sampwidth, framerate, nframes, comptype, compname))
self.assertEqual(params.nchannels, nchannels)
self.assertEqual(params.sampwidth, sampwidth)
self.assertEqual(params.framerate, framerate)
self.assertEqual(params.nframes, nframes)
self.assertEqual(params.comptype, comptype)
self.assertEqual(params.compname, compname)
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
dump = pickle.dumps(params, proto)
self.assertEqual(pickle.loads(dump), params)
class AudioWriteTests(AudioTests):
def create_file(self, testfile):
f = self.fout = self.module.open(testfile, 'wb')
f.setnchannels(self.nchannels)
f.setsampwidth(self.sampwidth)
f.setframerate(self.framerate)
f.setcomptype(self.comptype, self.compname)
return f
def check_file(self, testfile, nframes, frames):
with self.module.open(testfile, 'rb') as f:
self.assertEqual(f.getnchannels(), self.nchannels)
self.assertEqual(f.getsampwidth(), self.sampwidth)
self.assertEqual(f.getframerate(), self.framerate)
self.assertEqual(f.getnframes(), nframes)
self.assertEqual(f.readframes(nframes), frames)
def test_write_params(self):
f = self.create_file(TESTFN)
f.setnframes(self.nframes)
f.writeframes(self.frames)
self.check_params(f, self.nchannels, self.sampwidth, self.framerate,
self.nframes, self.comptype, self.compname)
f.close()
def test_write_context_manager_calls_close(self):
# Close checks for a minimum header and will raise an error
# if it is not set, so this proves that close is called.
with self.assertRaises(self.module.Error):
with self.module.open(TESTFN, 'wb'):
pass
with self.assertRaises(self.module.Error):
with open(TESTFN, 'wb') as testfile:
with self.module.open(testfile):
pass
def test_context_manager_with_open_file(self):
with open(TESTFN, 'wb') as testfile:
with self.module.open(testfile) as f:
f.setnchannels(self.nchannels)
f.setsampwidth(self.sampwidth)
f.setframerate(self.framerate)
f.setcomptype(self.comptype, self.compname)
self.assertEqual(testfile.closed, self.close_fd)
with open(TESTFN, 'rb') as testfile:
with self.module.open(testfile) as f:
self.assertFalse(f.getfp().closed)
params = f.getparams()
self.assertEqual(params.nchannels, self.nchannels)
self.assertEqual(params.sampwidth, self.sampwidth)
self.assertEqual(params.framerate, self.framerate)
if not self.close_fd:
self.assertIsNone(f.getfp())
self.assertEqual(testfile.closed, self.close_fd)
def test_context_manager_with_filename(self):
# If the file doesn't get closed, this test won't fail, but it will
# produce a resource leak warning.
with self.module.open(TESTFN, 'wb') as f:
f.setnchannels(self.nchannels)
f.setsampwidth(self.sampwidth)
f.setframerate(self.framerate)
f.setcomptype(self.comptype, self.compname)
with self.module.open(TESTFN) as f:
self.assertFalse(f.getfp().closed)
params = f.getparams()
self.assertEqual(params.nchannels, self.nchannels)
self.assertEqual(params.sampwidth, self.sampwidth)
self.assertEqual(params.framerate, self.framerate)
if not self.close_fd:
self.assertIsNone(f.getfp())
def test_write(self):
f = self.create_file(TESTFN)
f.setnframes(self.nframes)
f.writeframes(self.frames)
f.close()
self.check_file(TESTFN, self.nframes, self.frames)
def test_write_bytearray(self):
f = self.create_file(TESTFN)
f.setnframes(self.nframes)
f.writeframes(bytearray(self.frames))
f.close()
self.check_file(TESTFN, self.nframes, self.frames)
def test_write_array(self):
f = self.create_file(TESTFN)
f.setnframes(self.nframes)
f.writeframes(array.array('h', self.frames))
f.close()
self.check_file(TESTFN, self.nframes, self.frames)
def test_write_memoryview(self):
f = self.create_file(TESTFN)
f.setnframes(self.nframes)
f.writeframes(memoryview(self.frames))
f.close()
self.check_file(TESTFN, self.nframes, self.frames)
def test_incompleted_write(self):
with open(TESTFN, 'wb') as testfile:
testfile.write(b'ababagalamaga')
f = self.create_file(testfile)
f.setnframes(self.nframes + 1)
f.writeframes(self.frames)
f.close()
with open(TESTFN, 'rb') as testfile:
self.assertEqual(testfile.read(13), b'ababagalamaga')
self.check_file(testfile, self.nframes, self.frames)
def test_multiple_writes(self):
with open(TESTFN, 'wb') as testfile:
testfile.write(b'ababagalamaga')
f = self.create_file(testfile)
f.setnframes(self.nframes)
framesize = self.nchannels * self.sampwidth
f.writeframes(self.frames[:-framesize])
f.writeframes(self.frames[-framesize:])
f.close()
with open(TESTFN, 'rb') as testfile:
self.assertEqual(testfile.read(13), b'ababagalamaga')
self.check_file(testfile, self.nframes, self.frames)
def test_overflowed_write(self):
with open(TESTFN, 'wb') as testfile:
testfile.write(b'ababagalamaga')
f = self.create_file(testfile)
f.setnframes(self.nframes - 1)
f.writeframes(self.frames)
f.close()
with open(TESTFN, 'rb') as testfile:
self.assertEqual(testfile.read(13), b'ababagalamaga')
self.check_file(testfile, self.nframes, self.frames)
def test_unseekable_read(self):
with self.create_file(TESTFN) as f:
f.setnframes(self.nframes)
f.writeframes(self.frames)
with UnseekableIO(TESTFN, 'rb') as testfile:
self.check_file(testfile, self.nframes, self.frames)
def test_unseekable_write(self):
with UnseekableIO(TESTFN, 'wb') as testfile:
with self.create_file(testfile) as f:
f.setnframes(self.nframes)
f.writeframes(self.frames)
self.check_file(TESTFN, self.nframes, self.frames)
def test_unseekable_incompleted_write(self):
with UnseekableIO(TESTFN, 'wb') as testfile:
testfile.write(b'ababagalamaga')
f = self.create_file(testfile)
f.setnframes(self.nframes + 1)
try:
f.writeframes(self.frames)
except OSError:
pass
try:
f.close()
except OSError:
pass
with open(TESTFN, 'rb') as testfile:
self.assertEqual(testfile.read(13), b'ababagalamaga')
self.check_file(testfile, self.nframes + 1, self.frames)
def test_unseekable_overflowed_write(self):
with UnseekableIO(TESTFN, 'wb') as testfile:
testfile.write(b'ababagalamaga')
f = self.create_file(testfile)
f.setnframes(self.nframes - 1)
try:
f.writeframes(self.frames)
except OSError:
pass
try:
f.close()
except OSError:
pass
with open(TESTFN, 'rb') as testfile:
self.assertEqual(testfile.read(13), b'ababagalamaga')
framesize = self.nchannels * self.sampwidth
self.check_file(testfile, self.nframes - 1, self.frames[:-framesize])
class AudioTestsWithSourceFile(AudioTests):
@classmethod
def setUpClass(cls):
cls.sndfilepath = findfile(cls.sndfilename, subdir='/zip/.python/test/audiodata')
def test_read_params(self):
f = self.f = self.module.open(self.sndfilepath)
#self.assertEqual(f.getfp().name, self.sndfilepath)
self.check_params(f, self.nchannels, self.sampwidth, self.framerate,
self.sndfilenframes, self.comptype, self.compname)
def test_close(self):
with open(self.sndfilepath, 'rb') as testfile:
f = self.f = self.module.open(testfile)
self.assertFalse(testfile.closed)
f.close()
self.assertEqual(testfile.closed, self.close_fd)
with open(TESTFN, 'wb') as testfile:
fout = self.fout = self.module.open(testfile, 'wb')
self.assertFalse(testfile.closed)
with self.assertRaises(self.module.Error):
fout.close()
self.assertEqual(testfile.closed, self.close_fd)
fout.close() # do nothing
def test_read(self):
framesize = self.nchannels * self.sampwidth
chunk1 = self.frames[:2 * framesize]
chunk2 = self.frames[2 * framesize: 4 * framesize]
f = self.f = self.module.open(self.sndfilepath)
self.assertEqual(f.readframes(0), b'')
self.assertEqual(f.tell(), 0)
self.assertEqual(f.readframes(2), chunk1)
f.rewind()
pos0 = f.tell()
self.assertEqual(pos0, 0)
self.assertEqual(f.readframes(2), chunk1)
pos2 = f.tell()
self.assertEqual(pos2, 2)
self.assertEqual(f.readframes(2), chunk2)
f.setpos(pos2)
self.assertEqual(f.readframes(2), chunk2)
f.setpos(pos0)
self.assertEqual(f.readframes(2), chunk1)
with self.assertRaises(self.module.Error):
f.setpos(-1)
with self.assertRaises(self.module.Error):
f.setpos(f.getnframes() + 1)
def test_copy(self):
f = self.f = self.module.open(self.sndfilepath)
fout = self.fout = self.module.open(TESTFN, 'wb')
fout.setparams(f.getparams())
i = 0
n = f.getnframes()
while n > 0:
i += 1
fout.writeframes(f.readframes(i))
n -= i
fout.close()
fout = self.fout = self.module.open(TESTFN, 'rb')
f.rewind()
self.assertEqual(f.getparams(), fout.getparams())
self.assertEqual(f.readframes(f.getnframes()),
fout.readframes(fout.getnframes()))
def test_read_not_from_start(self):
with open(TESTFN, 'wb') as testfile:
testfile.write(b'ababagalamaga')
with open(self.sndfilepath, 'rb') as f:
testfile.write(f.read())
with open(TESTFN, 'rb') as testfile:
self.assertEqual(testfile.read(13), b'ababagalamaga')
with self.module.open(testfile, 'rb') as f:
self.assertEqual(f.getnchannels(), self.nchannels)
self.assertEqual(f.getsampwidth(), self.sampwidth)
self.assertEqual(f.getframerate(), self.framerate)
self.assertEqual(f.getnframes(), self.sndfilenframes)
self.assertEqual(f.readframes(self.nframes), self.frames)
| 12,409 | 330 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_iter.py | # Test iterators.
import sys
import unittest
from test.support import run_unittest, TESTFN, unlink, cpython_only
from test.support import check_free_after_iterating
import pickle
import collections.abc
# Test result of triple loop (too big to inline)
TRIPLETS = [(0, 0, 0), (0, 0, 1), (0, 0, 2),
(0, 1, 0), (0, 1, 1), (0, 1, 2),
(0, 2, 0), (0, 2, 1), (0, 2, 2),
(1, 0, 0), (1, 0, 1), (1, 0, 2),
(1, 1, 0), (1, 1, 1), (1, 1, 2),
(1, 2, 0), (1, 2, 1), (1, 2, 2),
(2, 0, 0), (2, 0, 1), (2, 0, 2),
(2, 1, 0), (2, 1, 1), (2, 1, 2),
(2, 2, 0), (2, 2, 1), (2, 2, 2)]
# Helper classes
class BasicIterClass:
def __init__(self, n):
self.n = n
self.i = 0
def __next__(self):
res = self.i
if res >= self.n:
raise StopIteration
self.i = res + 1
return res
def __iter__(self):
return self
class IteratingSequenceClass:
def __init__(self, n):
self.n = n
def __iter__(self):
return BasicIterClass(self.n)
class SequenceClass:
def __init__(self, n):
self.n = n
def __getitem__(self, i):
if 0 <= i < self.n:
return i
else:
raise IndexError
class UnlimitedSequenceClass:
def __getitem__(self, i):
return i
class DefaultIterClass:
pass
class NoIterClass:
def __getitem__(self, i):
return i
__iter__ = None
# Main test suite
class TestCase(unittest.TestCase):
# Helper to check that an iterator returns a given sequence
def check_iterator(self, it, seq, pickle=True):
if pickle:
self.check_pickle(it, seq)
res = []
while 1:
try:
val = next(it)
except StopIteration:
break
res.append(val)
self.assertEqual(res, seq)
# Helper to check that a for loop generates a given sequence
def check_for_loop(self, expr, seq, pickle=True):
if pickle:
self.check_pickle(iter(expr), seq)
res = []
for val in expr:
res.append(val)
self.assertEqual(res, seq)
# Helper to check picklability
def check_pickle(self, itorg, seq):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
d = pickle.dumps(itorg, proto)
it = pickle.loads(d)
# Cannot assert type equality because dict iterators unpickle as list
# iterators.
# self.assertEqual(type(itorg), type(it))
self.assertTrue(isinstance(it, collections.abc.Iterator))
self.assertEqual(list(it), seq)
it = pickle.loads(d)
try:
next(it)
except StopIteration:
continue
d = pickle.dumps(it, proto)
it = pickle.loads(d)
self.assertEqual(list(it), seq[1:])
# Test basic use of iter() function
def test_iter_basic(self):
self.check_iterator(iter(range(10)), list(range(10)))
# Test that iter(iter(x)) is the same as iter(x)
def test_iter_idempotency(self):
seq = list(range(10))
it = iter(seq)
it2 = iter(it)
self.assertTrue(it is it2)
# Test that for loops over iterators work
def test_iter_for_loop(self):
self.check_for_loop(iter(range(10)), list(range(10)))
# Test several independent iterators over the same list
def test_iter_independence(self):
seq = range(3)
res = []
for i in iter(seq):
for j in iter(seq):
for k in iter(seq):
res.append((i, j, k))
self.assertEqual(res, TRIPLETS)
# Test triple list comprehension using iterators
def test_nested_comprehensions_iter(self):
seq = range(3)
res = [(i, j, k)
for i in iter(seq) for j in iter(seq) for k in iter(seq)]
self.assertEqual(res, TRIPLETS)
# Test triple list comprehension without iterators
def test_nested_comprehensions_for(self):
seq = range(3)
res = [(i, j, k) for i in seq for j in seq for k in seq]
self.assertEqual(res, TRIPLETS)
# Test a class with __iter__ in a for loop
def test_iter_class_for(self):
self.check_for_loop(IteratingSequenceClass(10), list(range(10)))
# Test a class with __iter__ with explicit iter()
def test_iter_class_iter(self):
self.check_iterator(iter(IteratingSequenceClass(10)), list(range(10)))
# Test for loop on a sequence class without __iter__
def test_seq_class_for(self):
self.check_for_loop(SequenceClass(10), list(range(10)))
# Test iter() on a sequence class without __iter__
def test_seq_class_iter(self):
self.check_iterator(iter(SequenceClass(10)), list(range(10)))
def test_mutating_seq_class_iter_pickle(self):
orig = SequenceClass(5)
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
# initial iterator
itorig = iter(orig)
d = pickle.dumps((itorig, orig), proto)
it, seq = pickle.loads(d)
seq.n = 7
self.assertIs(type(it), type(itorig))
self.assertEqual(list(it), list(range(7)))
# running iterator
next(itorig)
d = pickle.dumps((itorig, orig), proto)
it, seq = pickle.loads(d)
seq.n = 7
self.assertIs(type(it), type(itorig))
self.assertEqual(list(it), list(range(1, 7)))
# empty iterator
for i in range(1, 5):
next(itorig)
d = pickle.dumps((itorig, orig), proto)
it, seq = pickle.loads(d)
seq.n = 7
self.assertIs(type(it), type(itorig))
self.assertEqual(list(it), list(range(5, 7)))
# exhausted iterator
self.assertRaises(StopIteration, next, itorig)
d = pickle.dumps((itorig, orig), proto)
it, seq = pickle.loads(d)
seq.n = 7
self.assertTrue(isinstance(it, collections.abc.Iterator))
self.assertEqual(list(it), [])
def test_mutating_seq_class_exhausted_iter(self):
a = SequenceClass(5)
exhit = iter(a)
empit = iter(a)
for x in exhit: # exhaust the iterator
next(empit) # not exhausted
a.n = 7
self.assertEqual(list(exhit), [])
self.assertEqual(list(empit), [5, 6])
self.assertEqual(list(a), [0, 1, 2, 3, 4, 5, 6])
# Test a new_style class with __iter__ but no next() method
def test_new_style_iter_class(self):
class IterClass(object):
def __iter__(self):
return self
self.assertRaises(TypeError, iter, IterClass())
# Test two-argument iter() with callable instance
def test_iter_callable(self):
class C:
def __init__(self):
self.i = 0
def __call__(self):
i = self.i
self.i = i + 1
if i > 100:
raise IndexError # Emergency stop
return i
self.check_iterator(iter(C(), 10), list(range(10)), pickle=False)
# Test two-argument iter() with function
def test_iter_function(self):
def spam(state=[0]):
i = state[0]
state[0] = i+1
return i
self.check_iterator(iter(spam, 10), list(range(10)), pickle=False)
# Test two-argument iter() with function that raises StopIteration
def test_iter_function_stop(self):
def spam(state=[0]):
i = state[0]
if i == 10:
raise StopIteration
state[0] = i+1
return i
self.check_iterator(iter(spam, 20), list(range(10)), pickle=False)
# Test exception propagation through function iterator
def test_exception_function(self):
def spam(state=[0]):
i = state[0]
state[0] = i+1
if i == 10:
raise RuntimeError
return i
res = []
try:
for x in iter(spam, 20):
res.append(x)
except RuntimeError:
self.assertEqual(res, list(range(10)))
else:
self.fail("should have raised RuntimeError")
# Test exception propagation through sequence iterator
def test_exception_sequence(self):
class MySequenceClass(SequenceClass):
def __getitem__(self, i):
if i == 10:
raise RuntimeError
return SequenceClass.__getitem__(self, i)
res = []
try:
for x in MySequenceClass(20):
res.append(x)
except RuntimeError:
self.assertEqual(res, list(range(10)))
else:
self.fail("should have raised RuntimeError")
# Test for StopIteration from __getitem__
def test_stop_sequence(self):
class MySequenceClass(SequenceClass):
def __getitem__(self, i):
if i == 10:
raise StopIteration
return SequenceClass.__getitem__(self, i)
self.check_for_loop(MySequenceClass(20), list(range(10)), pickle=False)
# Test a big range
def test_iter_big_range(self):
self.check_for_loop(iter(range(10000)), list(range(10000)))
# Test an empty list
def test_iter_empty(self):
self.check_for_loop(iter([]), [])
# Test a tuple
def test_iter_tuple(self):
self.check_for_loop(iter((0,1,2,3,4,5,6,7,8,9)), list(range(10)))
# Test a range
def test_iter_range(self):
self.check_for_loop(iter(range(10)), list(range(10)))
# Test a string
def test_iter_string(self):
self.check_for_loop(iter("abcde"), ["a", "b", "c", "d", "e"])
# Test a directory
def test_iter_dict(self):
dict = {}
for i in range(10):
dict[i] = None
self.check_for_loop(dict, list(dict.keys()))
# Test a file
def test_iter_file(self):
f = open(TESTFN, "w")
try:
for i in range(5):
f.write("%d\n" % i)
finally:
f.close()
f = open(TESTFN, "r")
try:
self.check_for_loop(f, ["0\n", "1\n", "2\n", "3\n", "4\n"], pickle=False)
self.check_for_loop(f, [], pickle=False)
finally:
f.close()
try:
unlink(TESTFN)
except OSError:
pass
# Test list()'s use of iterators.
def test_builtin_list(self):
self.assertEqual(list(SequenceClass(5)), list(range(5)))
self.assertEqual(list(SequenceClass(0)), [])
self.assertEqual(list(()), [])
d = {"one": 1, "two": 2, "three": 3}
self.assertEqual(list(d), list(d.keys()))
self.assertRaises(TypeError, list, list)
self.assertRaises(TypeError, list, 42)
f = open(TESTFN, "w")
try:
for i in range(5):
f.write("%d\n" % i)
finally:
f.close()
f = open(TESTFN, "r")
try:
self.assertEqual(list(f), ["0\n", "1\n", "2\n", "3\n", "4\n"])
f.seek(0, 0)
self.assertEqual(list(f),
["0\n", "1\n", "2\n", "3\n", "4\n"])
finally:
f.close()
try:
unlink(TESTFN)
except OSError:
pass
# Test tuples()'s use of iterators.
def test_builtin_tuple(self):
self.assertEqual(tuple(SequenceClass(5)), (0, 1, 2, 3, 4))
self.assertEqual(tuple(SequenceClass(0)), ())
self.assertEqual(tuple([]), ())
self.assertEqual(tuple(()), ())
self.assertEqual(tuple("abc"), ("a", "b", "c"))
d = {"one": 1, "two": 2, "three": 3}
self.assertEqual(tuple(d), tuple(d.keys()))
self.assertRaises(TypeError, tuple, list)
self.assertRaises(TypeError, tuple, 42)
f = open(TESTFN, "w")
try:
for i in range(5):
f.write("%d\n" % i)
finally:
f.close()
f = open(TESTFN, "r")
try:
self.assertEqual(tuple(f), ("0\n", "1\n", "2\n", "3\n", "4\n"))
f.seek(0, 0)
self.assertEqual(tuple(f),
("0\n", "1\n", "2\n", "3\n", "4\n"))
finally:
f.close()
try:
unlink(TESTFN)
except OSError:
pass
# Test filter()'s use of iterators.
def test_builtin_filter(self):
self.assertEqual(list(filter(None, SequenceClass(5))),
list(range(1, 5)))
self.assertEqual(list(filter(None, SequenceClass(0))), [])
self.assertEqual(list(filter(None, ())), [])
self.assertEqual(list(filter(None, "abc")), ["a", "b", "c"])
d = {"one": 1, "two": 2, "three": 3}
self.assertEqual(list(filter(None, d)), list(d.keys()))
self.assertRaises(TypeError, filter, None, list)
self.assertRaises(TypeError, filter, None, 42)
class Boolean:
def __init__(self, truth):
self.truth = truth
def __bool__(self):
return self.truth
bTrue = Boolean(True)
bFalse = Boolean(False)
class Seq:
def __init__(self, *args):
self.vals = args
def __iter__(self):
class SeqIter:
def __init__(self, vals):
self.vals = vals
self.i = 0
def __iter__(self):
return self
def __next__(self):
i = self.i
self.i = i + 1
if i < len(self.vals):
return self.vals[i]
else:
raise StopIteration
return SeqIter(self.vals)
seq = Seq(*([bTrue, bFalse] * 25))
self.assertEqual(list(filter(lambda x: not x, seq)), [bFalse]*25)
self.assertEqual(list(filter(lambda x: not x, iter(seq))), [bFalse]*25)
# Test max() and min()'s use of iterators.
def test_builtin_max_min(self):
self.assertEqual(max(SequenceClass(5)), 4)
self.assertEqual(min(SequenceClass(5)), 0)
self.assertEqual(max(8, -1), 8)
self.assertEqual(min(8, -1), -1)
d = {"one": 1, "two": 2, "three": 3}
self.assertEqual(max(d), "two")
self.assertEqual(min(d), "one")
self.assertEqual(max(d.values()), 3)
self.assertEqual(min(iter(d.values())), 1)
f = open(TESTFN, "w")
try:
f.write("medium line\n")
f.write("xtra large line\n")
f.write("itty-bitty line\n")
finally:
f.close()
f = open(TESTFN, "r")
try:
self.assertEqual(min(f), "itty-bitty line\n")
f.seek(0, 0)
self.assertEqual(max(f), "xtra large line\n")
finally:
f.close()
try:
unlink(TESTFN)
except OSError:
pass
# Test map()'s use of iterators.
def test_builtin_map(self):
self.assertEqual(list(map(lambda x: x+1, SequenceClass(5))),
list(range(1, 6)))
d = {"one": 1, "two": 2, "three": 3}
self.assertEqual(list(map(lambda k, d=d: (k, d[k]), d)),
list(d.items()))
dkeys = list(d.keys())
expected = [(i < len(d) and dkeys[i] or None,
i,
i < len(d) and dkeys[i] or None)
for i in range(3)]
f = open(TESTFN, "w")
try:
for i in range(10):
f.write("xy" * i + "\n") # line i has len 2*i+1
finally:
f.close()
f = open(TESTFN, "r")
try:
self.assertEqual(list(map(len, f)), list(range(1, 21, 2)))
finally:
f.close()
try:
unlink(TESTFN)
except OSError:
pass
# Test zip()'s use of iterators.
def test_builtin_zip(self):
self.assertEqual(list(zip()), [])
self.assertEqual(list(zip(*[])), [])
self.assertEqual(list(zip(*[(1, 2), 'ab'])), [(1, 'a'), (2, 'b')])
self.assertRaises(TypeError, zip, None)
self.assertRaises(TypeError, zip, range(10), 42)
self.assertRaises(TypeError, zip, range(10), zip)
self.assertEqual(list(zip(IteratingSequenceClass(3))),
[(0,), (1,), (2,)])
self.assertEqual(list(zip(SequenceClass(3))),
[(0,), (1,), (2,)])
d = {"one": 1, "two": 2, "three": 3}
self.assertEqual(list(d.items()), list(zip(d, d.values())))
# Generate all ints starting at constructor arg.
class IntsFrom:
def __init__(self, start):
self.i = start
def __iter__(self):
return self
def __next__(self):
i = self.i
self.i = i+1
return i
f = open(TESTFN, "w")
try:
f.write("a\n" "bbb\n" "cc\n")
finally:
f.close()
f = open(TESTFN, "r")
try:
self.assertEqual(list(zip(IntsFrom(0), f, IntsFrom(-100))),
[(0, "a\n", -100),
(1, "bbb\n", -99),
(2, "cc\n", -98)])
finally:
f.close()
try:
unlink(TESTFN)
except OSError:
pass
self.assertEqual(list(zip(range(5))), [(i,) for i in range(5)])
# Classes that lie about their lengths.
class NoGuessLen5:
def __getitem__(self, i):
if i >= 5:
raise IndexError
return i
class Guess3Len5(NoGuessLen5):
def __len__(self):
return 3
class Guess30Len5(NoGuessLen5):
def __len__(self):
return 30
def lzip(*args):
return list(zip(*args))
self.assertEqual(len(Guess3Len5()), 3)
self.assertEqual(len(Guess30Len5()), 30)
self.assertEqual(lzip(NoGuessLen5()), lzip(range(5)))
self.assertEqual(lzip(Guess3Len5()), lzip(range(5)))
self.assertEqual(lzip(Guess30Len5()), lzip(range(5)))
expected = [(i, i) for i in range(5)]
for x in NoGuessLen5(), Guess3Len5(), Guess30Len5():
for y in NoGuessLen5(), Guess3Len5(), Guess30Len5():
self.assertEqual(lzip(x, y), expected)
def test_unicode_join_endcase(self):
# This class inserts a Unicode object into its argument's natural
# iteration, in the 3rd position.
class OhPhooey:
def __init__(self, seq):
self.it = iter(seq)
self.i = 0
def __iter__(self):
return self
def __next__(self):
i = self.i
self.i = i+1
if i == 2:
return "fooled you!"
return next(self.it)
f = open(TESTFN, "w")
try:
f.write("a\n" + "b\n" + "c\n")
finally:
f.close()
f = open(TESTFN, "r")
# Nasty: string.join(s) can't know whether unicode.join() is needed
# until it's seen all of s's elements. But in this case, f's
# iterator cannot be restarted. So what we're testing here is
# whether string.join() can manage to remember everything it's seen
# and pass that on to unicode.join().
try:
got = " - ".join(OhPhooey(f))
self.assertEqual(got, "a\n - b\n - fooled you! - c\n")
finally:
f.close()
try:
unlink(TESTFN)
except OSError:
pass
# Test iterators with 'x in y' and 'x not in y'.
def test_in_and_not_in(self):
for sc5 in IteratingSequenceClass(5), SequenceClass(5):
for i in range(5):
self.assertIn(i, sc5)
for i in "abc", -1, 5, 42.42, (3, 4), [], {1: 1}, 3-12j, sc5:
self.assertNotIn(i, sc5)
self.assertRaises(TypeError, lambda: 3 in 12)
self.assertRaises(TypeError, lambda: 3 not in map)
d = {"one": 1, "two": 2, "three": 3, 1j: 2j}
for k in d:
self.assertIn(k, d)
self.assertNotIn(k, d.values())
for v in d.values():
self.assertIn(v, d.values())
self.assertNotIn(v, d)
for k, v in d.items():
self.assertIn((k, v), d.items())
self.assertNotIn((v, k), d.items())
f = open(TESTFN, "w")
try:
f.write("a\n" "b\n" "c\n")
finally:
f.close()
f = open(TESTFN, "r")
try:
for chunk in "abc":
f.seek(0, 0)
self.assertNotIn(chunk, f)
f.seek(0, 0)
self.assertIn((chunk + "\n"), f)
finally:
f.close()
try:
unlink(TESTFN)
except OSError:
pass
# Test iterators with operator.countOf (PySequence_Count).
def test_countOf(self):
from operator import countOf
self.assertEqual(countOf([1,2,2,3,2,5], 2), 3)
self.assertEqual(countOf((1,2,2,3,2,5), 2), 3)
self.assertEqual(countOf("122325", "2"), 3)
self.assertEqual(countOf("122325", "6"), 0)
self.assertRaises(TypeError, countOf, 42, 1)
self.assertRaises(TypeError, countOf, countOf, countOf)
d = {"one": 3, "two": 3, "three": 3, 1j: 2j}
for k in d:
self.assertEqual(countOf(d, k), 1)
self.assertEqual(countOf(d.values(), 3), 3)
self.assertEqual(countOf(d.values(), 2j), 1)
self.assertEqual(countOf(d.values(), 1j), 0)
f = open(TESTFN, "w")
try:
f.write("a\n" "b\n" "c\n" "b\n")
finally:
f.close()
f = open(TESTFN, "r")
try:
for letter, count in ("a", 1), ("b", 2), ("c", 1), ("d", 0):
f.seek(0, 0)
self.assertEqual(countOf(f, letter + "\n"), count)
finally:
f.close()
try:
unlink(TESTFN)
except OSError:
pass
# Test iterators with operator.indexOf (PySequence_Index).
def test_indexOf(self):
from operator import indexOf
self.assertEqual(indexOf([1,2,2,3,2,5], 1), 0)
self.assertEqual(indexOf((1,2,2,3,2,5), 2), 1)
self.assertEqual(indexOf((1,2,2,3,2,5), 3), 3)
self.assertEqual(indexOf((1,2,2,3,2,5), 5), 5)
self.assertRaises(ValueError, indexOf, (1,2,2,3,2,5), 0)
self.assertRaises(ValueError, indexOf, (1,2,2,3,2,5), 6)
self.assertEqual(indexOf("122325", "2"), 1)
self.assertEqual(indexOf("122325", "5"), 5)
self.assertRaises(ValueError, indexOf, "122325", "6")
self.assertRaises(TypeError, indexOf, 42, 1)
self.assertRaises(TypeError, indexOf, indexOf, indexOf)
f = open(TESTFN, "w")
try:
f.write("a\n" "b\n" "c\n" "d\n" "e\n")
finally:
f.close()
f = open(TESTFN, "r")
try:
fiter = iter(f)
self.assertEqual(indexOf(fiter, "b\n"), 1)
self.assertEqual(indexOf(fiter, "d\n"), 1)
self.assertEqual(indexOf(fiter, "e\n"), 0)
self.assertRaises(ValueError, indexOf, fiter, "a\n")
finally:
f.close()
try:
unlink(TESTFN)
except OSError:
pass
iclass = IteratingSequenceClass(3)
for i in range(3):
self.assertEqual(indexOf(iclass, i), i)
self.assertRaises(ValueError, indexOf, iclass, -1)
# Test iterators with file.writelines().
def test_writelines(self):
f = open(TESTFN, "w")
try:
self.assertRaises(TypeError, f.writelines, None)
self.assertRaises(TypeError, f.writelines, 42)
f.writelines(["1\n", "2\n"])
f.writelines(("3\n", "4\n"))
f.writelines({'5\n': None})
f.writelines({})
# Try a big chunk too.
class Iterator:
def __init__(self, start, finish):
self.start = start
self.finish = finish
self.i = self.start
def __next__(self):
if self.i >= self.finish:
raise StopIteration
result = str(self.i) + '\n'
self.i += 1
return result
def __iter__(self):
return self
class Whatever:
def __init__(self, start, finish):
self.start = start
self.finish = finish
def __iter__(self):
return Iterator(self.start, self.finish)
f.writelines(Whatever(6, 6+2000))
f.close()
f = open(TESTFN)
expected = [str(i) + "\n" for i in range(1, 2006)]
self.assertEqual(list(f), expected)
finally:
f.close()
try:
unlink(TESTFN)
except OSError:
pass
# Test iterators on RHS of unpacking assignments.
def test_unpack_iter(self):
a, b = 1, 2
self.assertEqual((a, b), (1, 2))
a, b, c = IteratingSequenceClass(3)
self.assertEqual((a, b, c), (0, 1, 2))
try: # too many values
a, b = IteratingSequenceClass(3)
except ValueError:
pass
else:
self.fail("should have raised ValueError")
try: # not enough values
a, b, c = IteratingSequenceClass(2)
except ValueError:
pass
else:
self.fail("should have raised ValueError")
try: # not iterable
a, b, c = len
except TypeError:
pass
else:
self.fail("should have raised TypeError")
a, b, c = {1: 42, 2: 42, 3: 42}.values()
self.assertEqual((a, b, c), (42, 42, 42))
f = open(TESTFN, "w")
lines = ("a\n", "bb\n", "ccc\n")
try:
for line in lines:
f.write(line)
finally:
f.close()
f = open(TESTFN, "r")
try:
a, b, c = f
self.assertEqual((a, b, c), lines)
finally:
f.close()
try:
unlink(TESTFN)
except OSError:
pass
(a, b), (c,) = IteratingSequenceClass(2), {42: 24}
self.assertEqual((a, b, c), (0, 1, 42))
@cpython_only
def test_ref_counting_behavior(self):
class C(object):
count = 0
def __new__(cls):
cls.count += 1
return object.__new__(cls)
def __del__(self):
cls = self.__class__
assert cls.count > 0
cls.count -= 1
x = C()
self.assertEqual(C.count, 1)
del x
self.assertEqual(C.count, 0)
l = [C(), C(), C()]
self.assertEqual(C.count, 3)
try:
a, b = iter(l)
except ValueError:
pass
del l
self.assertEqual(C.count, 0)
# Make sure StopIteration is a "sink state".
# This tests various things that weren't sink states in Python 2.2.1,
# plus various things that always were fine.
def test_sinkstate_list(self):
# This used to fail
a = list(range(5))
b = iter(a)
self.assertEqual(list(b), list(range(5)))
a.extend(range(5, 10))
self.assertEqual(list(b), [])
def test_sinkstate_tuple(self):
a = (0, 1, 2, 3, 4)
b = iter(a)
self.assertEqual(list(b), list(range(5)))
self.assertEqual(list(b), [])
def test_sinkstate_string(self):
a = "abcde"
b = iter(a)
self.assertEqual(list(b), ['a', 'b', 'c', 'd', 'e'])
self.assertEqual(list(b), [])
def test_sinkstate_sequence(self):
# This used to fail
a = SequenceClass(5)
b = iter(a)
self.assertEqual(list(b), list(range(5)))
a.n = 10
self.assertEqual(list(b), [])
def test_sinkstate_callable(self):
# This used to fail
def spam(state=[0]):
i = state[0]
state[0] = i+1
if i == 10:
raise AssertionError("shouldn't have gotten this far")
return i
b = iter(spam, 5)
self.assertEqual(list(b), list(range(5)))
self.assertEqual(list(b), [])
def test_sinkstate_dict(self):
# XXX For a more thorough test, see towards the end of:
# http://mail.python.org/pipermail/python-dev/2002-July/026512.html
a = {1:1, 2:2, 0:0, 4:4, 3:3}
for b in iter(a), a.keys(), a.items(), a.values():
b = iter(a)
self.assertEqual(len(list(b)), 5)
self.assertEqual(list(b), [])
def test_sinkstate_yield(self):
def gen():
for i in range(5):
yield i
b = gen()
self.assertEqual(list(b), list(range(5)))
self.assertEqual(list(b), [])
def test_sinkstate_range(self):
a = range(5)
b = iter(a)
self.assertEqual(list(b), list(range(5)))
self.assertEqual(list(b), [])
def test_sinkstate_enumerate(self):
a = range(5)
e = enumerate(a)
b = iter(e)
self.assertEqual(list(b), list(zip(range(5), range(5))))
self.assertEqual(list(b), [])
def test_3720(self):
# Avoid a crash, when an iterator deletes its next() method.
class BadIterator(object):
def __iter__(self):
return self
def __next__(self):
del BadIterator.__next__
return 1
try:
for i in BadIterator() :
pass
except TypeError:
pass
def test_extending_list_with_iterator_does_not_segfault(self):
# The code to extend a list with an iterator has a fair
# amount of nontrivial logic in terms of guessing how
# much memory to allocate in advance, "stealing" refs,
# and then shrinking at the end. This is a basic smoke
# test for that scenario.
def gen():
for i in range(500):
yield i
lst = [0] * 500
for i in range(240):
lst.pop(0)
lst.extend(gen())
self.assertEqual(len(lst), 760)
@cpython_only
def test_iter_overflow(self):
# Test for the issue 22939
it = iter(UnlimitedSequenceClass())
# Manually set `it_index` to PY_SSIZE_T_MAX-2 without a loop
it.__setstate__(sys.maxsize - 2)
self.assertEqual(next(it), sys.maxsize - 2)
self.assertEqual(next(it), sys.maxsize - 1)
with self.assertRaises(OverflowError):
next(it)
# Check that Overflow error is always raised
with self.assertRaises(OverflowError):
next(it)
def test_iter_neg_setstate(self):
it = iter(UnlimitedSequenceClass())
it.__setstate__(-42)
self.assertEqual(next(it), 0)
self.assertEqual(next(it), 1)
def test_free_after_iterating(self):
check_free_after_iterating(self, iter, SequenceClass, (0,))
def test_error_iter(self):
for typ in (DefaultIterClass, NoIterClass):
self.assertRaises(TypeError, iter, typ())
def test_main():
run_unittest(TestCase)
if __name__ == "__main__":
test_main()
| 32,264 | 1,017 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_zipfile64.py | # Tests of the full ZIP64 functionality of zipfile
# The support.requires call is the only reason for keeping this separate
# from test_zipfile
from test import support
# XXX(nnorwitz): disable this test by looking for extralargefile resource,
# which doesn't exist. This test takes over 30 minutes to run in general
# and requires more disk space than most of the buildbots.
support.requires(
'extralargefile',
'test requires loads of disk-space bytes and a long time to run'
)
import zipfile, os, unittest
import time
import sys
from io import StringIO
from tempfile import TemporaryFile
from test.support import TESTFN, requires_zlib
TESTFN2 = TESTFN + "2"
# How much time in seconds can pass before we print a 'Still working' message.
_PRINT_WORKING_MSG_INTERVAL = 5 * 60
class TestsWithSourceFile(unittest.TestCase):
def setUp(self):
# Create test data.
line_gen = ("Test of zipfile line %d." % i for i in range(1000000))
self.data = '\n'.join(line_gen).encode('ascii')
# And write it to a file.
fp = open(TESTFN, "wb")
fp.write(self.data)
fp.close()
def zipTest(self, f, compression):
# Create the ZIP archive.
zipfp = zipfile.ZipFile(f, "w", compression)
# It will contain enough copies of self.data to reach about 6GB of
# raw data to store.
filecount = 6*1024**3 // len(self.data)
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
for num in range(filecount):
zipfp.writestr("testfn%d" % num, self.data)
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
print((
' zipTest still writing %d of %d, be patient...' %
(num, filecount)), file=sys.__stdout__)
sys.__stdout__.flush()
zipfp.close()
# Read the ZIP archive
zipfp = zipfile.ZipFile(f, "r", compression)
for num in range(filecount):
self.assertEqual(zipfp.read("testfn%d" % num), self.data)
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
print((
' zipTest still reading %d of %d, be patient...' %
(num, filecount)), file=sys.__stdout__)
sys.__stdout__.flush()
zipfp.close()
def testStored(self):
# Try the temp file first. If we do TESTFN2 first, then it hogs
# gigabytes of disk space for the duration of the test.
with TemporaryFile() as f:
self.zipTest(f, zipfile.ZIP_STORED)
self.assertFalse(f.closed)
self.zipTest(TESTFN2, zipfile.ZIP_STORED)
@requires_zlib
def testDeflated(self):
# Try the temp file first. If we do TESTFN2 first, then it hogs
# gigabytes of disk space for the duration of the test.
with TemporaryFile() as f:
self.zipTest(f, zipfile.ZIP_DEFLATED)
self.assertFalse(f.closed)
self.zipTest(TESTFN2, zipfile.ZIP_DEFLATED)
def tearDown(self):
for fname in TESTFN, TESTFN2:
if os.path.exists(fname):
os.remove(fname)
class OtherTests(unittest.TestCase):
def testMoreThan64kFiles(self):
# This test checks that more than 64k files can be added to an archive,
# and that the resulting archive can be read properly by ZipFile
zipf = zipfile.ZipFile(TESTFN, mode="w", allowZip64=True)
zipf.debug = 100
numfiles = (1 << 16) * 3//2
for i in range(numfiles):
zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
self.assertEqual(len(zipf.namelist()), numfiles)
zipf.close()
zipf2 = zipfile.ZipFile(TESTFN, mode="r")
self.assertEqual(len(zipf2.namelist()), numfiles)
for i in range(numfiles):
content = zipf2.read("foo%08d" % i).decode('ascii')
self.assertEqual(content, "%d" % (i**3 % 57))
zipf2.close()
def testMoreThan64kFilesAppend(self):
zipf = zipfile.ZipFile(TESTFN, mode="w", allowZip64=False)
zipf.debug = 100
numfiles = (1 << 16) - 1
for i in range(numfiles):
zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
self.assertEqual(len(zipf.namelist()), numfiles)
with self.assertRaises(zipfile.LargeZipFile):
zipf.writestr("foo%08d" % numfiles, b'')
self.assertEqual(len(zipf.namelist()), numfiles)
zipf.close()
zipf = zipfile.ZipFile(TESTFN, mode="a", allowZip64=False)
zipf.debug = 100
self.assertEqual(len(zipf.namelist()), numfiles)
with self.assertRaises(zipfile.LargeZipFile):
zipf.writestr("foo%08d" % numfiles, b'')
self.assertEqual(len(zipf.namelist()), numfiles)
zipf.close()
zipf = zipfile.ZipFile(TESTFN, mode="a", allowZip64=True)
zipf.debug = 100
self.assertEqual(len(zipf.namelist()), numfiles)
numfiles2 = (1 << 16) * 3//2
for i in range(numfiles, numfiles2):
zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
self.assertEqual(len(zipf.namelist()), numfiles2)
zipf.close()
zipf2 = zipfile.ZipFile(TESTFN, mode="r")
self.assertEqual(len(zipf2.namelist()), numfiles2)
for i in range(numfiles2):
content = zipf2.read("foo%08d" % i).decode('ascii')
self.assertEqual(content, "%d" % (i**3 % 57))
zipf2.close()
def tearDown(self):
support.unlink(TESTFN)
support.unlink(TESTFN2)
if __name__ == "__main__":
unittest.main()
| 5,861 | 156 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_pprint.py | # -*- coding: utf-8 -*-
import collections
import io
import itertools
import pprint
import random
import test.support
import test.test_set
import types
import unittest
# list, tuple and dict subclasses that do or don't overwrite __repr__
class list2(list):
pass
class list3(list):
def __repr__(self):
return list.__repr__(self)
class tuple2(tuple):
pass
class tuple3(tuple):
def __repr__(self):
return tuple.__repr__(self)
class set2(set):
pass
class set3(set):
def __repr__(self):
return set.__repr__(self)
class frozenset2(frozenset):
pass
class frozenset3(frozenset):
def __repr__(self):
return frozenset.__repr__(self)
class dict2(dict):
pass
class dict3(dict):
def __repr__(self):
return dict.__repr__(self)
class Unorderable:
def __repr__(self):
return str(id(self))
# Class Orderable is orderable with any type
class Orderable:
def __init__(self, hash):
self._hash = hash
def __lt__(self, other):
return False
def __gt__(self, other):
return self != other
def __le__(self, other):
return self == other
def __ge__(self, other):
return True
def __eq__(self, other):
return self is other
def __ne__(self, other):
return self is not other
def __hash__(self):
return self._hash
class QueryTestCase(unittest.TestCase):
def setUp(self):
self.a = list(range(100))
self.b = list(range(200))
self.a[-12] = self.b
def test_init(self):
pp = pprint.PrettyPrinter()
pp = pprint.PrettyPrinter(indent=4, width=40, depth=5,
stream=io.StringIO(), compact=True)
pp = pprint.PrettyPrinter(4, 40, 5, io.StringIO())
with self.assertRaises(TypeError):
pp = pprint.PrettyPrinter(4, 40, 5, io.StringIO(), True)
self.assertRaises(ValueError, pprint.PrettyPrinter, indent=-1)
self.assertRaises(ValueError, pprint.PrettyPrinter, depth=0)
self.assertRaises(ValueError, pprint.PrettyPrinter, depth=-1)
self.assertRaises(ValueError, pprint.PrettyPrinter, width=0)
def test_basic(self):
# Verify .isrecursive() and .isreadable() w/o recursion
pp = pprint.PrettyPrinter()
for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, b"def",
bytearray(b"ghi"), True, False, None, ...,
self.a, self.b):
# module-level convenience functions
self.assertFalse(pprint.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pprint.isreadable(safe),
"expected isreadable for %r" % (safe,))
# PrettyPrinter methods
self.assertFalse(pp.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pp.isreadable(safe),
"expected isreadable for %r" % (safe,))
def test_knotted(self):
# Verify .isrecursive() and .isreadable() w/ recursion
# Tie a knot.
self.b[67] = self.a
# Messy dict.
self.d = {}
self.d[0] = self.d[1] = self.d[2] = self.d
pp = pprint.PrettyPrinter()
for icky in self.a, self.b, self.d, (self.d, self.d):
self.assertTrue(pprint.isrecursive(icky), "expected isrecursive")
self.assertFalse(pprint.isreadable(icky), "expected not isreadable")
self.assertTrue(pp.isrecursive(icky), "expected isrecursive")
self.assertFalse(pp.isreadable(icky), "expected not isreadable")
# Break the cycles.
self.d.clear()
del self.a[:]
del self.b[:]
for safe in self.a, self.b, self.d, (self.d, self.d):
# module-level convenience functions
self.assertFalse(pprint.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pprint.isreadable(safe),
"expected isreadable for %r" % (safe,))
# PrettyPrinter methods
self.assertFalse(pp.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pp.isreadable(safe),
"expected isreadable for %r" % (safe,))
def test_unreadable(self):
# Not recursive but not readable anyway
pp = pprint.PrettyPrinter()
for unreadable in type(3), pprint, pprint.isrecursive:
# module-level convenience functions
self.assertFalse(pprint.isrecursive(unreadable),
"expected not isrecursive for %r" % (unreadable,))
self.assertFalse(pprint.isreadable(unreadable),
"expected not isreadable for %r" % (unreadable,))
# PrettyPrinter methods
self.assertFalse(pp.isrecursive(unreadable),
"expected not isrecursive for %r" % (unreadable,))
self.assertFalse(pp.isreadable(unreadable),
"expected not isreadable for %r" % (unreadable,))
def test_same_as_repr(self):
# Simple objects, small containers and classes that overwrite __repr__
# For those the result should be the same as repr().
# Ahem. The docs don't say anything about that -- this appears to
# be testing an implementation quirk. Starting in Python 2.5, it's
# not true for dicts: pprint always sorts dicts by key now; before,
# it sorted a dict display if and only if the display required
# multiple lines. For that reason, dicts with more than one element
# aren't tested here.
for simple in (0, 0, 0+0j, 0.0, "", b"", bytearray(),
(), tuple2(), tuple3(),
[], list2(), list3(),
set(), set2(), set3(),
frozenset(), frozenset2(), frozenset3(),
{}, dict2(), dict3(),
self.assertTrue, pprint,
-6, -6, -6-6j, -1.5, "x", b"x", bytearray(b"x"),
(3,), [3], {3: 6},
(1,2), [3,4], {5: 6},
tuple2((1,2)), tuple3((1,2)), tuple3(range(100)),
[3,4], list2([3,4]), list3([3,4]), list3(range(100)),
set({7}), set2({7}), set3({7}),
frozenset({8}), frozenset2({8}), frozenset3({8}),
dict2({5: 6}), dict3({5: 6}),
range(10, -11, -1),
True, False, None, ...,
):
native = repr(simple)
self.assertEqual(pprint.pformat(simple), native)
self.assertEqual(pprint.pformat(simple, width=1, indent=0)
.replace('\n', ' '), native)
self.assertEqual(pprint.saferepr(simple), native)
def test_basic_line_wrap(self):
# verify basic line-wrapping operation
o = {'RPM_cal': 0,
'RPM_cal2': 48059,
'Speed_cal': 0,
'controldesk_runtime_us': 0,
'main_code_runtime_us': 0,
'read_io_runtime_us': 0,
'write_io_runtime_us': 43690}
exp = """\
{'RPM_cal': 0,
'RPM_cal2': 48059,
'Speed_cal': 0,
'controldesk_runtime_us': 0,
'main_code_runtime_us': 0,
'read_io_runtime_us': 0,
'write_io_runtime_us': 43690}"""
for type in [dict, dict2]:
self.assertEqual(pprint.pformat(type(o)), exp)
o = range(100)
exp = '[%s]' % ',\n '.join(map(str, o))
for type in [list, list2]:
self.assertEqual(pprint.pformat(type(o)), exp)
o = tuple(range(100))
exp = '(%s)' % ',\n '.join(map(str, o))
for type in [tuple, tuple2]:
self.assertEqual(pprint.pformat(type(o)), exp)
# indent parameter
o = range(100)
exp = '[ %s]' % ',\n '.join(map(str, o))
for type in [list, list2]:
self.assertEqual(pprint.pformat(type(o), indent=4), exp)
def test_nested_indentations(self):
o1 = list(range(10))
o2 = dict(first=1, second=2, third=3)
o = [o1, o2]
expected = """\
[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
{'first': 1, 'second': 2, 'third': 3}]"""
self.assertEqual(pprint.pformat(o, indent=4, width=42), expected)
expected = """\
[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
{ 'first': 1,
'second': 2,
'third': 3}]"""
self.assertEqual(pprint.pformat(o, indent=4, width=41), expected)
def test_width(self):
expected = """\
[[[[[[1, 2, 3],
'1 2']]]],
{1: [1, 2, 3],
2: [12, 34]},
'abc def ghi',
('ab cd ef',),
set2({1, 23}),
[[[[[1, 2, 3],
'1 2']]]]]"""
o = eval(expected)
self.assertEqual(pprint.pformat(o, width=15), expected)
self.assertEqual(pprint.pformat(o, width=16), expected)
self.assertEqual(pprint.pformat(o, width=25), expected)
self.assertEqual(pprint.pformat(o, width=14), """\
[[[[[[1,
2,
3],
'1 '
'2']]]],
{1: [1,
2,
3],
2: [12,
34]},
'abc def '
'ghi',
('ab cd '
'ef',),
set2({1,
23}),
[[[[[1,
2,
3],
'1 '
'2']]]]]""")
def test_sorted_dict(self):
# Starting in Python 2.5, pprint sorts dict displays by key regardless
# of how small the dictionary may be.
# Before the change, on 32-bit Windows pformat() gave order
# 'a', 'c', 'b' here, so this test failed.
d = {'a': 1, 'b': 1, 'c': 1}
self.assertEqual(pprint.pformat(d), "{'a': 1, 'b': 1, 'c': 1}")
self.assertEqual(pprint.pformat([d, d]),
"[{'a': 1, 'b': 1, 'c': 1}, {'a': 1, 'b': 1, 'c': 1}]")
# The next one is kind of goofy. The sorted order depends on the
# alphabetic order of type names: "int" < "str" < "tuple". Before
# Python 2.5, this was in the test_same_as_repr() test. It's worth
# keeping around for now because it's one of few tests of pprint
# against a crazy mix of types.
self.assertEqual(pprint.pformat({"xy\tab\n": (3,), 5: [[]], (): {}}),
r"{5: [[]], 'xy\tab\n': (3,), (): {}}")
def test_ordered_dict(self):
d = collections.OrderedDict()
self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()')
d = collections.OrderedDict([])
self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()')
words = 'the quick brown fox jumped over a lazy dog'.split()
d = collections.OrderedDict(zip(words, itertools.count()))
self.assertEqual(pprint.pformat(d),
"""\
OrderedDict([('the', 0),
('quick', 1),
('brown', 2),
('fox', 3),
('jumped', 4),
('over', 5),
('a', 6),
('lazy', 7),
('dog', 8)])""")
def test_mapping_proxy(self):
words = 'the quick brown fox jumped over a lazy dog'.split()
d = dict(zip(words, itertools.count()))
m = types.MappingProxyType(d)
self.assertEqual(pprint.pformat(m), """\
mappingproxy({'a': 6,
'brown': 2,
'dog': 8,
'fox': 3,
'jumped': 4,
'lazy': 7,
'over': 5,
'quick': 1,
'the': 0})""")
d = collections.OrderedDict(zip(words, itertools.count()))
m = types.MappingProxyType(d)
self.assertEqual(pprint.pformat(m), """\
mappingproxy(OrderedDict([('the', 0),
('quick', 1),
('brown', 2),
('fox', 3),
('jumped', 4),
('over', 5),
('a', 6),
('lazy', 7),
('dog', 8)]))""")
def test_subclassing(self):
o = {'names with spaces': 'should be presented using repr()',
'others.should.not.be': 'like.this'}
exp = """\
{'names with spaces': 'should be presented using repr()',
others.should.not.be: like.this}"""
self.assertEqual(DottedPrettyPrinter().pformat(o), exp)
def test_set_reprs(self):
self.assertEqual(pprint.pformat(set()), 'set()')
self.assertEqual(pprint.pformat(set(range(3))), '{0, 1, 2}')
self.assertEqual(pprint.pformat(set(range(7)), width=20), '''\
{0,
1,
2,
3,
4,
5,
6}''')
self.assertEqual(pprint.pformat(set2(range(7)), width=20), '''\
set2({0,
1,
2,
3,
4,
5,
6})''')
self.assertEqual(pprint.pformat(set3(range(7)), width=20),
'set3({0, 1, 2, 3, 4, 5, 6})')
self.assertEqual(pprint.pformat(frozenset()), 'frozenset()')
self.assertEqual(pprint.pformat(frozenset(range(3))),
'frozenset({0, 1, 2})')
self.assertEqual(pprint.pformat(frozenset(range(7)), width=20), '''\
frozenset({0,
1,
2,
3,
4,
5,
6})''')
self.assertEqual(pprint.pformat(frozenset2(range(7)), width=20), '''\
frozenset2({0,
1,
2,
3,
4,
5,
6})''')
self.assertEqual(pprint.pformat(frozenset3(range(7)), width=20),
'frozenset3({0, 1, 2, 3, 4, 5, 6})')
@unittest.expectedFailure
#See http://bugs.python.org/issue13907
@test.support.cpython_only
def test_set_of_sets_reprs(self):
# This test creates a complex arrangement of frozensets and
# compares the pretty-printed repr against a string hard-coded in
# the test. The hard-coded repr depends on the sort order of
# frozensets.
#
# However, as the docs point out: "Since sets only define
# partial ordering (subset relationships), the output of the
# list.sort() method is undefined for lists of sets."
#
# In a nutshell, the test assumes frozenset({0}) will always
# sort before frozenset({1}), but:
#
# >>> frozenset({0}) < frozenset({1})
# False
# >>> frozenset({1}) < frozenset({0})
# False
#
# Consequently, this test is fragile and
# implementation-dependent. Small changes to Python's sort
# algorithm cause the test to fail when it should pass.
# XXX Or changes to the dictionary implmentation...
cube_repr_tgt = """\
{frozenset(): frozenset({frozenset({2}), frozenset({0}), frozenset({1})}),
frozenset({0}): frozenset({frozenset(),
frozenset({0, 2}),
frozenset({0, 1})}),
frozenset({1}): frozenset({frozenset(),
frozenset({1, 2}),
frozenset({0, 1})}),
frozenset({2}): frozenset({frozenset(),
frozenset({1, 2}),
frozenset({0, 2})}),
frozenset({1, 2}): frozenset({frozenset({2}),
frozenset({1}),
frozenset({0, 1, 2})}),
frozenset({0, 2}): frozenset({frozenset({2}),
frozenset({0}),
frozenset({0, 1, 2})}),
frozenset({0, 1}): frozenset({frozenset({0}),
frozenset({1}),
frozenset({0, 1, 2})}),
frozenset({0, 1, 2}): frozenset({frozenset({1, 2}),
frozenset({0, 2}),
frozenset({0, 1})})}"""
cube = test.test_set.cube(3)
self.assertEqual(pprint.pformat(cube), cube_repr_tgt)
cubo_repr_tgt = """\
{frozenset({frozenset({0, 2}), frozenset({0})}): frozenset({frozenset({frozenset({0,
2}),
frozenset({0,
1,
2})}),
frozenset({frozenset({0}),
frozenset({0,
1})}),
frozenset({frozenset(),
frozenset({0})}),
frozenset({frozenset({2}),
frozenset({0,
2})})}),
frozenset({frozenset({0, 1}), frozenset({1})}): frozenset({frozenset({frozenset({0,
1}),
frozenset({0,
1,
2})}),
frozenset({frozenset({0}),
frozenset({0,
1})}),
frozenset({frozenset({1}),
frozenset({1,
2})}),
frozenset({frozenset(),
frozenset({1})})}),
frozenset({frozenset({1, 2}), frozenset({1})}): frozenset({frozenset({frozenset({1,
2}),
frozenset({0,
1,
2})}),
frozenset({frozenset({2}),
frozenset({1,
2})}),
frozenset({frozenset(),
frozenset({1})}),
frozenset({frozenset({1}),
frozenset({0,
1})})}),
frozenset({frozenset({1, 2}), frozenset({2})}): frozenset({frozenset({frozenset({1,
2}),
frozenset({0,
1,
2})}),
frozenset({frozenset({1}),
frozenset({1,
2})}),
frozenset({frozenset({2}),
frozenset({0,
2})}),
frozenset({frozenset(),
frozenset({2})})}),
frozenset({frozenset(), frozenset({0})}): frozenset({frozenset({frozenset({0}),
frozenset({0,
1})}),
frozenset({frozenset({0}),
frozenset({0,
2})}),
frozenset({frozenset(),
frozenset({1})}),
frozenset({frozenset(),
frozenset({2})})}),
frozenset({frozenset(), frozenset({1})}): frozenset({frozenset({frozenset(),
frozenset({0})}),
frozenset({frozenset({1}),
frozenset({1,
2})}),
frozenset({frozenset(),
frozenset({2})}),
frozenset({frozenset({1}),
frozenset({0,
1})})}),
frozenset({frozenset({2}), frozenset()}): frozenset({frozenset({frozenset({2}),
frozenset({1,
2})}),
frozenset({frozenset(),
frozenset({0})}),
frozenset({frozenset(),
frozenset({1})}),
frozenset({frozenset({2}),
frozenset({0,
2})})}),
frozenset({frozenset({0, 1, 2}), frozenset({0, 1})}): frozenset({frozenset({frozenset({1,
2}),
frozenset({0,
1,
2})}),
frozenset({frozenset({0,
2}),
frozenset({0,
1,
2})}),
frozenset({frozenset({0}),
frozenset({0,
1})}),
frozenset({frozenset({1}),
frozenset({0,
1})})}),
frozenset({frozenset({0}), frozenset({0, 1})}): frozenset({frozenset({frozenset(),
frozenset({0})}),
frozenset({frozenset({0,
1}),
frozenset({0,
1,
2})}),
frozenset({frozenset({0}),
frozenset({0,
2})}),
frozenset({frozenset({1}),
frozenset({0,
1})})}),
frozenset({frozenset({2}), frozenset({0, 2})}): frozenset({frozenset({frozenset({0,
2}),
frozenset({0,
1,
2})}),
frozenset({frozenset({2}),
frozenset({1,
2})}),
frozenset({frozenset({0}),
frozenset({0,
2})}),
frozenset({frozenset(),
frozenset({2})})}),
frozenset({frozenset({0, 1, 2}), frozenset({0, 2})}): frozenset({frozenset({frozenset({1,
2}),
frozenset({0,
1,
2})}),
frozenset({frozenset({0,
1}),
frozenset({0,
1,
2})}),
frozenset({frozenset({0}),
frozenset({0,
2})}),
frozenset({frozenset({2}),
frozenset({0,
2})})}),
frozenset({frozenset({1, 2}), frozenset({0, 1, 2})}): frozenset({frozenset({frozenset({0,
2}),
frozenset({0,
1,
2})}),
frozenset({frozenset({0,
1}),
frozenset({0,
1,
2})}),
frozenset({frozenset({2}),
frozenset({1,
2})}),
frozenset({frozenset({1}),
frozenset({1,
2})})})}"""
cubo = test.test_set.linegraph(cube)
self.assertEqual(pprint.pformat(cubo), cubo_repr_tgt)
def test_depth(self):
nested_tuple = (1, (2, (3, (4, (5, 6)))))
nested_dict = {1: {2: {3: {4: {5: {6: 6}}}}}}
nested_list = [1, [2, [3, [4, [5, [6, []]]]]]]
self.assertEqual(pprint.pformat(nested_tuple), repr(nested_tuple))
self.assertEqual(pprint.pformat(nested_dict), repr(nested_dict))
self.assertEqual(pprint.pformat(nested_list), repr(nested_list))
lv1_tuple = '(1, (...))'
lv1_dict = '{1: {...}}'
lv1_list = '[1, [...]]'
self.assertEqual(pprint.pformat(nested_tuple, depth=1), lv1_tuple)
self.assertEqual(pprint.pformat(nested_dict, depth=1), lv1_dict)
self.assertEqual(pprint.pformat(nested_list, depth=1), lv1_list)
def test_sort_unorderable_values(self):
# Issue 3976: sorted pprints fail for unorderable values.
n = 20
keys = [Unorderable() for i in range(n)]
random.shuffle(keys)
skeys = sorted(keys, key=id)
clean = lambda s: s.replace(' ', '').replace('\n','')
self.assertEqual(clean(pprint.pformat(set(keys))),
'{' + ','.join(map(repr, skeys)) + '}')
self.assertEqual(clean(pprint.pformat(frozenset(keys))),
'frozenset({' + ','.join(map(repr, skeys)) + '})')
self.assertEqual(clean(pprint.pformat(dict.fromkeys(keys))),
'{' + ','.join('%r:None' % k for k in skeys) + '}')
# Issue 10017: TypeError on user-defined types as dict keys.
self.assertEqual(pprint.pformat({Unorderable: 0, 1: 0}),
'{1: 0, ' + repr(Unorderable) +': 0}')
# Issue 14998: TypeError on tuples with NoneTypes as dict keys.
keys = [(1,), (None,)]
self.assertEqual(pprint.pformat(dict.fromkeys(keys, 0)),
'{%r: 0, %r: 0}' % tuple(sorted(keys, key=id)))
def test_sort_orderable_and_unorderable_values(self):
# Issue 22721: sorted pprints is not stable
a = Unorderable()
b = Orderable(hash(a)) # should have the same hash value
# self-test
self.assertLess(a, b)
self.assertLess(str(type(b)), str(type(a)))
self.assertEqual(sorted([b, a]), [a, b])
self.assertEqual(sorted([a, b]), [a, b])
# set
self.assertEqual(pprint.pformat(set([b, a]), width=1),
'{%r,\n %r}' % (a, b))
self.assertEqual(pprint.pformat(set([a, b]), width=1),
'{%r,\n %r}' % (a, b))
# dict
self.assertEqual(pprint.pformat(dict.fromkeys([b, a]), width=1),
'{%r: None,\n %r: None}' % (a, b))
self.assertEqual(pprint.pformat(dict.fromkeys([a, b]), width=1),
'{%r: None,\n %r: None}' % (a, b))
def test_str_wrap(self):
# pprint tries to wrap strings intelligently
fox = 'the quick brown fox jumped over a lazy dog'
self.assertEqual(pprint.pformat(fox, width=19), """\
('the quick brown '
'fox jumped over '
'a lazy dog')""")
self.assertEqual(pprint.pformat({'a': 1, 'b': fox, 'c': 2},
width=25), """\
{'a': 1,
'b': 'the quick brown '
'fox jumped over '
'a lazy dog',
'c': 2}""")
# With some special characters
# - \n always triggers a new line in the pprint
# - \t and \n are escaped
# - non-ASCII is allowed
# - an apostrophe doesn't disrupt the pprint
special = "Portons dix bons \"whiskys\"\nà l'avocat goujat\t qui fumait au zoo"
self.assertEqual(pprint.pformat(special, width=68), repr(special))
self.assertEqual(pprint.pformat(special, width=31), """\
('Portons dix bons "whiskys"\\n'
"Ã l'avocat goujat\\t qui "
'fumait au zoo')""")
self.assertEqual(pprint.pformat(special, width=20), """\
('Portons dix bons '
'"whiskys"\\n'
"Ã l'avocat "
'goujat\\t qui '
'fumait au zoo')""")
self.assertEqual(pprint.pformat([[[[[special]]]]], width=35), """\
[[[[['Portons dix bons "whiskys"\\n'
"Ã l'avocat goujat\\t qui "
'fumait au zoo']]]]]""")
self.assertEqual(pprint.pformat([[[[[special]]]]], width=25), """\
[[[[['Portons dix bons '
'"whiskys"\\n'
"Ã l'avocat "
'goujat\\t qui '
'fumait au zoo']]]]]""")
self.assertEqual(pprint.pformat([[[[[special]]]]], width=23), """\
[[[[['Portons dix '
'bons "whiskys"\\n'
"Ã l'avocat "
'goujat\\t qui '
'fumait au '
'zoo']]]]]""")
# An unwrappable string is formatted as its repr
unwrappable = "x" * 100
self.assertEqual(pprint.pformat(unwrappable, width=80), repr(unwrappable))
self.assertEqual(pprint.pformat(''), "''")
# Check that the pprint is a usable repr
special *= 10
for width in range(3, 40):
formatted = pprint.pformat(special, width=width)
self.assertEqual(eval(formatted), special)
formatted = pprint.pformat([special] * 2, width=width)
self.assertEqual(eval(formatted), [special] * 2)
def test_compact(self):
o = ([list(range(i * i)) for i in range(5)] +
[list(range(i)) for i in range(6)])
expected = """\
[[], [0], [0, 1, 2, 3],
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15],
[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3],
[0, 1, 2, 3, 4]]"""
self.assertEqual(pprint.pformat(o, width=47, compact=True), expected)
def test_compact_width(self):
levels = 20
number = 10
o = [0] * number
for i in range(levels - 1):
o = [o]
for w in range(levels * 2 + 1, levels + 3 * number - 1):
lines = pprint.pformat(o, width=w, compact=True).splitlines()
maxwidth = max(map(len, lines))
self.assertLessEqual(maxwidth, w)
self.assertGreater(maxwidth, w - 3)
def test_bytes_wrap(self):
self.assertEqual(pprint.pformat(b'', width=1), "b''")
self.assertEqual(pprint.pformat(b'abcd', width=1), "b'abcd'")
letters = b'abcdefghijklmnopqrstuvwxyz'
self.assertEqual(pprint.pformat(letters, width=29), repr(letters))
self.assertEqual(pprint.pformat(letters, width=19), """\
(b'abcdefghijkl'
b'mnopqrstuvwxyz')""")
self.assertEqual(pprint.pformat(letters, width=18), """\
(b'abcdefghijkl'
b'mnopqrstuvwx'
b'yz')""")
self.assertEqual(pprint.pformat(letters, width=16), """\
(b'abcdefghijkl'
b'mnopqrstuvwx'
b'yz')""")
special = bytes(range(16))
self.assertEqual(pprint.pformat(special, width=61), repr(special))
self.assertEqual(pprint.pformat(special, width=48), """\
(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
b'\\x0c\\r\\x0e\\x0f')""")
self.assertEqual(pprint.pformat(special, width=32), """\
(b'\\x00\\x01\\x02\\x03'
b'\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
b'\\x0c\\r\\x0e\\x0f')""")
self.assertEqual(pprint.pformat(special, width=1), """\
(b'\\x00\\x01\\x02\\x03'
b'\\x04\\x05\\x06\\x07'
b'\\x08\\t\\n\\x0b'
b'\\x0c\\r\\x0e\\x0f')""")
self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
width=21), """\
{'a': 1,
'b': b'abcdefghijkl'
b'mnopqrstuvwx'
b'yz',
'c': 2}""")
self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
width=20), """\
{'a': 1,
'b': b'abcdefgh'
b'ijklmnop'
b'qrstuvwxyz',
'c': 2}""")
self.assertEqual(pprint.pformat([[[[[[letters]]]]]], width=25), """\
[[[[[[b'abcdefghijklmnop'
b'qrstuvwxyz']]]]]]""")
self.assertEqual(pprint.pformat([[[[[[special]]]]]], width=41), """\
[[[[[[b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'
b'\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f']]]]]]""")
# Check that the pprint is a usable repr
for width in range(1, 64):
formatted = pprint.pformat(special, width=width)
self.assertEqual(eval(formatted), special)
formatted = pprint.pformat([special] * 2, width=width)
self.assertEqual(eval(formatted), [special] * 2)
def test_bytearray_wrap(self):
self.assertEqual(pprint.pformat(bytearray(), width=1), "bytearray(b'')")
letters = bytearray(b'abcdefghijklmnopqrstuvwxyz')
self.assertEqual(pprint.pformat(letters, width=40), repr(letters))
self.assertEqual(pprint.pformat(letters, width=28), """\
bytearray(b'abcdefghijkl'
b'mnopqrstuvwxyz')""")
self.assertEqual(pprint.pformat(letters, width=27), """\
bytearray(b'abcdefghijkl'
b'mnopqrstuvwx'
b'yz')""")
self.assertEqual(pprint.pformat(letters, width=25), """\
bytearray(b'abcdefghijkl'
b'mnopqrstuvwx'
b'yz')""")
special = bytearray(range(16))
self.assertEqual(pprint.pformat(special, width=72), repr(special))
self.assertEqual(pprint.pformat(special, width=57), """\
bytearray(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
b'\\x0c\\r\\x0e\\x0f')""")
self.assertEqual(pprint.pformat(special, width=41), """\
bytearray(b'\\x00\\x01\\x02\\x03'
b'\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
b'\\x0c\\r\\x0e\\x0f')""")
self.assertEqual(pprint.pformat(special, width=1), """\
bytearray(b'\\x00\\x01\\x02\\x03'
b'\\x04\\x05\\x06\\x07'
b'\\x08\\t\\n\\x0b'
b'\\x0c\\r\\x0e\\x0f')""")
self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
width=31), """\
{'a': 1,
'b': bytearray(b'abcdefghijkl'
b'mnopqrstuvwx'
b'yz'),
'c': 2}""")
self.assertEqual(pprint.pformat([[[[[letters]]]]], width=37), """\
[[[[[bytearray(b'abcdefghijklmnop'
b'qrstuvwxyz')]]]]]""")
self.assertEqual(pprint.pformat([[[[[special]]]]], width=50), """\
[[[[[bytearray(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'
b'\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f')]]]]]""")
def test_default_dict(self):
d = collections.defaultdict(int)
self.assertEqual(pprint.pformat(d, width=1), "defaultdict(<class 'int'>, {})")
words = 'the quick brown fox jumped over a lazy dog'.split()
d = collections.defaultdict(int, zip(words, itertools.count()))
self.assertEqual(pprint.pformat(d),
"""\
defaultdict(<class 'int'>,
{'a': 6,
'brown': 2,
'dog': 8,
'fox': 3,
'jumped': 4,
'lazy': 7,
'over': 5,
'quick': 1,
'the': 0})""")
def test_counter(self):
d = collections.Counter()
self.assertEqual(pprint.pformat(d, width=1), "Counter()")
d = collections.Counter('senselessness')
self.assertEqual(pprint.pformat(d, width=40),
"""\
Counter({'s': 6,
'e': 4,
'n': 2,
'l': 1})""")
def test_chainmap(self):
d = collections.ChainMap()
self.assertEqual(pprint.pformat(d, width=1), "ChainMap({})")
words = 'the quick brown fox jumped over a lazy dog'.split()
items = list(zip(words, itertools.count()))
d = collections.ChainMap(dict(items))
self.assertEqual(pprint.pformat(d),
"""\
ChainMap({'a': 6,
'brown': 2,
'dog': 8,
'fox': 3,
'jumped': 4,
'lazy': 7,
'over': 5,
'quick': 1,
'the': 0})""")
d = collections.ChainMap(dict(items), collections.OrderedDict(items))
self.assertEqual(pprint.pformat(d),
"""\
ChainMap({'a': 6,
'brown': 2,
'dog': 8,
'fox': 3,
'jumped': 4,
'lazy': 7,
'over': 5,
'quick': 1,
'the': 0},
OrderedDict([('the', 0),
('quick', 1),
('brown', 2),
('fox', 3),
('jumped', 4),
('over', 5),
('a', 6),
('lazy', 7),
('dog', 8)]))""")
def test_deque(self):
d = collections.deque()
self.assertEqual(pprint.pformat(d, width=1), "deque([])")
d = collections.deque(maxlen=7)
self.assertEqual(pprint.pformat(d, width=1), "deque([], maxlen=7)")
words = 'the quick brown fox jumped over a lazy dog'.split()
d = collections.deque(zip(words, itertools.count()))
self.assertEqual(pprint.pformat(d),
"""\
deque([('the', 0),
('quick', 1),
('brown', 2),
('fox', 3),
('jumped', 4),
('over', 5),
('a', 6),
('lazy', 7),
('dog', 8)])""")
d = collections.deque(zip(words, itertools.count()), maxlen=7)
self.assertEqual(pprint.pformat(d),
"""\
deque([('brown', 2),
('fox', 3),
('jumped', 4),
('over', 5),
('a', 6),
('lazy', 7),
('dog', 8)],
maxlen=7)""")
def test_user_dict(self):
d = collections.UserDict()
self.assertEqual(pprint.pformat(d, width=1), "{}")
words = 'the quick brown fox jumped over a lazy dog'.split()
d = collections.UserDict(zip(words, itertools.count()))
self.assertEqual(pprint.pformat(d),
"""\
{'a': 6,
'brown': 2,
'dog': 8,
'fox': 3,
'jumped': 4,
'lazy': 7,
'over': 5,
'quick': 1,
'the': 0}""")
def test_user_list(self):
d = collections.UserList()
self.assertEqual(pprint.pformat(d, width=1), "[]")
words = 'the quick brown fox jumped over a lazy dog'.split()
d = collections.UserList(zip(words, itertools.count()))
self.assertEqual(pprint.pformat(d),
"""\
[('the', 0),
('quick', 1),
('brown', 2),
('fox', 3),
('jumped', 4),
('over', 5),
('a', 6),
('lazy', 7),
('dog', 8)]""")
def test_user_string(self):
d = collections.UserString('')
self.assertEqual(pprint.pformat(d, width=1), "''")
d = collections.UserString('the quick brown fox jumped over a lazy dog')
self.assertEqual(pprint.pformat(d, width=20),
"""\
('the quick brown '
'fox jumped over '
'a lazy dog')""")
self.assertEqual(pprint.pformat({1: d}, width=20),
"""\
{1: 'the quick '
'brown fox '
'jumped over a '
'lazy dog'}""")
class DottedPrettyPrinter(pprint.PrettyPrinter):
def format(self, object, context, maxlevels, level):
if isinstance(object, str):
if ' ' in object:
return repr(object), 1, 0
else:
return object, 0, 0
else:
return pprint.PrettyPrinter.format(
self, object, context, maxlevels, level)
if __name__ == "__main__":
unittest.main()
| 44,533 | 1,013 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/bad_coding.py | # -*- coding: uft-8 -*-
| 24 | 2 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_peepholer.py | import dis
import re
import sys
import textwrap
import unittest
from test.bytecode_helper import BytecodeTestCase
class TestTranforms(BytecodeTestCase):
def test_unot(self):
# UNARY_NOT POP_JUMP_IF_FALSE --> POP_JUMP_IF_TRUE'
def unot(x):
if not x == 2:
del x
self.assertNotInBytecode(unot, 'UNARY_NOT')
self.assertNotInBytecode(unot, 'POP_JUMP_IF_FALSE')
self.assertInBytecode(unot, 'POP_JUMP_IF_TRUE')
def test_elim_inversion_of_is_or_in(self):
for line, cmp_op in (
('not a is b', 'is not',),
('not a in b', 'not in',),
('not a is not b', 'is',),
('not a not in b', 'in',),
):
code = compile(line, '', 'single')
self.assertInBytecode(code, 'COMPARE_OP', cmp_op)
def test_global_as_constant(self):
# LOAD_GLOBAL None/True/False --> LOAD_CONST None/True/False
def f():
x = None
x = None
return x
def g():
x = True
return x
def h():
x = False
return x
for func, elem in ((f, None), (g, True), (h, False)):
self.assertNotInBytecode(func, 'LOAD_GLOBAL')
self.assertInBytecode(func, 'LOAD_CONST', elem)
def f():
'Adding a docstring made this test fail in Py2.5.0'
return None
self.assertNotInBytecode(f, 'LOAD_GLOBAL')
self.assertInBytecode(f, 'LOAD_CONST', None)
def test_while_one(self):
# Skip over: LOAD_CONST trueconst POP_JUMP_IF_FALSE xx
def f():
while 1:
pass
return list
for elem in ('LOAD_CONST', 'POP_JUMP_IF_FALSE'):
self.assertNotInBytecode(f, elem)
for elem in ('JUMP_ABSOLUTE',):
self.assertInBytecode(f, elem)
def test_pack_unpack(self):
for line, elem in (
('a, = a,', 'LOAD_CONST',),
('a, b = a, b', 'ROT_TWO',),
('a, b, c = a, b, c', 'ROT_THREE',),
):
code = compile(line,'','single')
self.assertInBytecode(code, elem)
self.assertNotInBytecode(code, 'BUILD_TUPLE')
self.assertNotInBytecode(code, 'UNPACK_TUPLE')
def test_folding_of_tuples_of_constants(self):
for line, elem in (
('a = 1,2,3', (1, 2, 3)),
('("a","b","c")', ('a', 'b', 'c')),
('a,b,c = 1,2,3', (1, 2, 3)),
('(None, 1, None)', (None, 1, None)),
('((1, 2), 3, 4)', ((1, 2), 3, 4)),
):
code = compile(line,'','single')
self.assertInBytecode(code, 'LOAD_CONST', elem)
self.assertNotInBytecode(code, 'BUILD_TUPLE')
# Long tuples should be folded too.
code = compile(repr(tuple(range(10000))),'','single')
self.assertNotInBytecode(code, 'BUILD_TUPLE')
# One LOAD_CONST for the tuple, one for the None return value
load_consts = [instr for instr in dis.get_instructions(code)
if instr.opname == 'LOAD_CONST']
self.assertEqual(len(load_consts), 2)
# Bug 1053819: Tuple of constants misidentified when presented with:
# . . . opcode_with_arg 100 unary_opcode BUILD_TUPLE 1 . . .
# The following would segfault upon compilation
def crater():
(~[
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
],)
def test_folding_of_lists_of_constants(self):
for line, elem in (
# in/not in constants with BUILD_LIST should be folded to a tuple:
('a in [1,2,3]', (1, 2, 3)),
('a not in ["a","b","c"]', ('a', 'b', 'c')),
('a in [None, 1, None]', (None, 1, None)),
('a not in [(1, 2), 3, 4]', ((1, 2), 3, 4)),
):
code = compile(line, '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', elem)
self.assertNotInBytecode(code, 'BUILD_LIST')
def test_folding_of_sets_of_constants(self):
for line, elem in (
# in/not in constants with BUILD_SET should be folded to a frozenset:
('a in {1,2,3}', frozenset({1, 2, 3})),
('a not in {"a","b","c"}', frozenset({'a', 'c', 'b'})),
('a in {None, 1, None}', frozenset({1, None})),
('a not in {(1, 2), 3, 4}', frozenset({(1, 2), 3, 4})),
('a in {1, 2, 3, 3, 2, 1}', frozenset({1, 2, 3})),
):
code = compile(line, '', 'single')
self.assertNotInBytecode(code, 'BUILD_SET')
self.assertInBytecode(code, 'LOAD_CONST', elem)
# Ensure that the resulting code actually works:
def f(a):
return a in {1, 2, 3}
def g(a):
return a not in {1, 2, 3}
self.assertTrue(f(3))
self.assertTrue(not f(4))
self.assertTrue(not g(3))
self.assertTrue(g(4))
def test_folding_of_binops_on_constants(self):
for line, elem in (
('a = 2+3+4', 9), # chained fold
('"@"*4', '@@@@'), # check string ops
('a="abc" + "def"', 'abcdef'), # check string ops
('a = 3**4', 81), # binary power
('a = 3*4', 12), # binary multiply
('a = 13//4', 3), # binary floor divide
('a = 14%4', 2), # binary modulo
('a = 2+3', 5), # binary add
('a = 13-4', 9), # binary subtract
('a = (12,13)[1]', 13), # binary subscr
('a = 13 << 2', 52), # binary lshift
('a = 13 >> 2', 3), # binary rshift
('a = 13 & 7', 5), # binary and
('a = 13 ^ 7', 10), # binary xor
('a = 13 | 7', 15), # binary or
):
code = compile(line, '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', elem)
for instr in dis.get_instructions(code):
self.assertFalse(instr.opname.startswith('BINARY_'))
# Verify that unfoldables are skipped
code = compile('a=2+"b"', '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', 2)
self.assertInBytecode(code, 'LOAD_CONST', 'b')
# Verify that large sequences do not result from folding
code = compile('a="x"*10000', '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', 10000)
self.assertNotIn("x"*10000, code.co_consts)
code = compile('a=1<<1000', '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', 1000)
self.assertNotIn(1<<1000, code.co_consts)
code = compile('a=2**1000', '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', 1000)
self.assertNotIn(2**1000, code.co_consts)
def test_binary_subscr_on_unicode(self):
# valid code get optimized
code = compile('"foo"[0]', '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', 'f')
self.assertNotInBytecode(code, 'BINARY_SUBSCR')
code = compile('"\u0061\uffff"[1]', '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', '\uffff')
self.assertNotInBytecode(code,'BINARY_SUBSCR')
# With PEP 393, non-BMP char get optimized
code = compile('"\U00012345"[0]', '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', '\U00012345')
self.assertNotInBytecode(code, 'BINARY_SUBSCR')
# invalid code doesn't get optimized
# out of range
code = compile('"fuu"[10]', '', 'single')
self.assertInBytecode(code, 'BINARY_SUBSCR')
def test_folding_of_unaryops_on_constants(self):
for line, elem in (
('-0.5', -0.5), # unary negative
('-0.0', -0.0), # -0.0
('-(1.0-1.0)', -0.0), # -0.0 after folding
('-0', 0), # -0
('~-2', 1), # unary invert
('+1', 1), # unary positive
):
code = compile(line, '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', elem)
for instr in dis.get_instructions(code):
self.assertFalse(instr.opname.startswith('UNARY_'))
# Check that -0.0 works after marshaling
def negzero():
return -(1.0-1.0)
for instr in dis.get_instructions(code):
self.assertFalse(instr.opname.startswith('UNARY_'))
# Verify that unfoldables are skipped
for line, elem, opname in (
('-"abc"', 'abc', 'UNARY_NEGATIVE'),
('~"abc"', 'abc', 'UNARY_INVERT'),
):
code = compile(line, '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', elem)
self.assertInBytecode(code, opname)
def test_elim_extra_return(self):
# RETURN LOAD_CONST None RETURN --> RETURN
def f(x):
return x
self.assertNotInBytecode(f, 'LOAD_CONST', None)
returns = [instr for instr in dis.get_instructions(f)
if instr.opname == 'RETURN_VALUE']
self.assertEqual(len(returns), 1)
def test_elim_jump_to_return(self):
# JUMP_FORWARD to RETURN --> RETURN
def f(cond, true_value, false_value):
return true_value if cond else false_value
self.assertNotInBytecode(f, 'JUMP_FORWARD')
self.assertNotInBytecode(f, 'JUMP_ABSOLUTE')
returns = [instr for instr in dis.get_instructions(f)
if instr.opname == 'RETURN_VALUE']
self.assertEqual(len(returns), 2)
def test_elim_jump_after_return1(self):
# Eliminate dead code: jumps immediately after returns can't be reached
def f(cond1, cond2):
if cond1: return 1
if cond2: return 2
while 1:
return 3
while 1:
if cond1: return 4
return 5
return 6
self.assertNotInBytecode(f, 'JUMP_FORWARD')
self.assertNotInBytecode(f, 'JUMP_ABSOLUTE')
returns = [instr for instr in dis.get_instructions(f)
if instr.opname == 'RETURN_VALUE']
self.assertEqual(len(returns), 6)
def test_elim_jump_after_return2(self):
# Eliminate dead code: jumps immediately after returns can't be reached
def f(cond1, cond2):
while 1:
if cond1: return 4
self.assertNotInBytecode(f, 'JUMP_FORWARD')
# There should be one jump for the while loop.
returns = [instr for instr in dis.get_instructions(f)
if instr.opname == 'JUMP_ABSOLUTE']
self.assertEqual(len(returns), 1)
returns = [instr for instr in dis.get_instructions(f)
if instr.opname == 'RETURN_VALUE']
self.assertEqual(len(returns), 2)
def test_make_function_doesnt_bail(self):
def f():
def g()->1+1:
pass
return g
self.assertNotInBytecode(f, 'BINARY_ADD')
def test_constant_folding(self):
# Issue #11244: aggressive constant folding.
exprs = [
'3 * -5',
'-3 * 5',
'2 * (3 * 4)',
'(2 * 3) * 4',
'(-1, 2, 3)',
'(1, -2, 3)',
'(1, 2, -3)',
'(1, 2, -3) * 6',
'lambda x: x in {(3 * -5) + (-1 - 6), (1, -2, 3) * 2, None}',
]
for e in exprs:
code = compile(e, '', 'single')
for instr in dis.get_instructions(code):
self.assertFalse(instr.opname.startswith('UNARY_'))
self.assertFalse(instr.opname.startswith('BINARY_'))
self.assertFalse(instr.opname.startswith('BUILD_'))
class TestBuglets(unittest.TestCase):
def test_bug_11510(self):
# folded constant set optimization was commingled with the tuple
# unpacking optimization which would fail if the set had duplicate
# elements so that the set length was unexpected
def f():
x, y = {1, 1}
return x, y
with self.assertRaises(ValueError):
f()
if __name__ == "__main__":
unittest.main()
| 12,974 | 333 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_cprofile.py | """Test suite for the cProfile module."""
import sys
import unittest
from test.support import run_unittest, TESTFN, unlink
from test.support.script_helper import assert_python_failure
# rip off all interesting stuff from test_profile
import cProfile
from test.test_profile import ProfileTest, regenerate_expected_output
class CProfileTest(ProfileTest):
profilerclass = cProfile.Profile
profilermodule = cProfile
expected_max_output = "{built-in method builtins.max}"
def get_expected_output(self):
return _ProfileOutput
# Issue 3895.
def test_bad_counter_during_dealloc(self):
import _lsprof
# Must use a file as StringIO doesn't trigger the bug.
orig_stderr = sys.stderr
try:
with open(TESTFN, 'w') as file:
sys.stderr = file
try:
obj = _lsprof.Profiler(lambda: int)
obj.enable()
obj = _lsprof.Profiler(1)
obj.disable()
obj.clear()
finally:
sys.stderr = orig_stderr
finally:
unlink(TESTFN)
class TestCommandLine(unittest.TestCase):
def test_sort(self):
rc, out, err = assert_python_failure('-m', 'cProfile', '-s', 'demo')
self.assertGreater(rc, 0)
self.assertIn(b"option -s: invalid choice: 'demo'", err)
def test_main():
run_unittest(CProfileTest, TestCommandLine)
def main():
if '-r' not in sys.argv:
test_main()
else:
regenerate_expected_output(__file__, CProfileTest)
# Don't remove this comment. Everything below it is auto-generated.
#--cut--------------------------------------------------------------------------
_ProfileOutput = {}
_ProfileOutput['print_stats'] = """\
28 0.028 0.001 0.028 0.001 profilee.py:110(__getattr__)
1 0.270 0.270 1.000 1.000 profilee.py:25(testfunc)
23/3 0.150 0.007 0.170 0.057 profilee.py:35(factorial)
20 0.020 0.001 0.020 0.001 profilee.py:48(mul)
2 0.040 0.020 0.600 0.300 profilee.py:55(helper)
4 0.116 0.029 0.120 0.030 profilee.py:73(helper1)
2 0.000 0.000 0.140 0.070 profilee.py:84(helper2_indirect)
8 0.312 0.039 0.400 0.050 profilee.py:88(helper2)
8 0.064 0.008 0.080 0.010 profilee.py:98(subhelper)"""
_ProfileOutput['print_callers'] = """\
profilee.py:110(__getattr__) <- 16 0.016 0.016 profilee.py:98(subhelper)
profilee.py:25(testfunc) <- 1 0.270 1.000 <string>:1(<module>)
profilee.py:35(factorial) <- 1 0.014 0.130 profilee.py:25(testfunc)
20/3 0.130 0.147 profilee.py:35(factorial)
2 0.006 0.040 profilee.py:84(helper2_indirect)
profilee.py:48(mul) <- 20 0.020 0.020 profilee.py:35(factorial)
profilee.py:55(helper) <- 2 0.040 0.600 profilee.py:25(testfunc)
profilee.py:73(helper1) <- 4 0.116 0.120 profilee.py:55(helper)
profilee.py:84(helper2_indirect) <- 2 0.000 0.140 profilee.py:55(helper)
profilee.py:88(helper2) <- 6 0.234 0.300 profilee.py:55(helper)
2 0.078 0.100 profilee.py:84(helper2_indirect)
profilee.py:98(subhelper) <- 8 0.064 0.080 profilee.py:88(helper2)
{built-in method builtins.hasattr} <- 4 0.000 0.004 profilee.py:73(helper1)
8 0.000 0.008 profilee.py:88(helper2)
{built-in method sys.exc_info} <- 4 0.000 0.000 profilee.py:73(helper1)
{method 'append' of 'list' objects} <- 4 0.000 0.000 profilee.py:73(helper1)"""
_ProfileOutput['print_callees'] = """\
<string>:1(<module>) -> 1 0.270 1.000 profilee.py:25(testfunc)
profilee.py:110(__getattr__) ->
profilee.py:25(testfunc) -> 1 0.014 0.130 profilee.py:35(factorial)
2 0.040 0.600 profilee.py:55(helper)
profilee.py:35(factorial) -> 20/3 0.130 0.147 profilee.py:35(factorial)
20 0.020 0.020 profilee.py:48(mul)
profilee.py:48(mul) ->
profilee.py:55(helper) -> 4 0.116 0.120 profilee.py:73(helper1)
2 0.000 0.140 profilee.py:84(helper2_indirect)
6 0.234 0.300 profilee.py:88(helper2)
profilee.py:73(helper1) -> 4 0.000 0.004 {built-in method builtins.hasattr}
profilee.py:84(helper2_indirect) -> 2 0.006 0.040 profilee.py:35(factorial)
2 0.078 0.100 profilee.py:88(helper2)
profilee.py:88(helper2) -> 8 0.064 0.080 profilee.py:98(subhelper)
profilee.py:98(subhelper) -> 16 0.016 0.016 profilee.py:110(__getattr__)
{built-in method builtins.hasattr} -> 12 0.012 0.012 profilee.py:110(__getattr__)"""
if __name__ == "__main__":
main()
| 5,862 | 108 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_mimetypes.py | import io
import locale
import mimetypes
import sys
import unittest
from test import support
# Tell it we don't know about external files:
mimetypes.knownfiles = []
mimetypes.inited = False
mimetypes._default_mime_types()
class MimeTypesTestCase(unittest.TestCase):
def setUp(self):
self.db = mimetypes.MimeTypes()
def test_default_data(self):
eq = self.assertEqual
eq(self.db.guess_type("foo.html"), ("text/html", None))
eq(self.db.guess_type("foo.tgz"), ("application/x-tar", "gzip"))
eq(self.db.guess_type("foo.tar.gz"), ("application/x-tar", "gzip"))
eq(self.db.guess_type("foo.tar.Z"), ("application/x-tar", "compress"))
eq(self.db.guess_type("foo.tar.bz2"), ("application/x-tar", "bzip2"))
eq(self.db.guess_type("foo.tar.xz"), ("application/x-tar", "xz"))
def test_data_urls(self):
eq = self.assertEqual
guess_type = self.db.guess_type
eq(guess_type("data:,thisIsTextPlain"), ("text/plain", None))
eq(guess_type("data:;base64,thisIsTextPlain"), ("text/plain", None))
eq(guess_type("data:text/x-foo,thisIsTextXFoo"), ("text/x-foo", None))
def test_file_parsing(self):
eq = self.assertEqual
sio = io.StringIO("x-application/x-unittest pyunit\n")
self.db.readfp(sio)
eq(self.db.guess_type("foo.pyunit"),
("x-application/x-unittest", None))
eq(self.db.guess_extension("x-application/x-unittest"), ".pyunit")
def test_non_standard_types(self):
eq = self.assertEqual
# First try strict
eq(self.db.guess_type('foo.xul', strict=True), (None, None))
eq(self.db.guess_extension('image/jpg', strict=True), None)
# And then non-strict
eq(self.db.guess_type('foo.xul', strict=False), ('text/xul', None))
eq(self.db.guess_extension('image/jpg', strict=False), '.jpg')
def test_guess_all_types(self):
eq = self.assertEqual
unless = self.assertTrue
# First try strict. Use a set here for testing the results because if
# test_urllib2 is run before test_mimetypes, global state is modified
# such that the 'all' set will have more items in it.
all = set(self.db.guess_all_extensions('text/plain', strict=True))
unless(all >= set(['.bat', '.c', '.h', '.ksh', '.pl', '.txt']))
# And now non-strict
all = self.db.guess_all_extensions('image/jpg', strict=False)
all.sort()
eq(all, ['.jpg'])
# And now for no hits
all = self.db.guess_all_extensions('image/jpg', strict=True)
eq(all, [])
def test_encoding(self):
getpreferredencoding = locale.getpreferredencoding
self.addCleanup(setattr, locale, 'getpreferredencoding',
getpreferredencoding)
locale.getpreferredencoding = lambda: 'ascii'
filename = support.findfile("mime.types")
mimes = mimetypes.MimeTypes([filename])
exts = mimes.guess_all_extensions('application/vnd.geocube+xml',
strict=True)
self.assertEqual(exts, ['.g3', '.g\xb3'])
@unittest.skipUnless(sys.platform.startswith("win"), "Windows only")
class Win32MimeTypesTestCase(unittest.TestCase):
def setUp(self):
# ensure all entries actually come from the Windows registry
self.original_types_map = mimetypes.types_map.copy()
mimetypes.types_map.clear()
mimetypes.init()
self.db = mimetypes.MimeTypes()
def tearDown(self):
# restore default settings
mimetypes.types_map.clear()
mimetypes.types_map.update(self.original_types_map)
def test_registry_parsing(self):
# the original, minimum contents of the MIME database in the
# Windows registry is undocumented AFAIK.
# Use file types that should *always* exist:
eq = self.assertEqual
eq(self.db.guess_type("foo.txt"), ("text/plain", None))
eq(self.db.guess_type("image.jpg"), ("image/jpeg", None))
eq(self.db.guess_type("image.png"), ("image/png", None))
class MiscTestCase(unittest.TestCase):
def test__all__(self):
support.check__all__(self, mimetypes)
if __name__ == "__main__":
unittest.main()
| 4,294 | 112 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_locale.py | from test.support import verbose, is_android
import unittest
import locale
import sys
import codecs
class BaseLocalizedTest(unittest.TestCase):
#
# Base class for tests using a real locale
#
@classmethod
def setUpClass(cls):
if sys.platform in ('darwin', 'cosmo'):
import os
tlocs = ("en_US.UTF-8", "en_US.ISO8859-1", "en_US")
if int(os.uname().release.split('.')[0]) < 10:
# The locale test work fine on OSX 10.6, I (ronaldoussoren)
# haven't had time yet to verify if tests work on OSX 10.5
# (10.4 is known to be bad)
raise unittest.SkipTest("Locale support on MacOSX is minimal")
elif sys.platform.startswith("win"):
tlocs = ("En", "English")
else:
tlocs = ("en_US.UTF-8", "en_US.ISO8859-1",
"en_US.US-ASCII", "en_US")
try:
oldlocale = locale.setlocale(locale.LC_NUMERIC)
for tloc in tlocs:
try:
locale.setlocale(locale.LC_NUMERIC, tloc)
except locale.Error:
continue
break
else:
raise unittest.SkipTest("Test locale not supported "
"(tried %s)" % (', '.join(tlocs)))
cls.enUS_locale = tloc
finally:
locale.setlocale(locale.LC_NUMERIC, oldlocale)
def setUp(self):
oldlocale = locale.setlocale(self.locale_type)
self.addCleanup(locale.setlocale, self.locale_type, oldlocale)
locale.setlocale(self.locale_type, self.enUS_locale)
if verbose:
print("testing with %r..." % self.enUS_locale, end=' ', flush=True)
class BaseCookedTest(unittest.TestCase):
#
# Base class for tests using cooked localeconv() values
#
def setUp(self):
locale._override_localeconv = self.cooked_values
def tearDown(self):
locale._override_localeconv = {}
class CCookedTest(BaseCookedTest):
# A cooked "C" locale
cooked_values = {
'currency_symbol': '',
'decimal_point': '.',
'frac_digits': 127,
'grouping': [],
'int_curr_symbol': '',
'int_frac_digits': 127,
'mon_decimal_point': '',
'mon_grouping': [],
'mon_thousands_sep': '',
'n_cs_precedes': 127,
'n_sep_by_space': 127,
'n_sign_posn': 127,
'negative_sign': '',
'p_cs_precedes': 127,
'p_sep_by_space': 127,
'p_sign_posn': 127,
'positive_sign': '',
'thousands_sep': ''
}
class EnUSCookedTest(BaseCookedTest):
# A cooked "en_US" locale
cooked_values = {
'currency_symbol': '$',
'decimal_point': '.',
'frac_digits': 2,
'grouping': [3, 3, 0],
'int_curr_symbol': 'USD ',
'int_frac_digits': 2,
'mon_decimal_point': '.',
'mon_grouping': [3, 3, 0],
'mon_thousands_sep': ',',
'n_cs_precedes': 1,
'n_sep_by_space': 0,
'n_sign_posn': 1,
'negative_sign': '-',
'p_cs_precedes': 1,
'p_sep_by_space': 0,
'p_sign_posn': 1,
'positive_sign': '',
'thousands_sep': ','
}
class FrFRCookedTest(BaseCookedTest):
# A cooked "fr_FR" locale with a space character as decimal separator
# and a non-ASCII currency symbol.
cooked_values = {
'currency_symbol': '\u20ac',
'decimal_point': ',',
'frac_digits': 2,
'grouping': [3, 3, 0],
'int_curr_symbol': 'EUR ',
'int_frac_digits': 2,
'mon_decimal_point': ',',
'mon_grouping': [3, 3, 0],
'mon_thousands_sep': ' ',
'n_cs_precedes': 0,
'n_sep_by_space': 1,
'n_sign_posn': 1,
'negative_sign': '-',
'p_cs_precedes': 0,
'p_sep_by_space': 1,
'p_sign_posn': 1,
'positive_sign': '',
'thousands_sep': ' '
}
class BaseFormattingTest(object):
#
# Utility functions for formatting tests
#
def _test_formatfunc(self, format, value, out, func, **format_opts):
self.assertEqual(
func(format, value, **format_opts), out)
def _test_format(self, format, value, out, **format_opts):
self._test_formatfunc(format, value, out,
func=locale.format, **format_opts)
def _test_format_string(self, format, value, out, **format_opts):
self._test_formatfunc(format, value, out,
func=locale.format_string, **format_opts)
def _test_currency(self, value, out, **format_opts):
self.assertEqual(locale.currency(value, **format_opts), out)
class EnUSNumberFormatting(BaseFormattingTest):
# XXX there is a grouping + padding bug when the thousands separator
# is empty but the grouping array contains values (e.g. Solaris 10)
def setUp(self):
self.sep = locale.localeconv()['thousands_sep']
def test_grouping(self):
self._test_format("%f", 1024, grouping=1, out='1%s024.000000' % self.sep)
self._test_format("%f", 102, grouping=1, out='102.000000')
self._test_format("%f", -42, grouping=1, out='-42.000000')
self._test_format("%+f", -42, grouping=1, out='-42.000000')
def test_grouping_and_padding(self):
self._test_format("%20.f", -42, grouping=1, out='-42'.rjust(20))
if self.sep:
self._test_format("%+10.f", -4200, grouping=1,
out=('-4%s200' % self.sep).rjust(10))
self._test_format("%-10.f", -4200, grouping=1,
out=('-4%s200' % self.sep).ljust(10))
def test_integer_grouping(self):
self._test_format("%d", 4200, grouping=True, out='4%s200' % self.sep)
self._test_format("%+d", 4200, grouping=True, out='+4%s200' % self.sep)
self._test_format("%+d", -4200, grouping=True, out='-4%s200' % self.sep)
def test_integer_grouping_and_padding(self):
self._test_format("%10d", 4200, grouping=True,
out=('4%s200' % self.sep).rjust(10))
self._test_format("%-10d", -4200, grouping=True,
out=('-4%s200' % self.sep).ljust(10))
def test_simple(self):
self._test_format("%f", 1024, grouping=0, out='1024.000000')
self._test_format("%f", 102, grouping=0, out='102.000000')
self._test_format("%f", -42, grouping=0, out='-42.000000')
self._test_format("%+f", -42, grouping=0, out='-42.000000')
def test_padding(self):
self._test_format("%20.f", -42, grouping=0, out='-42'.rjust(20))
self._test_format("%+10.f", -4200, grouping=0, out='-4200'.rjust(10))
self._test_format("%-10.f", 4200, grouping=0, out='4200'.ljust(10))
def test_complex_formatting(self):
# Spaces in formatting string
self._test_format_string("One million is %i", 1000000, grouping=1,
out='One million is 1%s000%s000' % (self.sep, self.sep))
self._test_format_string("One million is %i", 1000000, grouping=1,
out='One million is 1%s000%s000' % (self.sep, self.sep))
# Dots in formatting string
self._test_format_string(".%f.", 1000.0, out='.1000.000000.')
# Padding
if self.sep:
self._test_format_string("--> %10.2f", 4200, grouping=1,
out='--> ' + ('4%s200.00' % self.sep).rjust(10))
# Asterisk formats
self._test_format_string("%10.*f", (2, 1000), grouping=0,
out='1000.00'.rjust(10))
if self.sep:
self._test_format_string("%*.*f", (10, 2, 1000), grouping=1,
out=('1%s000.00' % self.sep).rjust(10))
# Test more-in-one
if self.sep:
self._test_format_string("int %i float %.2f str %s",
(1000, 1000.0, 'str'), grouping=1,
out='int 1%s000 float 1%s000.00 str str' %
(self.sep, self.sep))
class TestFormatPatternArg(unittest.TestCase):
# Test handling of pattern argument of format
def test_onlyOnePattern(self):
# Issue 2522: accept exactly one % pattern, and no extra chars.
self.assertRaises(ValueError, locale.format, "%f\n", 'foo')
self.assertRaises(ValueError, locale.format, "%f\r", 'foo')
self.assertRaises(ValueError, locale.format, "%f\r\n", 'foo')
self.assertRaises(ValueError, locale.format, " %f", 'foo')
self.assertRaises(ValueError, locale.format, "%fg", 'foo')
self.assertRaises(ValueError, locale.format, "%^g", 'foo')
self.assertRaises(ValueError, locale.format, "%f%%", 'foo')
class TestLocaleFormatString(unittest.TestCase):
"""General tests on locale.format_string"""
def test_percent_escape(self):
self.assertEqual(locale.format_string('%f%%', 1.0), '%f%%' % 1.0)
self.assertEqual(locale.format_string('%d %f%%d', (1, 1.0)),
'%d %f%%d' % (1, 1.0))
self.assertEqual(locale.format_string('%(foo)s %%d', {'foo': 'bar'}),
('%(foo)s %%d' % {'foo': 'bar'}))
def test_mapping(self):
self.assertEqual(locale.format_string('%(foo)s bing.', {'foo': 'bar'}),
('%(foo)s bing.' % {'foo': 'bar'}))
self.assertEqual(locale.format_string('%(foo)s', {'foo': 'bar'}),
('%(foo)s' % {'foo': 'bar'}))
class TestNumberFormatting(BaseLocalizedTest, EnUSNumberFormatting):
# Test number formatting with a real English locale.
locale_type = locale.LC_NUMERIC
def setUp(self):
BaseLocalizedTest.setUp(self)
EnUSNumberFormatting.setUp(self)
class TestEnUSNumberFormatting(EnUSCookedTest, EnUSNumberFormatting):
# Test number formatting with a cooked "en_US" locale.
def setUp(self):
EnUSCookedTest.setUp(self)
EnUSNumberFormatting.setUp(self)
def test_currency(self):
self._test_currency(50000, "$50000.00")
self._test_currency(50000, "$50,000.00", grouping=True)
self._test_currency(50000, "USD 50,000.00",
grouping=True, international=True)
class TestCNumberFormatting(CCookedTest, BaseFormattingTest):
# Test number formatting with a cooked "C" locale.
def test_grouping(self):
self._test_format("%.2f", 12345.67, grouping=True, out='12345.67')
def test_grouping_and_padding(self):
self._test_format("%9.2f", 12345.67, grouping=True, out=' 12345.67')
class TestFrFRNumberFormatting(FrFRCookedTest, BaseFormattingTest):
# Test number formatting with a cooked "fr_FR" locale.
def test_decimal_point(self):
self._test_format("%.2f", 12345.67, out='12345,67')
def test_grouping(self):
self._test_format("%.2f", 345.67, grouping=True, out='345,67')
self._test_format("%.2f", 12345.67, grouping=True, out='12 345,67')
def test_grouping_and_padding(self):
self._test_format("%6.2f", 345.67, grouping=True, out='345,67')
self._test_format("%7.2f", 345.67, grouping=True, out=' 345,67')
self._test_format("%8.2f", 12345.67, grouping=True, out='12 345,67')
self._test_format("%9.2f", 12345.67, grouping=True, out='12 345,67')
self._test_format("%10.2f", 12345.67, grouping=True, out=' 12 345,67')
self._test_format("%-6.2f", 345.67, grouping=True, out='345,67')
self._test_format("%-7.2f", 345.67, grouping=True, out='345,67 ')
self._test_format("%-8.2f", 12345.67, grouping=True, out='12 345,67')
self._test_format("%-9.2f", 12345.67, grouping=True, out='12 345,67')
self._test_format("%-10.2f", 12345.67, grouping=True, out='12 345,67 ')
def test_integer_grouping(self):
self._test_format("%d", 200, grouping=True, out='200')
self._test_format("%d", 4200, grouping=True, out='4 200')
def test_integer_grouping_and_padding(self):
self._test_format("%4d", 4200, grouping=True, out='4 200')
self._test_format("%5d", 4200, grouping=True, out='4 200')
self._test_format("%10d", 4200, grouping=True, out='4 200'.rjust(10))
self._test_format("%-4d", 4200, grouping=True, out='4 200')
self._test_format("%-5d", 4200, grouping=True, out='4 200')
self._test_format("%-10d", 4200, grouping=True, out='4 200'.ljust(10))
def test_currency(self):
euro = '\u20ac'
self._test_currency(50000, "50000,00 " + euro)
self._test_currency(50000, "50 000,00 " + euro, grouping=True)
# XXX is the trailing space a bug?
self._test_currency(50000, "50 000,00 EUR ",
grouping=True, international=True)
class TestCollation(unittest.TestCase):
# Test string collation functions
def test_strcoll(self):
self.assertLess(locale.strcoll('a', 'b'), 0)
self.assertEqual(locale.strcoll('a', 'a'), 0)
self.assertGreater(locale.strcoll('b', 'a'), 0)
# embedded null character
self.assertRaises(ValueError, locale.strcoll, 'a\0', 'a')
self.assertRaises(ValueError, locale.strcoll, 'a', 'a\0')
def test_strxfrm(self):
self.assertLess(locale.strxfrm('a'), locale.strxfrm('b'))
# embedded null character
self.assertRaises(ValueError, locale.strxfrm, 'a\0')
class TestEnUSCollation(BaseLocalizedTest, TestCollation):
# Test string collation functions with a real English locale
locale_type = locale.LC_ALL
def setUp(self):
enc = codecs.lookup(locale.getpreferredencoding(False) or 'ascii').name
if enc not in ('utf-8', 'iso8859-1', 'cp1252'):
raise unittest.SkipTest('encoding not suitable')
if enc != 'iso8859-1' and (sys.platform in ('darwin','cosmo') or is_android or
sys.platform.startswith('freebsd')):
raise unittest.SkipTest('wcscoll/wcsxfrm have known bugs')
BaseLocalizedTest.setUp(self)
def test_strcoll_with_diacritic(self):
self.assertLess(locale.strcoll('Ã ', 'b'), 0)
def test_strxfrm_with_diacritic(self):
self.assertLess(locale.strxfrm('Ã '), locale.strxfrm('b'))
class NormalizeTest(unittest.TestCase):
def check(self, localename, expected):
self.assertEqual(locale.normalize(localename), expected, msg=localename)
def test_locale_alias(self):
for localename, alias in locale.locale_alias.items():
with self.subTest(locale=(localename, alias)):
self.check(localename, alias)
def test_empty(self):
self.check('', '')
def test_c(self):
self.check('c', 'C')
self.check('posix', 'C')
def test_english(self):
self.check('en', 'en_US.ISO8859-1')
self.check('EN', 'en_US.ISO8859-1')
self.check('en.iso88591', 'en_US.ISO8859-1')
self.check('en_US', 'en_US.ISO8859-1')
self.check('en_us', 'en_US.ISO8859-1')
self.check('en_GB', 'en_GB.ISO8859-1')
self.check('en_US.UTF-8', 'en_US.UTF-8')
self.check('en_US.utf8', 'en_US.UTF-8')
self.check('en_US:UTF-8', 'en_US.UTF-8')
self.check('en_US.ISO8859-1', 'en_US.ISO8859-1')
self.check('en_US.US-ASCII', 'en_US.ISO8859-1')
self.check('en_US.88591', 'en_US.ISO8859-1')
self.check('en_US.885915', 'en_US.ISO8859-15')
self.check('english', 'en_EN.ISO8859-1')
self.check('english_uk.ascii', 'en_GB.ISO8859-1')
def test_hyphenated_encoding(self):
self.check('az_AZ.iso88599e', 'az_AZ.ISO8859-9E')
self.check('az_AZ.ISO8859-9E', 'az_AZ.ISO8859-9E')
self.check('tt_RU.koi8c', 'tt_RU.KOI8-C')
self.check('tt_RU.KOI8-C', 'tt_RU.KOI8-C')
self.check('lo_LA.cp1133', 'lo_LA.IBM-CP1133')
self.check('lo_LA.ibmcp1133', 'lo_LA.IBM-CP1133')
self.check('lo_LA.IBM-CP1133', 'lo_LA.IBM-CP1133')
self.check('uk_ua.microsoftcp1251', 'uk_UA.CP1251')
self.check('uk_ua.microsoft-cp1251', 'uk_UA.CP1251')
self.check('ka_ge.georgianacademy', 'ka_GE.GEORGIAN-ACADEMY')
self.check('ka_GE.GEORGIAN-ACADEMY', 'ka_GE.GEORGIAN-ACADEMY')
self.check('cs_CZ.iso88592', 'cs_CZ.ISO8859-2')
self.check('cs_CZ.ISO8859-2', 'cs_CZ.ISO8859-2')
def test_euro_modifier(self):
self.check('de_DE@euro', 'de_DE.ISO8859-15')
self.check('en_US.ISO8859-15@euro', 'en_US.ISO8859-15')
self.check('de_DE.utf8@euro', 'de_DE.UTF-8')
def test_latin_modifier(self):
self.check('be_BY.UTF-8@latin', 'be_BY.UTF-8@latin')
self.check('sr_RS.UTF-8@latin', 'sr_RS.UTF-8@latin')
self.check('sr_RS.UTF-8@latn', 'sr_RS.UTF-8@latin')
def test_valencia_modifier(self):
self.check('ca_ES.UTF-8@valencia', 'ca_ES.UTF-8@valencia')
self.check('ca_ES@valencia', 'ca_ES.UTF-8@valencia')
self.check('ca@valencia', 'ca_ES.ISO8859-1@valencia')
def test_devanagari_modifier(self):
self.check('ks_IN.UTF-8@devanagari', 'ks_IN.UTF-8@devanagari')
self.check('ks_IN@devanagari', 'ks_IN.UTF-8@devanagari')
self.check('ks@devanagari', 'ks_IN.UTF-8@devanagari')
self.check('ks_IN.UTF-8', 'ks_IN.UTF-8')
self.check('ks_IN', 'ks_IN.UTF-8')
self.check('ks', 'ks_IN.UTF-8')
self.check('sd_IN.UTF-8@devanagari', 'sd_IN.UTF-8@devanagari')
self.check('sd_IN@devanagari', 'sd_IN.UTF-8@devanagari')
self.check('sd@devanagari', 'sd_IN.UTF-8@devanagari')
self.check('sd_IN.UTF-8', 'sd_IN.UTF-8')
self.check('sd_IN', 'sd_IN.UTF-8')
self.check('sd', 'sd_IN.UTF-8')
def test_euc_encoding(self):
self.check('ja_jp.euc', 'ja_JP.eucJP')
self.check('ja_jp.eucjp', 'ja_JP.eucJP')
self.check('ko_kr.euc', 'ko_KR.eucKR')
self.check('ko_kr.euckr', 'ko_KR.eucKR')
self.check('zh_cn.euc', 'zh_CN.eucCN')
self.check('zh_tw.euc', 'zh_TW.eucTW')
self.check('zh_tw.euctw', 'zh_TW.eucTW')
def test_japanese(self):
self.check('ja', 'ja_JP.eucJP')
self.check('ja.jis', 'ja_JP.JIS7')
self.check('ja.sjis', 'ja_JP.SJIS')
self.check('ja_jp', 'ja_JP.eucJP')
self.check('ja_jp.ajec', 'ja_JP.eucJP')
self.check('ja_jp.euc', 'ja_JP.eucJP')
self.check('ja_jp.eucjp', 'ja_JP.eucJP')
self.check('ja_jp.iso-2022-jp', 'ja_JP.JIS7')
self.check('ja_jp.iso2022jp', 'ja_JP.JIS7')
self.check('ja_jp.jis', 'ja_JP.JIS7')
self.check('ja_jp.jis7', 'ja_JP.JIS7')
self.check('ja_jp.mscode', 'ja_JP.SJIS')
self.check('ja_jp.pck', 'ja_JP.SJIS')
self.check('ja_jp.sjis', 'ja_JP.SJIS')
self.check('ja_jp.ujis', 'ja_JP.eucJP')
self.check('ja_jp.utf8', 'ja_JP.UTF-8')
self.check('japan', 'ja_JP.eucJP')
self.check('japanese', 'ja_JP.eucJP')
self.check('japanese-euc', 'ja_JP.eucJP')
self.check('japanese.euc', 'ja_JP.eucJP')
self.check('japanese.sjis', 'ja_JP.SJIS')
self.check('jp_jp', 'ja_JP.eucJP')
class TestMiscellaneous(unittest.TestCase):
def test_getpreferredencoding(self):
# Invoke getpreferredencoding to make sure it does not cause exceptions.
enc = locale.getpreferredencoding()
if enc:
# If encoding non-empty, make sure it is valid
codecs.lookup(enc)
def test_strcoll_3303(self):
# test crasher from bug #3303
self.assertRaises(TypeError, locale.strcoll, "a", None)
self.assertRaises(TypeError, locale.strcoll, b"a", None)
def test_setlocale_category(self):
locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_TIME)
locale.setlocale(locale.LC_CTYPE)
locale.setlocale(locale.LC_COLLATE)
locale.setlocale(locale.LC_MONETARY)
locale.setlocale(locale.LC_NUMERIC)
# crasher from bug #7419
self.assertRaises(locale.Error, locale.setlocale, 12345)
def test_getsetlocale_issue1813(self):
# Issue #1813: setting and getting the locale under a Turkish locale
oldlocale = locale.setlocale(locale.LC_CTYPE)
self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
try:
locale.setlocale(locale.LC_CTYPE, 'tr_TR')
except locale.Error:
# Unsupported locale on this system
self.skipTest('test needs Turkish locale')
loc = locale.getlocale(locale.LC_CTYPE)
if verbose:
print('testing with %a' % (loc,), end=' ', flush=True)
locale.setlocale(locale.LC_CTYPE, loc)
self.assertEqual(loc, locale.getlocale(locale.LC_CTYPE))
def test_invalid_locale_format_in_localetuple(self):
with self.assertRaises(TypeError):
locale.setlocale(locale.LC_ALL, b'fi_FI')
def test_invalid_iterable_in_localetuple(self):
with self.assertRaises(TypeError):
locale.setlocale(locale.LC_ALL, (b'not', b'valid'))
class BaseDelocalizeTest(BaseLocalizedTest):
def _test_delocalize(self, value, out):
self.assertEqual(locale.delocalize(value), out)
def _test_atof(self, value, out):
self.assertEqual(locale.atof(value), out)
def _test_atoi(self, value, out):
self.assertEqual(locale.atoi(value), out)
class TestEnUSDelocalize(EnUSCookedTest, BaseDelocalizeTest):
def test_delocalize(self):
self._test_delocalize('50000.00', '50000.00')
self._test_delocalize('50,000.00', '50000.00')
def test_atof(self):
self._test_atof('50000.00', 50000.)
self._test_atof('50,000.00', 50000.)
def test_atoi(self):
self._test_atoi('50000', 50000)
self._test_atoi('50,000', 50000)
class TestCDelocalizeTest(CCookedTest, BaseDelocalizeTest):
def test_delocalize(self):
self._test_delocalize('50000.00', '50000.00')
def test_atof(self):
self._test_atof('50000.00', 50000.)
def test_atoi(self):
self._test_atoi('50000', 50000)
class TestfrFRDelocalizeTest(FrFRCookedTest, BaseDelocalizeTest):
def test_delocalize(self):
self._test_delocalize('50000,00', '50000.00')
self._test_delocalize('50 000,00', '50000.00')
def test_atof(self):
self._test_atof('50000,00', 50000.)
self._test_atof('50 000,00', 50000.)
def test_atoi(self):
self._test_atoi('50000', 50000)
self._test_atoi('50 000', 50000)
if __name__ == '__main__':
unittest.main()
| 22,410 | 588 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_binop.py | """Tests for binary operators on subtypes of built-in types."""
import unittest
from test import support
from operator import eq, le, ne
from abc import ABCMeta
def gcd(a, b):
"""Greatest common divisor using Euclid's algorithm."""
while a:
a, b = b%a, a
return b
def isint(x):
"""Test whether an object is an instance of int."""
return isinstance(x, int)
def isnum(x):
"""Test whether an object is an instance of a built-in numeric type."""
for T in int, float, complex:
if isinstance(x, T):
return 1
return 0
def isRat(x):
"""Test wheter an object is an instance of the Rat class."""
return isinstance(x, Rat)
class Rat(object):
"""Rational number implemented as a normalized pair of ints."""
__slots__ = ['_Rat__num', '_Rat__den']
def __init__(self, num=0, den=1):
"""Constructor: Rat([num[, den]]).
The arguments must be ints, and default to (0, 1)."""
if not isint(num):
raise TypeError("Rat numerator must be int (%r)" % num)
if not isint(den):
raise TypeError("Rat denominator must be int (%r)" % den)
# But the zero is always on
if den == 0:
raise ZeroDivisionError("zero denominator")
g = gcd(den, num)
self.__num = int(num//g)
self.__den = int(den//g)
def _get_num(self):
"""Accessor function for read-only 'num' attribute of Rat."""
return self.__num
num = property(_get_num, None)
def _get_den(self):
"""Accessor function for read-only 'den' attribute of Rat."""
return self.__den
den = property(_get_den, None)
def __repr__(self):
"""Convert a Rat to a string resembling a Rat constructor call."""
return "Rat(%d, %d)" % (self.__num, self.__den)
def __str__(self):
"""Convert a Rat to a string resembling a decimal numeric value."""
return str(float(self))
def __float__(self):
"""Convert a Rat to a float."""
return self.__num*1.0/self.__den
def __int__(self):
"""Convert a Rat to an int; self.den must be 1."""
if self.__den == 1:
try:
return int(self.__num)
except OverflowError:
raise OverflowError("%s too large to convert to int" %
repr(self))
raise ValueError("can't convert %s to int" % repr(self))
def __add__(self, other):
"""Add two Rats, or a Rat and a number."""
if isint(other):
other = Rat(other)
if isRat(other):
return Rat(self.__num*other.__den + other.__num*self.__den,
self.__den*other.__den)
if isnum(other):
return float(self) + other
return NotImplemented
__radd__ = __add__
def __sub__(self, other):
"""Subtract two Rats, or a Rat and a number."""
if isint(other):
other = Rat(other)
if isRat(other):
return Rat(self.__num*other.__den - other.__num*self.__den,
self.__den*other.__den)
if isnum(other):
return float(self) - other
return NotImplemented
def __rsub__(self, other):
"""Subtract two Rats, or a Rat and a number (reversed args)."""
if isint(other):
other = Rat(other)
if isRat(other):
return Rat(other.__num*self.__den - self.__num*other.__den,
self.__den*other.__den)
if isnum(other):
return other - float(self)
return NotImplemented
def __mul__(self, other):
"""Multiply two Rats, or a Rat and a number."""
if isRat(other):
return Rat(self.__num*other.__num, self.__den*other.__den)
if isint(other):
return Rat(self.__num*other, self.__den)
if isnum(other):
return float(self)*other
return NotImplemented
__rmul__ = __mul__
def __truediv__(self, other):
"""Divide two Rats, or a Rat and a number."""
if isRat(other):
return Rat(self.__num*other.__den, self.__den*other.__num)
if isint(other):
return Rat(self.__num, self.__den*other)
if isnum(other):
return float(self) / other
return NotImplemented
def __rtruediv__(self, other):
"""Divide two Rats, or a Rat and a number (reversed args)."""
if isRat(other):
return Rat(other.__num*self.__den, other.__den*self.__num)
if isint(other):
return Rat(other*self.__den, self.__num)
if isnum(other):
return other / float(self)
return NotImplemented
def __floordiv__(self, other):
"""Divide two Rats, returning the floored result."""
if isint(other):
other = Rat(other)
elif not isRat(other):
return NotImplemented
x = self/other
return x.__num // x.__den
def __rfloordiv__(self, other):
"""Divide two Rats, returning the floored result (reversed args)."""
x = other/self
return x.__num // x.__den
def __divmod__(self, other):
"""Divide two Rats, returning quotient and remainder."""
if isint(other):
other = Rat(other)
elif not isRat(other):
return NotImplemented
x = self//other
return (x, self - other * x)
def __rdivmod__(self, other):
"""Divide two Rats, returning quotient and remainder (reversed args)."""
if isint(other):
other = Rat(other)
elif not isRat(other):
return NotImplemented
return divmod(other, self)
def __mod__(self, other):
"""Take one Rat modulo another."""
return divmod(self, other)[1]
def __rmod__(self, other):
"""Take one Rat modulo another (reversed args)."""
return divmod(other, self)[1]
def __eq__(self, other):
"""Compare two Rats for equality."""
if isint(other):
return self.__den == 1 and self.__num == other
if isRat(other):
return self.__num == other.__num and self.__den == other.__den
if isnum(other):
return float(self) == other
return NotImplemented
class RatTestCase(unittest.TestCase):
"""Unit tests for Rat class and its support utilities."""
def test_gcd(self):
self.assertEqual(gcd(10, 12), 2)
self.assertEqual(gcd(10, 15), 5)
self.assertEqual(gcd(10, 11), 1)
self.assertEqual(gcd(100, 15), 5)
self.assertEqual(gcd(-10, 2), -2)
self.assertEqual(gcd(10, -2), 2)
self.assertEqual(gcd(-10, -2), -2)
for i in range(1, 20):
for j in range(1, 20):
self.assertTrue(gcd(i, j) > 0)
self.assertTrue(gcd(-i, j) < 0)
self.assertTrue(gcd(i, -j) > 0)
self.assertTrue(gcd(-i, -j) < 0)
def test_constructor(self):
a = Rat(10, 15)
self.assertEqual(a.num, 2)
self.assertEqual(a.den, 3)
a = Rat(10, -15)
self.assertEqual(a.num, -2)
self.assertEqual(a.den, 3)
a = Rat(-10, 15)
self.assertEqual(a.num, -2)
self.assertEqual(a.den, 3)
a = Rat(-10, -15)
self.assertEqual(a.num, 2)
self.assertEqual(a.den, 3)
a = Rat(7)
self.assertEqual(a.num, 7)
self.assertEqual(a.den, 1)
try:
a = Rat(1, 0)
except ZeroDivisionError:
pass
else:
self.fail("Rat(1, 0) didn't raise ZeroDivisionError")
for bad in "0", 0.0, 0j, (), [], {}, None, Rat, unittest:
try:
a = Rat(bad)
except TypeError:
pass
else:
self.fail("Rat(%r) didn't raise TypeError" % bad)
try:
a = Rat(1, bad)
except TypeError:
pass
else:
self.fail("Rat(1, %r) didn't raise TypeError" % bad)
def test_add(self):
self.assertEqual(Rat(2, 3) + Rat(1, 3), 1)
self.assertEqual(Rat(2, 3) + 1, Rat(5, 3))
self.assertEqual(1 + Rat(2, 3), Rat(5, 3))
self.assertEqual(1.0 + Rat(1, 2), 1.5)
self.assertEqual(Rat(1, 2) + 1.0, 1.5)
def test_sub(self):
self.assertEqual(Rat(7, 2) - Rat(7, 5), Rat(21, 10))
self.assertEqual(Rat(7, 5) - 1, Rat(2, 5))
self.assertEqual(1 - Rat(3, 5), Rat(2, 5))
self.assertEqual(Rat(3, 2) - 1.0, 0.5)
self.assertEqual(1.0 - Rat(1, 2), 0.5)
def test_mul(self):
self.assertEqual(Rat(2, 3) * Rat(5, 7), Rat(10, 21))
self.assertEqual(Rat(10, 3) * 3, 10)
self.assertEqual(3 * Rat(10, 3), 10)
self.assertEqual(Rat(10, 5) * 0.5, 1.0)
self.assertEqual(0.5 * Rat(10, 5), 1.0)
def test_div(self):
self.assertEqual(Rat(10, 3) / Rat(5, 7), Rat(14, 3))
self.assertEqual(Rat(10, 3) / 3, Rat(10, 9))
self.assertEqual(2 / Rat(5), Rat(2, 5))
self.assertEqual(3.0 * Rat(1, 2), 1.5)
self.assertEqual(Rat(1, 2) * 3.0, 1.5)
def test_floordiv(self):
self.assertEqual(Rat(10) // Rat(4), 2)
self.assertEqual(Rat(10, 3) // Rat(4, 3), 2)
self.assertEqual(Rat(10) // 4, 2)
self.assertEqual(10 // Rat(4), 2)
def test_eq(self):
self.assertEqual(Rat(10), Rat(20, 2))
self.assertEqual(Rat(10), 10)
self.assertEqual(10, Rat(10))
self.assertEqual(Rat(10), 10.0)
self.assertEqual(10.0, Rat(10))
def test_true_div(self):
self.assertEqual(Rat(10, 3) / Rat(5, 7), Rat(14, 3))
self.assertEqual(Rat(10, 3) / 3, Rat(10, 9))
self.assertEqual(2 / Rat(5), Rat(2, 5))
self.assertEqual(3.0 * Rat(1, 2), 1.5)
self.assertEqual(Rat(1, 2) * 3.0, 1.5)
self.assertEqual(eval('1/2'), 0.5)
# XXX Ran out of steam; TO DO: divmod, div, future division
class OperationLogger:
"""Base class for classes with operation logging."""
def __init__(self, logger):
self.logger = logger
def log_operation(self, *args):
self.logger(*args)
def op_sequence(op, *classes):
"""Return the sequence of operations that results from applying
the operation `op` to instances of the given classes."""
log = []
instances = []
for c in classes:
instances.append(c(log.append))
try:
op(*instances)
except TypeError:
pass
return log
class A(OperationLogger):
def __eq__(self, other):
self.log_operation('A.__eq__')
return NotImplemented
def __le__(self, other):
self.log_operation('A.__le__')
return NotImplemented
def __ge__(self, other):
self.log_operation('A.__ge__')
return NotImplemented
class B(OperationLogger, metaclass=ABCMeta):
def __eq__(self, other):
self.log_operation('B.__eq__')
return NotImplemented
def __le__(self, other):
self.log_operation('B.__le__')
return NotImplemented
def __ge__(self, other):
self.log_operation('B.__ge__')
return NotImplemented
class C(B):
def __eq__(self, other):
self.log_operation('C.__eq__')
return NotImplemented
def __le__(self, other):
self.log_operation('C.__le__')
return NotImplemented
def __ge__(self, other):
self.log_operation('C.__ge__')
return NotImplemented
class V(OperationLogger):
"""Virtual subclass of B"""
def __eq__(self, other):
self.log_operation('V.__eq__')
return NotImplemented
def __le__(self, other):
self.log_operation('V.__le__')
return NotImplemented
def __ge__(self, other):
self.log_operation('V.__ge__')
return NotImplemented
B.register(V)
class OperationOrderTests(unittest.TestCase):
def test_comparison_orders(self):
self.assertEqual(op_sequence(eq, A, A), ['A.__eq__', 'A.__eq__'])
self.assertEqual(op_sequence(eq, A, B), ['A.__eq__', 'B.__eq__'])
self.assertEqual(op_sequence(eq, B, A), ['B.__eq__', 'A.__eq__'])
# C is a subclass of B, so C.__eq__ is called first
self.assertEqual(op_sequence(eq, B, C), ['C.__eq__', 'B.__eq__'])
self.assertEqual(op_sequence(eq, C, B), ['C.__eq__', 'B.__eq__'])
self.assertEqual(op_sequence(le, A, A), ['A.__le__', 'A.__ge__'])
self.assertEqual(op_sequence(le, A, B), ['A.__le__', 'B.__ge__'])
self.assertEqual(op_sequence(le, B, A), ['B.__le__', 'A.__ge__'])
self.assertEqual(op_sequence(le, B, C), ['C.__ge__', 'B.__le__'])
self.assertEqual(op_sequence(le, C, B), ['C.__le__', 'B.__ge__'])
self.assertTrue(issubclass(V, B))
self.assertEqual(op_sequence(eq, B, V), ['B.__eq__', 'V.__eq__'])
self.assertEqual(op_sequence(le, B, V), ['B.__le__', 'V.__ge__'])
class SupEq(object):
"""Class that can test equality"""
def __eq__(self, other):
return True
class S(SupEq):
"""Subclass of SupEq that should fail"""
__eq__ = None
class F(object):
"""Independent class that should fall back"""
class X(object):
"""Independent class that should fail"""
__eq__ = None
class SN(SupEq):
"""Subclass of SupEq that can test equality, but not non-equality"""
__ne__ = None
class XN:
"""Independent class that can test equality, but not non-equality"""
def __eq__(self, other):
return True
__ne__ = None
class FallbackBlockingTests(unittest.TestCase):
"""Unit tests for None method blocking"""
def test_fallback_rmethod_blocking(self):
e, f, s, x = SupEq(), F(), S(), X()
self.assertEqual(e, e)
self.assertEqual(e, f)
self.assertEqual(f, e)
# left operand is checked first
self.assertEqual(e, x)
self.assertRaises(TypeError, eq, x, e)
# S is a subclass, so it's always checked first
self.assertRaises(TypeError, eq, e, s)
self.assertRaises(TypeError, eq, s, e)
def test_fallback_ne_blocking(self):
e, sn, xn = SupEq(), SN(), XN()
self.assertFalse(e != e)
self.assertRaises(TypeError, ne, e, sn)
self.assertRaises(TypeError, ne, sn, e)
self.assertFalse(e != xn)
self.assertRaises(TypeError, ne, xn, e)
if __name__ == "__main__":
unittest.main()
| 14,503 | 442 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_future5.py | # Check that multiple features can be enabled.
from __future__ import unicode_literals, print_function
import sys
import unittest
from test import support
class TestMultipleFeatures(unittest.TestCase):
def test_unicode_literals(self):
self.assertIsInstance("", str)
def test_print_function(self):
with support.captured_output("stderr") as s:
print("foo", file=sys.stderr)
self.assertEqual(s.getvalue(), "foo\n")
if __name__ == '__main__':
unittest.main()
| 510 | 22 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/future_test1.py | """This is a test"""
# Import the name nested_scopes twice to trigger SF bug #407394 (regression).
from __future__ import nested_scopes, nested_scopes
def f(x):
def g(y):
return x + y
return g
result = f(2)(4)
| 229 | 12 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_linecache.py | """ Tests for the linecache module """
import linecache
import unittest
import os.path
import tempfile
import tokenize
from test import support
FILENAME = linecache.__file__
NONEXISTENT_FILENAME = FILENAME + '.missing'
INVALID_NAME = '!@$)(!@#_1'
EMPTY = ''
TEST_PATH = os.path.dirname(__file__)
MODULES = "linecache abc".split()
MODULE_PATH = os.path.dirname(FILENAME)
SOURCE_1 = '''
" Docstring "
def function():
return result
'''
SOURCE_2 = '''
def f():
return 1 + 1
a = f()
'''
SOURCE_3 = '''
def f():
return 3''' # No ending newline
class TempFile:
def setUp(self):
super().setUp()
with tempfile.NamedTemporaryFile(delete=False) as fp:
self.file_name = fp.name
fp.write(self.file_byte_string)
self.addCleanup(support.unlink, self.file_name)
class GetLineTestsGoodData(TempFile):
# file_list = ['list\n', 'of\n', 'good\n', 'strings\n']
def setUp(self):
self.file_byte_string = ''.join(self.file_list).encode('utf-8')
super().setUp()
def test_getline(self):
with tokenize.open(self.file_name) as fp:
for index, line in enumerate(fp):
if not line.endswith('\n'):
line += '\n'
cached_line = linecache.getline(self.file_name, index + 1)
self.assertEqual(line, cached_line)
def test_getlines(self):
lines = linecache.getlines(self.file_name)
self.assertEqual(lines, self.file_list)
class GetLineTestsBadData(TempFile):
# file_byte_string = b'Bad data goes here'
def test_getline(self):
self.assertRaises((SyntaxError, UnicodeDecodeError),
linecache.getline, self.file_name, 1)
def test_getlines(self):
self.assertRaises((SyntaxError, UnicodeDecodeError),
linecache.getlines, self.file_name)
class EmptyFile(GetLineTestsGoodData, unittest.TestCase):
file_list = []
class SingleEmptyLine(GetLineTestsGoodData, unittest.TestCase):
file_list = ['\n']
class GoodUnicode(GetLineTestsGoodData, unittest.TestCase):
file_list = ['á\n', 'b\n', 'abcdef\n', 'ááááá\n']
class BadUnicode(GetLineTestsBadData, unittest.TestCase):
file_byte_string = b'\x80abc'
class LineCacheTests(unittest.TestCase):
def test_getline(self):
getline = linecache.getline
# Bad values for line number should return an empty string
self.assertEqual(getline(FILENAME, 2**15), EMPTY)
self.assertEqual(getline(FILENAME, -1), EMPTY)
# Float values currently raise TypeError, should it?
self.assertRaises(TypeError, getline, FILENAME, 1.1)
# Bad filenames should return an empty string
self.assertEqual(getline(EMPTY, 1), EMPTY)
self.assertEqual(getline(INVALID_NAME, 1), EMPTY)
# Check module loading
for entry in MODULES:
filename = os.path.join(MODULE_PATH, entry) + '.py'
with open(filename) as file:
for index, line in enumerate(file):
self.assertEqual(line, getline(filename, index + 1))
# Check that bogus data isn't returned (issue #1309567)
empty = linecache.getlines('a/b/c/__init__.py')
self.assertEqual(empty, [])
def test_no_ending_newline(self):
self.addCleanup(support.unlink, support.TESTFN)
with open(support.TESTFN, "w") as fp:
fp.write(SOURCE_3)
lines = linecache.getlines(support.TESTFN)
self.assertEqual(lines, ["\n", "def f():\n", " return 3\n"])
def test_clearcache(self):
cached = []
for entry in MODULES:
filename = os.path.join(MODULE_PATH, entry) + '.py'
cached.append(filename)
linecache.getline(filename, 1)
# Are all files cached?
self.assertNotEqual(cached, [])
cached_empty = [fn for fn in cached if fn not in linecache.cache]
self.assertEqual(cached_empty, [])
# Can we clear the cache?
linecache.clearcache()
cached_empty = [fn for fn in cached if fn in linecache.cache]
self.assertEqual(cached_empty, [])
def test_checkcache(self):
getline = linecache.getline
# Create a source file and cache its contents
source_name = support.TESTFN + '.py'
self.addCleanup(support.unlink, source_name)
with open(source_name, 'w') as source:
source.write(SOURCE_1)
getline(source_name, 1)
# Keep a copy of the old contents
source_list = []
with open(source_name) as source:
for index, line in enumerate(source):
self.assertEqual(line, getline(source_name, index + 1))
source_list.append(line)
with open(source_name, 'w') as source:
source.write(SOURCE_2)
# Try to update a bogus cache entry
linecache.checkcache('dummy')
# Check that the cache matches the old contents
for index, line in enumerate(source_list):
self.assertEqual(line, getline(source_name, index + 1))
# Update the cache and check whether it matches the new source file
linecache.checkcache(source_name)
with open(source_name) as source:
for index, line in enumerate(source):
self.assertEqual(line, getline(source_name, index + 1))
source_list.append(line)
def test_lazycache_no_globals(self):
lines = linecache.getlines(FILENAME)
linecache.clearcache()
self.assertEqual(False, linecache.lazycache(FILENAME, None))
self.assertEqual(lines, linecache.getlines(FILENAME))
def test_lazycache_smoke(self):
lines = linecache.getlines(NONEXISTENT_FILENAME, globals())
linecache.clearcache()
self.assertEqual(
True, linecache.lazycache(NONEXISTENT_FILENAME, globals()))
self.assertEqual(1, len(linecache.cache[NONEXISTENT_FILENAME]))
# Note here that we're looking up a nonexistent filename with no
# globals: this would error if the lazy value wasn't resolved.
self.assertEqual(lines, linecache.getlines(NONEXISTENT_FILENAME))
def test_lazycache_provide_after_failed_lookup(self):
linecache.clearcache()
lines = linecache.getlines(NONEXISTENT_FILENAME, globals())
linecache.clearcache()
linecache.getlines(NONEXISTENT_FILENAME)
linecache.lazycache(NONEXISTENT_FILENAME, globals())
self.assertEqual(lines, linecache.updatecache(NONEXISTENT_FILENAME))
def test_lazycache_check(self):
linecache.clearcache()
linecache.lazycache(NONEXISTENT_FILENAME, globals())
linecache.checkcache()
def test_lazycache_bad_filename(self):
linecache.clearcache()
self.assertEqual(False, linecache.lazycache('', globals()))
self.assertEqual(False, linecache.lazycache('<foo>', globals()))
def test_lazycache_already_cached(self):
linecache.clearcache()
lines = linecache.getlines(NONEXISTENT_FILENAME, globals())
self.assertEqual(
False,
linecache.lazycache(NONEXISTENT_FILENAME, globals()))
self.assertEqual(4, len(linecache.cache[NONEXISTENT_FILENAME]))
def test_memoryerror(self):
lines = linecache.getlines(FILENAME)
self.assertTrue(lines)
def raise_memoryerror(*args, **kwargs):
raise MemoryError
with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
lines2 = linecache.getlines(FILENAME)
self.assertEqual(lines2, lines)
linecache.clearcache()
with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
lines3 = linecache.getlines(FILENAME)
self.assertEqual(lines3, [])
self.assertEqual(linecache.getlines(FILENAME), lines)
if __name__ == "__main__":
unittest.main()
| 7,980 | 243 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_netrc.py | import netrc, os, unittest, sys, tempfile, textwrap
from test import support
class NetrcTestCase(unittest.TestCase):
def make_nrc(self, test_data):
test_data = textwrap.dedent(test_data)
mode = 'w'
if sys.platform != 'cygwin':
mode += 't'
temp_fd, temp_filename = tempfile.mkstemp()
with os.fdopen(temp_fd, mode=mode) as fp:
fp.write(test_data)
self.addCleanup(os.unlink, temp_filename)
return netrc.netrc(temp_filename)
def test_default(self):
nrc = self.make_nrc("""\
machine host1.domain.com login log1 password pass1 account acct1
default login log2 password pass2
""")
self.assertEqual(nrc.hosts['host1.domain.com'],
('log1', 'acct1', 'pass1'))
self.assertEqual(nrc.hosts['default'], ('log2', None, 'pass2'))
nrc2 = self.make_nrc(nrc.__repr__())
self.assertEqual(nrc.hosts, nrc2.hosts)
def test_macros(self):
nrc = self.make_nrc("""\
macdef macro1
line1
line2
macdef macro2
line3
line4
""")
self.assertEqual(nrc.macros, {'macro1': ['line1\n', 'line2\n'],
'macro2': ['line3\n', 'line4\n']})
def _test_passwords(self, nrc, passwd):
nrc = self.make_nrc(nrc)
self.assertEqual(nrc.hosts['host.domain.com'], ('log', 'acct', passwd))
def test_password_with_leading_hash(self):
self._test_passwords("""\
machine host.domain.com login log password #pass account acct
""", '#pass')
def test_password_with_trailing_hash(self):
self._test_passwords("""\
machine host.domain.com login log password pass# account acct
""", 'pass#')
def test_password_with_internal_hash(self):
self._test_passwords("""\
machine host.domain.com login log password pa#ss account acct
""", 'pa#ss')
def _test_comment(self, nrc, passwd='pass'):
nrc = self.make_nrc(nrc)
self.assertEqual(nrc.hosts['foo.domain.com'], ('bar', None, passwd))
self.assertEqual(nrc.hosts['bar.domain.com'], ('foo', None, 'pass'))
def test_comment_before_machine_line(self):
self._test_comment("""\
# comment
machine foo.domain.com login bar password pass
machine bar.domain.com login foo password pass
""")
def test_comment_before_machine_line_no_space(self):
self._test_comment("""\
#comment
machine foo.domain.com login bar password pass
machine bar.domain.com login foo password pass
""")
def test_comment_before_machine_line_hash_only(self):
self._test_comment("""\
#
machine foo.domain.com login bar password pass
machine bar.domain.com login foo password pass
""")
def test_comment_at_end_of_machine_line(self):
self._test_comment("""\
machine foo.domain.com login bar password pass # comment
machine bar.domain.com login foo password pass
""")
def test_comment_at_end_of_machine_line_no_space(self):
self._test_comment("""\
machine foo.domain.com login bar password pass #comment
machine bar.domain.com login foo password pass
""")
def test_comment_at_end_of_machine_line_pass_has_hash(self):
self._test_comment("""\
machine foo.domain.com login bar password #pass #comment
machine bar.domain.com login foo password pass
""", '#pass')
@unittest.skipUnless(os.name == 'posix', 'POSIX only test')
def test_security(self):
# This test is incomplete since we are normally not run as root and
# therefore can't test the file ownership being wrong.
d = support.TESTFN
os.mkdir(d)
self.addCleanup(support.rmtree, d)
fn = os.path.join(d, '.netrc')
with open(fn, 'wt') as f:
f.write("""\
machine foo.domain.com login bar password pass
default login foo password pass
""")
with support.EnvironmentVarGuard() as environ:
environ.set('HOME', d)
os.chmod(fn, 0o600)
nrc = netrc.netrc()
self.assertEqual(nrc.hosts['foo.domain.com'],
('bar', None, 'pass'))
os.chmod(fn, 0o622)
self.assertRaises(netrc.NetrcParseError, netrc.netrc)
def test_main():
support.run_unittest(NetrcTestCase)
if __name__ == "__main__":
test_main()
| 4,736 | 134 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/talos-2019-0758.pem | -----BEGIN CERTIFICATE-----
MIIDqDCCApKgAwIBAgIBAjALBgkqhkiG9w0BAQswHzELMAkGA1UEBhMCVUsxEDAO
BgNVBAMTB2NvZHktY2EwHhcNMTgwNjE4MTgwMDU4WhcNMjgwNjE0MTgwMDU4WjA7
MQswCQYDVQQGEwJVSzEsMCoGA1UEAxMjY29kZW5vbWljb24tdm0tMi50ZXN0Lmxh
bC5jaXNjby5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC63fGB
J80A9Av1GB0bptslKRIUtJm8EeEu34HkDWbL6AJY0P8WfDtlXjlPaLqFa6sqH6ES
V48prSm1ZUbDSVL8R6BYVYpOlK8/48xk4pGTgRzv69gf5SGtQLwHy8UPBKgjSZoD
5a5k5wJXGswhKFFNqyyxqCvWmMnJWxXTt2XDCiWc4g4YAWi4O4+6SeeHVAV9rV7C
1wxqjzKovVe2uZOHjKEzJbbIU6JBPb6TRfMdRdYOw98n1VXDcKVgdX2DuuqjCzHP
WhU4Tw050M9NaK3eXp4Mh69VuiKoBGOLSOcS8reqHIU46Reg0hqeL8LIL6OhFHIF
j7HR6V1X6F+BfRS/AgMBAAGjgdYwgdMwCQYDVR0TBAIwADAdBgNVHQ4EFgQUOktp
HQjxDXXUg8prleY9jeLKeQ4wTwYDVR0jBEgwRoAUx6zgPygZ0ZErF9sPC4+5e2Io
UU+hI6QhMB8xCzAJBgNVBAYTAlVLMRAwDgYDVQQDEwdjb2R5LWNhggkA1QEAuwb7
2s0wCQYDVR0SBAIwADAuBgNVHREEJzAlgiNjb2Rlbm9taWNvbi12bS0yLnRlc3Qu
bGFsLmNpc2NvLmNvbTAOBgNVHQ8BAf8EBAMCBaAwCwYDVR0fBAQwAjAAMAsGCSqG
SIb3DQEBCwOCAQEAvqantx2yBlM11RoFiCfi+AfSblXPdrIrHvccepV4pYc/yO6p
t1f2dxHQb8rWH3i6cWag/EgIZx+HJQvo0rgPY1BFJsX1WnYf1/znZpkUBGbVmlJr
t/dW1gSkNS6sPsM0Q+7HPgEv8CPDNK5eo7vU2seE0iWOkxSyVUuiCEY9ZVGaLVit
p0C78nZ35Pdv4I+1cosmHl28+es1WI22rrnmdBpH8J1eY6WvUw2xuZHLeNVN0TzV
Q3qq53AaCWuLOD1AjESWuUCxMZTK9DPS4JKXTK8RLyDeqOvJGjsSWp3kL0y3GaQ+
10T1rfkKJub2+m9A9duin1fn6tHc2wSvB7m3DA==
-----END CERTIFICATE-----
| 1,330 | 23 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_robotparser.py | import io
import os
import unittest
import urllib.robotparser
from test import support
from http.server import BaseHTTPRequestHandler, HTTPServer
try:
import _thread
import threading
except ImportError:
threading = None
class BaseRobotTest:
robots_txt = ''
agent = 'test_robotparser'
good = []
bad = []
def setUp(self):
lines = io.StringIO(self.robots_txt).readlines()
self.parser = urllib.robotparser.RobotFileParser()
self.parser.parse(lines)
def get_agent_and_url(self, url):
if isinstance(url, tuple):
agent, url = url
return agent, url
return self.agent, url
def test_good_urls(self):
for url in self.good:
agent, url = self.get_agent_and_url(url)
with self.subTest(url=url, agent=agent):
self.assertTrue(self.parser.can_fetch(agent, url))
def test_bad_urls(self):
for url in self.bad:
agent, url = self.get_agent_and_url(url)
with self.subTest(url=url, agent=agent):
self.assertFalse(self.parser.can_fetch(agent, url))
class UserAgentWildcardTest(BaseRobotTest, unittest.TestCase):
robots_txt = """\
User-agent: *
Disallow: /cyberworld/map/ # This is an infinite virtual URL space
Disallow: /tmp/ # these will soon disappear
Disallow: /foo.html
"""
good = ['/', '/test.html']
bad = ['/cyberworld/map/index.html', '/tmp/xxx', '/foo.html']
class CrawlDelayAndCustomAgentTest(BaseRobotTest, unittest.TestCase):
robots_txt = """\
# robots.txt for http://www.example.com/
User-agent: *
Crawl-delay: 1
Request-rate: 3/15
Disallow: /cyberworld/map/ # This is an infinite virtual URL space
# Cybermapper knows where to go.
User-agent: cybermapper
Disallow:
"""
good = ['/', '/test.html', ('cybermapper', '/cyberworld/map/index.html')]
bad = ['/cyberworld/map/index.html']
class RejectAllRobotsTest(BaseRobotTest, unittest.TestCase):
robots_txt = """\
# go away
User-agent: *
Disallow: /
"""
good = []
bad = ['/cyberworld/map/index.html', '/', '/tmp/']
class BaseRequestRateTest(BaseRobotTest):
def test_request_rate(self):
for url in self.good + self.bad:
agent, url = self.get_agent_and_url(url)
with self.subTest(url=url, agent=agent):
if self.crawl_delay:
self.assertEqual(
self.parser.crawl_delay(agent), self.crawl_delay
)
if self.request_rate:
self.assertIsInstance(
self.parser.request_rate(agent),
urllib.robotparser.RequestRate
)
self.assertEqual(
self.parser.request_rate(agent).requests,
self.request_rate.requests
)
self.assertEqual(
self.parser.request_rate(agent).seconds,
self.request_rate.seconds
)
class CrawlDelayAndRequestRateTest(BaseRequestRateTest, unittest.TestCase):
robots_txt = """\
User-agent: figtree
Crawl-delay: 3
Request-rate: 9/30
Disallow: /tmp
Disallow: /a%3cd.html
Disallow: /a%2fb.html
Disallow: /%7ejoe/index.html
"""
agent = 'figtree'
request_rate = urllib.robotparser.RequestRate(9, 30)
crawl_delay = 3
good = [('figtree', '/foo.html')]
bad = ['/tmp', '/tmp.html', '/tmp/a.html', '/a%3cd.html', '/a%3Cd.html',
'/a%2fb.html', '/~joe/index.html']
class DifferentAgentTest(CrawlDelayAndRequestRateTest):
agent = 'FigTree Robot libwww-perl/5.04'
# these are not actually tested, but we still need to parse it
# in order to accommodate the input parameters
request_rate = None
crawl_delay = None
class InvalidRequestRateTest(BaseRobotTest, unittest.TestCase):
robots_txt = """\
User-agent: *
Disallow: /tmp/
Disallow: /a%3Cd.html
Disallow: /a/b.html
Disallow: /%7ejoe/index.html
Crawl-delay: 3
Request-rate: 9/banana
"""
good = ['/tmp']
bad = ['/tmp/', '/tmp/a.html', '/a%3cd.html', '/a%3Cd.html', '/a/b.html',
'/%7Ejoe/index.html']
crawl_delay = 3
class InvalidCrawlDelayTest(BaseRobotTest, unittest.TestCase):
# From bug report #523041
robots_txt = """\
User-Agent: *
Disallow: /.
Crawl-delay: pears
"""
good = ['/foo.html']
# bug report says "/" should be denied, but that is not in the RFC
bad = []
class AnotherInvalidRequestRateTest(BaseRobotTest, unittest.TestCase):
# also test that Allow and Diasallow works well with each other
robots_txt = """\
User-agent: Googlebot
Allow: /folder1/myfile.html
Disallow: /folder1/
Request-rate: whale/banana
"""
agent = 'Googlebot'
good = ['/folder1/myfile.html']
bad = ['/folder1/anotherfile.html']
class UserAgentOrderingTest(BaseRobotTest, unittest.TestCase):
# the order of User-agent should be correct. note
# that this file is incorrect because "Googlebot" is a
# substring of "Googlebot-Mobile"
robots_txt = """\
User-agent: Googlebot
Disallow: /
User-agent: Googlebot-Mobile
Allow: /
"""
agent = 'Googlebot'
bad = ['/something.jpg']
class UserAgentGoogleMobileTest(UserAgentOrderingTest):
agent = 'Googlebot-Mobile'
class GoogleURLOrderingTest(BaseRobotTest, unittest.TestCase):
# Google also got the order wrong. You need
# to specify the URLs from more specific to more general
robots_txt = """\
User-agent: Googlebot
Allow: /folder1/myfile.html
Disallow: /folder1/
"""
agent = 'googlebot'
good = ['/folder1/myfile.html']
bad = ['/folder1/anotherfile.html']
class DisallowQueryStringTest(BaseRobotTest, unittest.TestCase):
# see issue #6325 for details
robots_txt = """\
User-agent: *
Disallow: /some/path?name=value
"""
good = ['/some/path']
bad = ['/some/path?name=value']
class UseFirstUserAgentWildcardTest(BaseRobotTest, unittest.TestCase):
# obey first * entry (#4108)
robots_txt = """\
User-agent: *
Disallow: /some/path
User-agent: *
Disallow: /another/path
"""
good = ['/another/path']
bad = ['/some/path']
class EmptyQueryStringTest(BaseRobotTest, unittest.TestCase):
# normalize the URL first (#17403)
robots_txt = """\
User-agent: *
Allow: /some/path?
Disallow: /another/path?
"""
good = ['/some/path?']
bad = ['/another/path?']
class DefaultEntryTest(BaseRequestRateTest, unittest.TestCase):
robots_txt = """\
User-agent: *
Crawl-delay: 1
Request-rate: 3/15
Disallow: /cyberworld/map/
"""
request_rate = urllib.robotparser.RequestRate(3, 15)
crawl_delay = 1
good = ['/', '/test.html']
bad = ['/cyberworld/map/index.html']
class StringFormattingTest(BaseRobotTest, unittest.TestCase):
robots_txt = """\
User-agent: *
Crawl-delay: 1
Request-rate: 3/15
Disallow: /cyberworld/map/ # This is an infinite virtual URL space
# Cybermapper knows where to go.
User-agent: cybermapper
Disallow: /some/path
"""
expected_output = """\
User-agent: cybermapper
Disallow: /some/path
User-agent: *
Crawl-delay: 1
Request-rate: 3/15
Disallow: /cyberworld/map/
"""
def test_string_formatting(self):
self.assertEqual(str(self.parser), self.expected_output)
class RobotHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_error(403, "Forbidden access")
def log_message(self, format, *args):
pass
if __name__=='__main__':
unittest.main()
| 7,561 | 290 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_property.py | # Test case for property
# more tests are in test_descr
import sys
import cosmo
import unittest
from test import support
class PropertyBase(Exception):
pass
class PropertyGet(PropertyBase):
pass
class PropertySet(PropertyBase):
pass
class PropertyDel(PropertyBase):
pass
class BaseClass(object):
def __init__(self):
self._spam = 5
@property
def spam(self):
"""BaseClass.getter"""
return self._spam
@spam.setter
def spam(self, value):
self._spam = value
@spam.deleter
def spam(self):
del self._spam
class SubClass(BaseClass):
@BaseClass.spam.getter
def spam(self):
"""SubClass.getter"""
raise PropertyGet(self._spam)
@spam.setter
def spam(self, value):
raise PropertySet(self._spam)
@spam.deleter
def spam(self):
raise PropertyDel(self._spam)
class PropertyDocBase(object):
_spam = 1
def _get_spam(self):
return self._spam
spam = property(_get_spam, doc="spam spam spam")
class PropertyDocSub(PropertyDocBase):
@PropertyDocBase.spam.getter
def spam(self):
"""The decorator does not use this doc string"""
return self._spam
class PropertySubNewGetter(BaseClass):
@BaseClass.spam.getter
def spam(self):
"""new docstring"""
return 5
class PropertyNewGetter(object):
@property
def spam(self):
"""original docstring"""
return 1
@spam.getter
def spam(self):
"""new docstring"""
return 8
class PropertyTests(unittest.TestCase):
def test_property_decorator_baseclass(self):
# see #1620
base = BaseClass()
self.assertEqual(base.spam, 5)
self.assertEqual(base._spam, 5)
base.spam = 10
self.assertEqual(base.spam, 10)
self.assertEqual(base._spam, 10)
delattr(base, "spam")
self.assertTrue(not hasattr(base, "spam"))
self.assertTrue(not hasattr(base, "_spam"))
base.spam = 20
self.assertEqual(base.spam, 20)
self.assertEqual(base._spam, 20)
def test_property_decorator_subclass(self):
# see #1620
sub = SubClass()
self.assertRaises(PropertyGet, getattr, sub, "spam")
self.assertRaises(PropertySet, setattr, sub, "spam", None)
self.assertRaises(PropertyDel, delattr, sub, "spam")
@unittest.skipIf(sys.flags.optimize >= 2 or cosmo.MODE == 'tiny',
"Docstrings are omitted with -O2 and above")
def test_property_decorator_subclass_doc(self):
sub = SubClass()
self.assertEqual(sub.__class__.spam.__doc__, "SubClass.getter")
@unittest.skipIf(sys.flags.optimize >= 2 or cosmo.MODE == 'tiny',
"Docstrings are omitted with -O2 and above")
def test_property_decorator_baseclass_doc(self):
base = BaseClass()
self.assertEqual(base.__class__.spam.__doc__, "BaseClass.getter")
def test_property_decorator_doc(self):
base = PropertyDocBase()
sub = PropertyDocSub()
self.assertEqual(base.__class__.spam.__doc__, "spam spam spam")
self.assertEqual(sub.__class__.spam.__doc__, "spam spam spam")
@unittest.skipIf(sys.flags.optimize >= 2 or cosmo.MODE == 'tiny',
"Docstrings are omitted with -O2 and above")
def test_property_getter_doc_override(self):
newgettersub = PropertySubNewGetter()
self.assertEqual(newgettersub.spam, 5)
self.assertEqual(newgettersub.__class__.spam.__doc__, "new docstring")
newgetter = PropertyNewGetter()
self.assertEqual(newgetter.spam, 8)
self.assertEqual(newgetter.__class__.spam.__doc__, "new docstring")
def test_property___isabstractmethod__descriptor(self):
for val in (True, False, [], [1], '', '1'):
class C(object):
def foo(self):
pass
foo.__isabstractmethod__ = val
foo = property(foo)
self.assertIs(C.foo.__isabstractmethod__, bool(val))
# check that the property's __isabstractmethod__ descriptor does the
# right thing when presented with a value that fails truth testing:
class NotBool(object):
def __bool__(self):
raise ValueError()
__len__ = __bool__
with self.assertRaises(ValueError):
class C(object):
def foo(self):
pass
foo.__isabstractmethod__ = NotBool()
foo = property(foo)
C.foo.__isabstractmethod__
@unittest.skipIf(sys.flags.optimize >= 2 or cosmo.MODE == 'tiny',
"Docstrings are omitted with -O2 and above")
def test_property_builtin_doc_writable(self):
p = property(doc='basic')
self.assertEqual(p.__doc__, 'basic')
p.__doc__ = 'extended'
self.assertEqual(p.__doc__, 'extended')
@unittest.skipIf(sys.flags.optimize >= 2 or cosmo.MODE == 'tiny',
"Docstrings are omitted with -O2 and above")
def test_property_decorator_doc_writable(self):
class PropertyWritableDoc(object):
@property
def spam(self):
"""Eggs"""
return "eggs"
sub = PropertyWritableDoc()
self.assertEqual(sub.__class__.spam.__doc__, 'Eggs')
sub.__class__.spam.__doc__ = 'Spam'
self.assertEqual(sub.__class__.spam.__doc__, 'Spam')
@support.refcount_test
def test_refleaks_in___init__(self):
gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
fake_prop = property('fget', 'fset', 'fdel', 'doc')
refs_before = gettotalrefcount()
for i in range(100):
fake_prop.__init__('fget', 'fset', 'fdel', 'doc')
self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
# Issue 5890: subclasses of property do not preserve method __doc__ strings
class PropertySub(property):
"""This is a subclass of property"""
class PropertySubSlots(property):
"""This is a subclass of property that defines __slots__"""
__slots__ = ()
class PropertySubclassTests(unittest.TestCase):
def test_slots_docstring_copy_exception(self):
try:
class Foo(object):
@PropertySubSlots
def spam(self):
"""Trying to copy this docstring will raise an exception"""
return 1
except AttributeError:
pass
else:
raise Exception("AttributeError not raised")
@unittest.skipIf(sys.flags.optimize >= 2 or cosmo.MODE == 'tiny',
"Docstrings are omitted with -O2 and above")
def test_docstring_copy(self):
class Foo(object):
@PropertySub
def spam(self):
"""spam wrapped in property subclass"""
return 1
self.assertEqual(
Foo.spam.__doc__,
"spam wrapped in property subclass")
@unittest.skipIf(sys.flags.optimize >= 2 or cosmo.MODE == 'tiny',
"Docstrings are omitted with -O2 and above")
def test_property_setter_copies_getter_docstring(self):
class Foo(object):
def __init__(self): self._spam = 1
@PropertySub
def spam(self):
"""spam wrapped in property subclass"""
return self._spam
@spam.setter
def spam(self, value):
"""this docstring is ignored"""
self._spam = value
foo = Foo()
self.assertEqual(foo.spam, 1)
foo.spam = 2
self.assertEqual(foo.spam, 2)
self.assertEqual(
Foo.spam.__doc__,
"spam wrapped in property subclass")
class FooSub(Foo):
@Foo.spam.setter
def spam(self, value):
"""another ignored docstring"""
self._spam = 'eggs'
foosub = FooSub()
self.assertEqual(foosub.spam, 1)
foosub.spam = 7
self.assertEqual(foosub.spam, 'eggs')
self.assertEqual(
FooSub.spam.__doc__,
"spam wrapped in property subclass")
@unittest.skipIf(sys.flags.optimize >= 2 or cosmo.MODE == 'tiny',
"Docstrings are omitted with -O2 and above")
def test_property_new_getter_new_docstring(self):
class Foo(object):
@PropertySub
def spam(self):
"""a docstring"""
return 1
@spam.getter
def spam(self):
"""a new docstring"""
return 2
self.assertEqual(Foo.spam.__doc__, "a new docstring")
class FooBase(object):
@PropertySub
def spam(self):
"""a docstring"""
return 1
class Foo2(FooBase):
@FooBase.spam.getter
def spam(self):
"""a new docstring"""
return 2
self.assertEqual(Foo.spam.__doc__, "a new docstring")
if __name__ == '__main__':
unittest.main()
| 9,185 | 285 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_urllib2net.py | import unittest
from test import support
from test.test_urllib2 import sanepathname2url
import os
import socket
import urllib.error
import urllib.request
import sys
support.requires("network")
TIMEOUT = 60 # seconds
def _retry_thrice(func, exc, *args, **kwargs):
for i in range(3):
try:
return func(*args, **kwargs)
except exc as e:
last_exc = e
continue
raise last_exc
def _wrap_with_retry_thrice(func, exc):
def wrapped(*args, **kwargs):
return _retry_thrice(func, exc, *args, **kwargs)
return wrapped
# bpo-35411: FTP tests of test_urllib2net randomly fail
# with "425 Security: Bad IP connecting" on Travis CI
skip_ftp_test_on_travis = unittest.skipIf('TRAVIS' in os.environ,
'bpo-35411: skip FTP test '
'on Travis CI')
# Connecting to remote hosts is flaky. Make it more robust by retrying
# the connection several times.
_urlopen_with_retry = _wrap_with_retry_thrice(urllib.request.urlopen,
urllib.error.URLError)
class AuthTests(unittest.TestCase):
"""Tests urllib2 authentication features."""
## Disabled at the moment since there is no page under python.org which
## could be used to HTTP authentication.
#
# def test_basic_auth(self):
# import http.client
#
# test_url = "http://www.python.org/test/test_urllib2/basic_auth"
# test_hostport = "www.python.org"
# test_realm = 'Test Realm'
# test_user = 'test.test_urllib2net'
# test_password = 'blah'
#
# # failure
# try:
# _urlopen_with_retry(test_url)
# except urllib2.HTTPError, exc:
# self.assertEqual(exc.code, 401)
# else:
# self.fail("urlopen() should have failed with 401")
#
# # success
# auth_handler = urllib2.HTTPBasicAuthHandler()
# auth_handler.add_password(test_realm, test_hostport,
# test_user, test_password)
# opener = urllib2.build_opener(auth_handler)
# f = opener.open('http://localhost/')
# response = _urlopen_with_retry("http://www.python.org/")
#
# # The 'userinfo' URL component is deprecated by RFC 3986 for security
# # reasons, let's not implement it! (it's already implemented for proxy
# # specification strings (that is, URLs or authorities specifying a
# # proxy), so we must keep that)
# self.assertRaises(http.client.InvalidURL,
# urllib2.urlopen, "http://evil:[email protected]")
class CloseSocketTest(unittest.TestCase):
def test_close(self):
# calling .close() on urllib2's response objects should close the
# underlying socket
url = "http://www.example.com/"
with support.transient_internet(url):
response = _urlopen_with_retry(url)
sock = response.fp
self.assertFalse(sock.closed)
response.close()
self.assertTrue(sock.closed)
class OtherNetworkTests(unittest.TestCase):
def setUp(self):
if 0: # for debugging
import logging
logger = logging.getLogger("test_urllib2net")
logger.addHandler(logging.StreamHandler())
# XXX The rest of these tests aren't very good -- they don't check much.
# They do sometimes catch some major disasters, though.
@skip_ftp_test_on_travis
def test_ftp(self):
urls = [
'ftp://www.pythontest.net/README',
('ftp://www.pythontest.net/non-existent-file',
None, urllib.error.URLError),
]
self._test_urls(urls, self._extra_handlers())
def test_file(self):
TESTFN = support.TESTFN
f = open(TESTFN, 'w')
try:
f.write('hi there\n')
f.close()
urls = [
'file:' + sanepathname2url(os.path.abspath(TESTFN)),
('file:///nonsensename/etc/passwd', None,
urllib.error.URLError),
]
self._test_urls(urls, self._extra_handlers(), retry=True)
finally:
os.remove(TESTFN)
self.assertRaises(ValueError, urllib.request.urlopen,'./relative_path/to/file')
# XXX Following test depends on machine configurations that are internal
# to CNRI. Need to set up a public server with the right authentication
# configuration for test purposes.
## def test_cnri(self):
## if socket.gethostname() == 'bitdiddle':
## localhost = 'bitdiddle.cnri.reston.va.us'
## elif socket.gethostname() == 'bitdiddle.concentric.net':
## localhost = 'localhost'
## else:
## localhost = None
## if localhost is not None:
## urls = [
## 'file://%s/etc/passwd' % localhost,
## 'http://%s/simple/' % localhost,
## 'http://%s/digest/' % localhost,
## 'http://%s/not/found.h' % localhost,
## ]
## bauth = HTTPBasicAuthHandler()
## bauth.add_password('basic_test_realm', localhost, 'jhylton',
## 'password')
## dauth = HTTPDigestAuthHandler()
## dauth.add_password('digest_test_realm', localhost, 'jhylton',
## 'password')
## self._test_urls(urls, self._extra_handlers()+[bauth, dauth])
def test_urlwithfrag(self):
urlwith_frag = "http://www.pythontest.net/index.html#frag"
with support.transient_internet(urlwith_frag):
req = urllib.request.Request(urlwith_frag)
res = urllib.request.urlopen(req)
self.assertEqual(res.geturl(),
"http://www.pythontest.net/index.html#frag")
def test_redirect_url_withfrag(self):
redirect_url_with_frag = "http://www.pythontest.net/redir/with_frag/"
with support.transient_internet(redirect_url_with_frag):
req = urllib.request.Request(redirect_url_with_frag)
res = urllib.request.urlopen(req)
self.assertEqual(res.geturl(),
"http://www.pythontest.net/elsewhere/#frag")
def test_custom_headers(self):
url = "http://www.example.com"
with support.transient_internet(url):
opener = urllib.request.build_opener()
request = urllib.request.Request(url)
self.assertFalse(request.header_items())
opener.open(request)
self.assertTrue(request.header_items())
self.assertTrue(request.has_header('User-agent'))
request.add_header('User-Agent','Test-Agent')
opener.open(request)
self.assertEqual(request.get_header('User-agent'),'Test-Agent')
@unittest.skip('XXX: http://www.imdb.com is gone')
def test_sites_no_connection_close(self):
# Some sites do not send Connection: close header.
# Verify that those work properly. (#issue12576)
URL = 'http://www.imdb.com' # mangles Connection:close
with support.transient_internet(URL):
try:
with urllib.request.urlopen(URL) as res:
pass
except ValueError as e:
self.fail("urlopen failed for site not sending \
Connection:close")
else:
self.assertTrue(res)
req = urllib.request.urlopen(URL)
res = req.read()
self.assertTrue(res)
def _test_urls(self, urls, handlers, retry=True):
import time
import logging
debug = logging.getLogger("test_urllib2").debug
urlopen = urllib.request.build_opener(*handlers).open
if retry:
urlopen = _wrap_with_retry_thrice(urlopen, urllib.error.URLError)
for url in urls:
with self.subTest(url=url):
if isinstance(url, tuple):
url, req, expected_err = url
else:
req = expected_err = None
with support.transient_internet(url):
try:
f = urlopen(url, req, TIMEOUT)
# urllib.error.URLError is a subclass of OSError
except OSError as err:
if expected_err:
msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" %
(expected_err, url, req, type(err), err))
self.assertIsInstance(err, expected_err, msg)
else:
raise
else:
try:
with support.time_out, \
support.socket_peer_reset, \
support.ioerror_peer_reset:
buf = f.read()
debug("read %d bytes" % len(buf))
except socket.timeout:
print("<timeout: %s>" % url, file=sys.stderr)
f.close()
time.sleep(0.1)
def _extra_handlers(self):
handlers = []
cfh = urllib.request.CacheFTPHandler()
self.addCleanup(cfh.clear_cache)
cfh.setTimeout(1)
handlers.append(cfh)
return handlers
class TimeoutTest(unittest.TestCase):
def test_http_basic(self):
self.assertIsNone(socket.getdefaulttimeout())
url = "http://www.example.com"
with support.transient_internet(url, timeout=None):
u = _urlopen_with_retry(url)
self.addCleanup(u.close)
self.assertIsNone(u.fp.raw._sock.gettimeout())
def test_http_default_timeout(self):
self.assertIsNone(socket.getdefaulttimeout())
url = "http://www.example.com"
with support.transient_internet(url):
socket.setdefaulttimeout(60)
try:
u = _urlopen_with_retry(url)
self.addCleanup(u.close)
finally:
socket.setdefaulttimeout(None)
self.assertEqual(u.fp.raw._sock.gettimeout(), 60)
def test_http_no_timeout(self):
self.assertIsNone(socket.getdefaulttimeout())
url = "http://www.example.com"
with support.transient_internet(url):
socket.setdefaulttimeout(60)
try:
u = _urlopen_with_retry(url, timeout=None)
self.addCleanup(u.close)
finally:
socket.setdefaulttimeout(None)
self.assertIsNone(u.fp.raw._sock.gettimeout())
def test_http_timeout(self):
url = "http://www.example.com"
with support.transient_internet(url):
u = _urlopen_with_retry(url, timeout=120)
self.addCleanup(u.close)
self.assertEqual(u.fp.raw._sock.gettimeout(), 120)
FTP_HOST = 'ftp://www.pythontest.net/'
@skip_ftp_test_on_travis
def test_ftp_basic(self):
self.assertIsNone(socket.getdefaulttimeout())
with support.transient_internet(self.FTP_HOST, timeout=None):
u = _urlopen_with_retry(self.FTP_HOST)
self.addCleanup(u.close)
self.assertIsNone(u.fp.fp.raw._sock.gettimeout())
@skip_ftp_test_on_travis
def test_ftp_default_timeout(self):
self.assertIsNone(socket.getdefaulttimeout())
with support.transient_internet(self.FTP_HOST):
socket.setdefaulttimeout(60)
try:
u = _urlopen_with_retry(self.FTP_HOST)
self.addCleanup(u.close)
finally:
socket.setdefaulttimeout(None)
self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
@skip_ftp_test_on_travis
def test_ftp_no_timeout(self):
self.assertIsNone(socket.getdefaulttimeout())
with support.transient_internet(self.FTP_HOST):
socket.setdefaulttimeout(60)
try:
u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
self.addCleanup(u.close)
finally:
socket.setdefaulttimeout(None)
self.assertIsNone(u.fp.fp.raw._sock.gettimeout())
@skip_ftp_test_on_travis
def test_ftp_timeout(self):
with support.transient_internet(self.FTP_HOST):
u = _urlopen_with_retry(self.FTP_HOST, timeout=60)
self.addCleanup(u.close)
self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
if __name__ == "__main__":
unittest.main()
| 12,710 | 343 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_pyclbr.py | '''
Test cases for pyclbr.py
Nick Mathewson
'''
import sys
from types import FunctionType, MethodType, BuiltinFunctionType
import pyclbr
from unittest import TestCase, main as unittest_main
StaticMethodType = type(staticmethod(lambda: None))
ClassMethodType = type(classmethod(lambda c: None))
# Here we test the python class browser code.
#
# The main function in this suite, 'testModule', compares the output
# of pyclbr with the introspected members of a module. Because pyclbr
# is imperfect (as designed), testModule is called with a set of
# members to ignore.
class PyclbrTest(TestCase):
def assertListEq(self, l1, l2, ignore):
''' succeed iff {l1} - {ignore} == {l2} - {ignore} '''
missing = (set(l1) ^ set(l2)) - set(ignore)
if missing:
print("l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore), file=sys.stderr)
self.fail("%r missing" % missing.pop())
def assertHasattr(self, obj, attr, ignore):
''' succeed iff hasattr(obj,attr) or attr in ignore. '''
if attr in ignore: return
if not hasattr(obj, attr): print("???", attr)
self.assertTrue(hasattr(obj, attr),
'expected hasattr(%r, %r)' % (obj, attr))
def assertHaskey(self, obj, key, ignore):
''' succeed iff key in obj or key in ignore. '''
if key in ignore: return
if key not in obj:
print("***",key, file=sys.stderr)
self.assertIn(key, obj)
def assertEqualsOrIgnored(self, a, b, ignore):
''' succeed iff a == b or a in ignore or b in ignore '''
if a not in ignore and b not in ignore:
self.assertEqual(a, b)
def checkModule(self, moduleName, module=None, ignore=()):
''' succeed iff pyclbr.readmodule_ex(modulename) corresponds
to the actual module object, module. Any identifiers in
ignore are ignored. If no module is provided, the appropriate
module is loaded with __import__.'''
ignore = set(ignore) | set(['object'])
if module is None:
# Import it.
# ('<silly>' is to work around an API silliness in __import__)
module = __import__(moduleName, globals(), {}, ['<silly>'])
dict = pyclbr.readmodule_ex(moduleName)
def ismethod(oclass, obj, name):
classdict = oclass.__dict__
if isinstance(obj, MethodType):
# could be a classmethod
if (not isinstance(classdict[name], ClassMethodType) or
obj.__self__ is not oclass):
return False
elif not isinstance(obj, FunctionType):
return False
objname = obj.__name__
if objname.startswith("__") and not objname.endswith("__"):
objname = "_%s%s" % (oclass.__name__, objname)
return objname == name
# Make sure the toplevel functions and classes are the same.
for name, value in dict.items():
if name in ignore:
continue
self.assertHasattr(module, name, ignore)
py_item = getattr(module, name)
if isinstance(value, pyclbr.Function):
self.assertIsInstance(py_item, (FunctionType, BuiltinFunctionType))
if py_item.__module__ != moduleName:
continue # skip functions that came from somewhere else
self.assertEqual(py_item.__module__, value.module)
else:
self.assertIsInstance(py_item, type)
if py_item.__module__ != moduleName:
continue # skip classes that came from somewhere else
real_bases = [base.__name__ for base in py_item.__bases__]
pyclbr_bases = [ getattr(base, 'name', base)
for base in value.super ]
try:
self.assertListEq(real_bases, pyclbr_bases, ignore)
except:
print("class=%s" % py_item, file=sys.stderr)
raise
actualMethods = []
for m in py_item.__dict__.keys():
if ismethod(py_item, getattr(py_item, m), m):
actualMethods.append(m)
foundMethods = []
for m in value.methods.keys():
if m[:2] == '__' and m[-2:] != '__':
foundMethods.append('_'+name+m)
else:
foundMethods.append(m)
try:
self.assertListEq(foundMethods, actualMethods, ignore)
self.assertEqual(py_item.__module__, value.module)
self.assertEqualsOrIgnored(py_item.__name__, value.name,
ignore)
# can't check file or lineno
except:
print("class=%s" % py_item, file=sys.stderr)
raise
# Now check for missing stuff.
def defined_in(item, module):
if isinstance(item, type):
return item.__module__ == module.__name__
if isinstance(item, FunctionType):
return item.__globals__ is module.__dict__
return False
for name in dir(module):
item = getattr(module, name)
if isinstance(item, (type, FunctionType)):
if defined_in(item, module):
self.assertHaskey(dict, name, ignore)
def test_easy(self):
self.checkModule('pyclbr')
self.checkModule('ast')
self.checkModule('doctest', ignore=("TestResults", "_SpoofOut",
"DocTestCase", '_DocTestSuite'))
self.checkModule('difflib', ignore=("Match",))
def test_decorators(self):
# XXX: See comment in pyclbr_input.py for a test that would fail
# if it were not commented out.
#
self.checkModule('test.pyclbr_input', ignore=['om'])
def test_others(self):
cm = self.checkModule
# These were once about the 10 longest modules
cm('random', ignore=('Random',)) # from _random import Random as CoreGenerator
cm('cgi', ignore=('log',)) # set with = in module
cm('pickle', ignore=('partial',))
cm('aifc', ignore=('openfp', '_aifc_params')) # set with = in module
cm('sre_parse', ignore=('dump', 'groups', 'pos')) # from sre_constants import *; property
cm('pdb')
cm('pydoc')
# Tests for modules inside packages
cm('email.parser')
cm('test.test_pyclbr')
def test_issue_14798(self):
# test ImportError is raised when the first part of a dotted name is
# not a package
self.assertRaises(ImportError, pyclbr.readmodule_ex, 'asyncore.foo')
if __name__ == "__main__":
unittest_main()
| 6,980 | 177 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/fork_wait.py | """This test case provides support for checking forking and wait behavior.
To test different wait behavior, override the wait_impl method.
We want fork1() semantics -- only the forking thread survives in the
child after a fork().
On some systems (e.g. Solaris without posix threads) we find that all
active threads survive in the child after a fork(); this is an error.
"""
import os, sys, time, unittest
import test.support as support
threading = support.import_module('threading')
LONGSLEEP = 2
SHORTSLEEP = 0.5
NUM_THREADS = 4
class ForkWait(unittest.TestCase):
def setUp(self):
self._threading_key = support.threading_setup()
self.alive = {}
self.stop = 0
self.threads = []
def tearDown(self):
# Stop threads
self.stop = 1
for thread in self.threads:
thread.join()
thread = None
self.threads.clear()
support.threading_cleanup(*self._threading_key)
def f(self, id):
while not self.stop:
self.alive[id] = os.getpid()
try:
time.sleep(SHORTSLEEP)
except OSError:
pass
def wait_impl(self, cpid):
for i in range(10):
# waitpid() shouldn't hang, but some of the buildbots seem to hang
# in the forking tests. This is an attempt to fix the problem.
spid, status = os.waitpid(cpid, os.WNOHANG)
if spid == cpid:
break
time.sleep(2 * SHORTSLEEP)
self.assertEqual(spid, cpid)
self.assertEqual(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8))
def test_wait(self):
for i in range(NUM_THREADS):
thread = threading.Thread(target=self.f, args=(i,))
thread.start()
self.threads.append(thread)
# busy-loop to wait for threads
deadline = time.monotonic() + 10.0
while len(self.alive) < NUM_THREADS:
time.sleep(0.1)
if deadline < time.monotonic():
break
a = sorted(self.alive.keys())
self.assertEqual(a, list(range(NUM_THREADS)))
prefork_lives = self.alive.copy()
if sys.platform in ['unixware7']:
cpid = os.fork1()
else:
cpid = os.fork()
if cpid == 0:
# Child
time.sleep(LONGSLEEP)
n = 0
for key in self.alive:
if self.alive[key] != prefork_lives[key]:
n += 1
os._exit(n)
else:
# Parent
self.wait_impl(cpid)
| 2,621 | 92 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/badsyntax_pep3120.py | print("böse")
| 14 | 2 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_html.py | """
Tests for the html module functions.
"""
import html
import unittest
class HtmlTests(unittest.TestCase):
def test_escape(self):
self.assertEqual(
html.escape('\'<script>"&foo;"</script>\''),
''<script>"&foo;"</script>'')
self.assertEqual(
html.escape('\'<script>"&foo;"</script>\'', False),
'\'<script>"&foo;"</script>\'')
def test_unescape(self):
numeric_formats = ['&#%d', '&#%d;', '&#x%x', '&#x%x;']
errmsg = 'unescape(%r) should have returned %r'
def check(text, expected):
self.assertEqual(html.unescape(text), expected,
msg=errmsg % (text, expected))
def check_num(num, expected):
for format in numeric_formats:
text = format % num
self.assertEqual(html.unescape(text), expected,
msg=errmsg % (text, expected))
# check text with no character references
check('no character references', 'no character references')
# check & followed by invalid chars
check('&\n&\t& &&', '&\n&\t& &&')
# check & followed by numbers and letters
check('&0 &9 &a &0; &9; &a;', '&0 &9 &a &0; &9; &a;')
# check incomplete entities at the end of the string
for x in ['&', '&#', '&#x', '&#X', '&#y', '&#xy', '&#Xy']:
check(x, x)
check(x+';', x+';')
# check several combinations of numeric character references,
# possibly followed by different characters
formats = ['&#%d', '&#%07d', '&#%d;', '&#%07d;',
'&#x%x', '&#x%06x', '&#x%x;', '&#x%06x;',
'&#x%X', '&#x%06X', '&#X%x;', '&#X%06x;']
for num, char in zip([65, 97, 34, 38, 0x2603, 0x101234],
['A', 'a', '"', '&', '\u2603', '\U00101234']):
for s in formats:
check(s % num, char)
for end in [' ', 'X']:
check((s+end) % num, char+end)
# check invalid code points
for cp in [0xD800, 0xDB00, 0xDC00, 0xDFFF, 0x110000]:
check_num(cp, '\uFFFD')
# check more invalid code points
for cp in [0x1, 0xb, 0xe, 0x7f, 0xfffe, 0xffff, 0x10fffe, 0x10ffff]:
check_num(cp, '')
# check invalid numbers
for num, ch in zip([0x0d, 0x80, 0x95, 0x9d], '\r\u20ac\u2022\x9d'):
check_num(num, ch)
# check small numbers
check_num(0, '\uFFFD')
check_num(9, '\t')
# check a big number
check_num(1000000000000000000, '\uFFFD')
# check that multiple trailing semicolons are handled correctly
for e in ['";', '";', '";', '";']:
check(e, '";')
# check that semicolons in the middle don't create problems
for e in ['"quot;', '"quot;', '"quot;', '"quot;']:
check(e, '"quot;')
# check triple adjacent charrefs
for e in ['"', '"', '"', '"']:
check(e*3, '"""')
check((e+';')*3, '"""')
# check that the case is respected
for e in ['&', '&', '&', '&']:
check(e, '&')
for e in ['&Amp', '&Amp;']:
check(e, e)
# check that non-existent named entities are returned unchanged
check('&svadilfari;', '&svadilfari;')
# the following examples are in the html5 specs
check('¬it', '¬it')
check('¬it;', '¬it;')
check('¬in', '¬in')
check('∉', 'â')
# a similar example with a long name
check('¬ReallyAnExistingNamedCharacterReference;',
'¬ReallyAnExistingNamedCharacterReference;')
# longest valid name
check('∳', 'â³')
# check a charref that maps to two unicode chars
check('∾̳', '\u223E\u0333')
check('&acE', '&acE')
# see #12888
check('{ ' * 1050, '{ ' * 1050)
# see #15156
check('ÉricÉric&alphacentauriαcentauri',
'ÃricÃric&alphacentauriαcentauri')
check('&co;', '&co;')
if __name__ == '__main__':
unittest.main()
| 4,336 | 104 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_bool.py | # Test properties of bool promised by PEP 285
import unittest
from test import support
import os
class BoolTest(unittest.TestCase):
def test_subclass(self):
try:
class C(bool):
pass
except TypeError:
pass
else:
self.fail("bool should not be subclassable")
self.assertRaises(TypeError, int.__new__, bool, 0)
def test_print(self):
try:
fo = open(support.TESTFN, "w")
print(False, True, file=fo)
fo.close()
fo = open(support.TESTFN, "r")
self.assertEqual(fo.read(), 'False True\n')
finally:
fo.close()
os.remove(support.TESTFN)
def test_repr(self):
self.assertEqual(repr(False), 'False')
self.assertEqual(repr(True), 'True')
self.assertEqual(eval(repr(False)), False)
self.assertEqual(eval(repr(True)), True)
def test_str(self):
self.assertEqual(str(False), 'False')
self.assertEqual(str(True), 'True')
def test_int(self):
self.assertEqual(int(False), 0)
self.assertIsNot(int(False), False)
self.assertEqual(int(True), 1)
self.assertIsNot(int(True), True)
def test_float(self):
self.assertEqual(float(False), 0.0)
self.assertIsNot(float(False), False)
self.assertEqual(float(True), 1.0)
self.assertIsNot(float(True), True)
def test_math(self):
self.assertEqual(+False, 0)
self.assertIsNot(+False, False)
self.assertEqual(-False, 0)
self.assertIsNot(-False, False)
self.assertEqual(abs(False), 0)
self.assertIsNot(abs(False), False)
self.assertEqual(+True, 1)
self.assertIsNot(+True, True)
self.assertEqual(-True, -1)
self.assertEqual(abs(True), 1)
self.assertIsNot(abs(True), True)
self.assertEqual(~False, -1)
self.assertEqual(~True, -2)
self.assertEqual(False+2, 2)
self.assertEqual(True+2, 3)
self.assertEqual(2+False, 2)
self.assertEqual(2+True, 3)
self.assertEqual(False+False, 0)
self.assertIsNot(False+False, False)
self.assertEqual(False+True, 1)
self.assertIsNot(False+True, True)
self.assertEqual(True+False, 1)
self.assertIsNot(True+False, True)
self.assertEqual(True+True, 2)
self.assertEqual(True-True, 0)
self.assertIsNot(True-True, False)
self.assertEqual(False-False, 0)
self.assertIsNot(False-False, False)
self.assertEqual(True-False, 1)
self.assertIsNot(True-False, True)
self.assertEqual(False-True, -1)
self.assertEqual(True*1, 1)
self.assertEqual(False*1, 0)
self.assertIsNot(False*1, False)
self.assertEqual(True/1, 1)
self.assertIsNot(True/1, True)
self.assertEqual(False/1, 0)
self.assertIsNot(False/1, False)
self.assertEqual(True%1, 0)
self.assertIsNot(True%1, False)
self.assertEqual(True%2, 1)
self.assertIsNot(True%2, True)
self.assertEqual(False%1, 0)
self.assertIsNot(False%1, False)
for b in False, True:
for i in 0, 1, 2:
self.assertEqual(b**i, int(b)**i)
self.assertIsNot(b**i, bool(int(b)**i))
for a in False, True:
for b in False, True:
self.assertIs(a&b, bool(int(a)&int(b)))
self.assertIs(a|b, bool(int(a)|int(b)))
self.assertIs(a^b, bool(int(a)^int(b)))
self.assertEqual(a&int(b), int(a)&int(b))
self.assertIsNot(a&int(b), bool(int(a)&int(b)))
self.assertEqual(a|int(b), int(a)|int(b))
self.assertIsNot(a|int(b), bool(int(a)|int(b)))
self.assertEqual(a^int(b), int(a)^int(b))
self.assertIsNot(a^int(b), bool(int(a)^int(b)))
self.assertEqual(int(a)&b, int(a)&int(b))
self.assertIsNot(int(a)&b, bool(int(a)&int(b)))
self.assertEqual(int(a)|b, int(a)|int(b))
self.assertIsNot(int(a)|b, bool(int(a)|int(b)))
self.assertEqual(int(a)^b, int(a)^int(b))
self.assertIsNot(int(a)^b, bool(int(a)^int(b)))
self.assertIs(1==1, True)
self.assertIs(1==0, False)
self.assertIs(0<1, True)
self.assertIs(1<0, False)
self.assertIs(0<=0, True)
self.assertIs(1<=0, False)
self.assertIs(1>0, True)
self.assertIs(1>1, False)
self.assertIs(1>=1, True)
self.assertIs(0>=1, False)
self.assertIs(0!=1, True)
self.assertIs(0!=0, False)
x = [1]
self.assertIs(x is x, True)
self.assertIs(x is not x, False)
self.assertIs(1 in x, True)
self.assertIs(0 in x, False)
self.assertIs(1 not in x, False)
self.assertIs(0 not in x, True)
x = {1: 2}
self.assertIs(x is x, True)
self.assertIs(x is not x, False)
self.assertIs(1 in x, True)
self.assertIs(0 in x, False)
self.assertIs(1 not in x, False)
self.assertIs(0 not in x, True)
self.assertIs(not True, False)
self.assertIs(not False, True)
def test_convert(self):
self.assertRaises(TypeError, bool, 42, 42)
self.assertIs(bool(10), True)
self.assertIs(bool(1), True)
self.assertIs(bool(-1), True)
self.assertIs(bool(0), False)
self.assertIs(bool("hello"), True)
self.assertIs(bool(""), False)
self.assertIs(bool(), False)
def test_format(self):
self.assertEqual("%d" % False, "0")
self.assertEqual("%d" % True, "1")
self.assertEqual("%x" % False, "0")
self.assertEqual("%x" % True, "1")
def test_hasattr(self):
self.assertIs(hasattr([], "append"), True)
self.assertIs(hasattr([], "wobble"), False)
def test_callable(self):
self.assertIs(callable(len), True)
self.assertIs(callable(1), False)
def test_isinstance(self):
self.assertIs(isinstance(True, bool), True)
self.assertIs(isinstance(False, bool), True)
self.assertIs(isinstance(True, int), True)
self.assertIs(isinstance(False, int), True)
self.assertIs(isinstance(1, bool), False)
self.assertIs(isinstance(0, bool), False)
def test_issubclass(self):
self.assertIs(issubclass(bool, int), True)
self.assertIs(issubclass(int, bool), False)
def test_contains(self):
self.assertIs(1 in {}, False)
self.assertIs(1 in {1:1}, True)
def test_string(self):
self.assertIs("xyz".endswith("z"), True)
self.assertIs("xyz".endswith("x"), False)
self.assertIs("xyz0123".isalnum(), True)
self.assertIs("@#$%".isalnum(), False)
self.assertIs("xyz".isalpha(), True)
self.assertIs("@#$%".isalpha(), False)
self.assertIs("0123".isdigit(), True)
self.assertIs("xyz".isdigit(), False)
self.assertIs("xyz".islower(), True)
self.assertIs("XYZ".islower(), False)
self.assertIs("0123".isdecimal(), True)
self.assertIs("xyz".isdecimal(), False)
self.assertIs("0123".isnumeric(), True)
self.assertIs("xyz".isnumeric(), False)
self.assertIs(" ".isspace(), True)
self.assertIs("\xa0".isspace(), True)
self.assertIs("\u3000".isspace(), True)
self.assertIs("XYZ".isspace(), False)
self.assertIs("X".istitle(), True)
self.assertIs("x".istitle(), False)
self.assertIs("XYZ".isupper(), True)
self.assertIs("xyz".isupper(), False)
self.assertIs("xyz".startswith("x"), True)
self.assertIs("xyz".startswith("z"), False)
def test_boolean(self):
self.assertEqual(True & 1, 1)
self.assertNotIsInstance(True & 1, bool)
self.assertIs(True & True, True)
self.assertEqual(True | 1, 1)
self.assertNotIsInstance(True | 1, bool)
self.assertIs(True | True, True)
self.assertEqual(True ^ 1, 0)
self.assertNotIsInstance(True ^ 1, bool)
self.assertIs(True ^ True, False)
def test_fileclosed(self):
try:
f = open(support.TESTFN, "w")
self.assertIs(f.closed, False)
f.close()
self.assertIs(f.closed, True)
finally:
os.remove(support.TESTFN)
def test_types(self):
# types are always true.
for t in [bool, complex, dict, float, int, list, object,
set, str, tuple, type]:
self.assertIs(bool(t), True)
def test_operator(self):
import operator
self.assertIs(operator.truth(0), False)
self.assertIs(operator.truth(1), True)
self.assertIs(operator.not_(1), False)
self.assertIs(operator.not_(0), True)
self.assertIs(operator.contains([], 1), False)
self.assertIs(operator.contains([1], 1), True)
self.assertIs(operator.lt(0, 0), False)
self.assertIs(operator.lt(0, 1), True)
self.assertIs(operator.is_(True, True), True)
self.assertIs(operator.is_(True, False), False)
self.assertIs(operator.is_not(True, True), False)
self.assertIs(operator.is_not(True, False), True)
def test_marshal(self):
import marshal
self.assertIs(marshal.loads(marshal.dumps(True)), True)
self.assertIs(marshal.loads(marshal.dumps(False)), False)
def test_pickle(self):
import pickle
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
self.assertIs(pickle.loads(pickle.dumps(True, proto)), True)
self.assertIs(pickle.loads(pickle.dumps(False, proto)), False)
def test_picklevalues(self):
# Test for specific backwards-compatible pickle values
import pickle
self.assertEqual(pickle.dumps(True, protocol=0), b"I01\n.")
self.assertEqual(pickle.dumps(False, protocol=0), b"I00\n.")
self.assertEqual(pickle.dumps(True, protocol=1), b"I01\n.")
self.assertEqual(pickle.dumps(False, protocol=1), b"I00\n.")
self.assertEqual(pickle.dumps(True, protocol=2), b'\x80\x02\x88.')
self.assertEqual(pickle.dumps(False, protocol=2), b'\x80\x02\x89.')
def test_convert_to_bool(self):
# Verify that TypeError occurs when bad things are returned
# from __bool__(). This isn't really a bool test, but
# it's related.
check = lambda o: self.assertRaises(TypeError, bool, o)
class Foo(object):
def __bool__(self):
return self
check(Foo())
class Bar(object):
def __bool__(self):
return "Yes"
check(Bar())
class Baz(int):
def __bool__(self):
return self
check(Baz())
# __bool__() must return a bool not an int
class Spam(int):
def __bool__(self):
return 1
check(Spam())
class Eggs:
def __len__(self):
return -1
self.assertRaises(ValueError, bool, Eggs())
def test_from_bytes(self):
self.assertIs(bool.from_bytes(b'\x00'*8, 'big'), False)
self.assertIs(bool.from_bytes(b'abcd', 'little'), True)
def test_sane_len(self):
# this test just tests our assumptions about __len__
# this will start failing if __len__ changes assertions
for badval in ['illegal', -1, 1 << 32]:
class A:
def __len__(self):
return badval
try:
bool(A())
except (Exception) as e_bool:
try:
len(A())
except (Exception) as e_len:
self.assertEqual(str(e_bool), str(e_len))
def test_blocked(self):
class A:
__bool__ = None
self.assertRaises(TypeError, bool, A())
class B:
def __len__(self):
return 10
__bool__ = None
self.assertRaises(TypeError, bool, B())
def test_real_and_imag(self):
self.assertEqual(True.real, 1)
self.assertEqual(True.imag, 0)
self.assertIs(type(True.real), int)
self.assertIs(type(True.imag), int)
self.assertEqual(False.real, 0)
self.assertEqual(False.imag, 0)
self.assertIs(type(False.real), int)
self.assertIs(type(False.imag), int)
def test_main():
support.run_unittest(BoolTest)
if __name__ == "__main__":
test_main()
| 12,694 | 369 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_funcattrs.py | import types
import unittest
def global_function():
def inner_function():
class LocalClass:
pass
global inner_global_function
def inner_global_function():
def inner_function2():
pass
return inner_function2
return LocalClass
return lambda: inner_function
class FuncAttrsTest(unittest.TestCase):
def setUp(self):
class F:
def a(self):
pass
def b():
return 3
self.fi = F()
self.F = F
self.b = b
def cannot_set_attr(self, obj, name, value, exceptions):
try:
setattr(obj, name, value)
except exceptions:
pass
else:
self.fail("shouldn't be able to set %s to %r" % (name, value))
try:
delattr(obj, name)
except exceptions:
pass
else:
self.fail("shouldn't be able to del %s" % name)
class FunctionPropertiesTest(FuncAttrsTest):
# Include the external setUp method that is common to all tests
def test_module(self):
self.assertEqual(self.b.__module__, __name__)
def test_dir_includes_correct_attrs(self):
self.b.known_attr = 7
self.assertIn('known_attr', dir(self.b),
"set attributes not in dir listing of method")
# Test on underlying function object of method
self.F.a.known_attr = 7
self.assertIn('known_attr', dir(self.fi.a), "set attribute on function "
"implementations, should show up in next dir")
def test_duplicate_function_equality(self):
# Body of `duplicate' is the exact same as self.b
def duplicate():
'my docstring'
return 3
self.assertNotEqual(self.b, duplicate)
def test_copying___code__(self):
def test(): pass
self.assertEqual(test(), None)
test.__code__ = self.b.__code__
self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily
def test___globals__(self):
self.assertIs(self.b.__globals__, globals())
self.cannot_set_attr(self.b, '__globals__', 2,
(AttributeError, TypeError))
def test___closure__(self):
a = 12
def f(): print(a)
c = f.__closure__
self.assertIsInstance(c, tuple)
self.assertEqual(len(c), 1)
# don't have a type object handy
self.assertEqual(c[0].__class__.__name__, "cell")
self.cannot_set_attr(f, "__closure__", c, AttributeError)
def test_empty_cell(self):
def f(): print(a)
try:
f.__closure__[0].cell_contents
except ValueError:
pass
else:
self.fail("shouldn't be able to read an empty cell")
a = 12
def test___name__(self):
self.assertEqual(self.b.__name__, 'b')
self.b.__name__ = 'c'
self.assertEqual(self.b.__name__, 'c')
self.b.__name__ = 'd'
self.assertEqual(self.b.__name__, 'd')
# __name__ and __name__ must be a string
self.cannot_set_attr(self.b, '__name__', 7, TypeError)
# __name__ must be available when in restricted mode. Exec will raise
# AttributeError if __name__ is not available on f.
s = """def f(): pass\nf.__name__"""
exec(s, {'__builtins__': {}})
# Test on methods, too
self.assertEqual(self.fi.a.__name__, 'a')
self.cannot_set_attr(self.fi.a, "__name__", 'a', AttributeError)
def test___qualname__(self):
# PEP 3155
self.assertEqual(self.b.__qualname__, 'FuncAttrsTest.setUp.<locals>.b')
self.assertEqual(FuncAttrsTest.setUp.__qualname__, 'FuncAttrsTest.setUp')
self.assertEqual(global_function.__qualname__, 'global_function')
self.assertEqual(global_function().__qualname__,
'global_function.<locals>.<lambda>')
self.assertEqual(global_function()().__qualname__,
'global_function.<locals>.inner_function')
self.assertEqual(global_function()()().__qualname__,
'global_function.<locals>.inner_function.<locals>.LocalClass')
self.assertEqual(inner_global_function.__qualname__, 'inner_global_function')
self.assertEqual(inner_global_function().__qualname__, 'inner_global_function.<locals>.inner_function2')
self.b.__qualname__ = 'c'
self.assertEqual(self.b.__qualname__, 'c')
self.b.__qualname__ = 'd'
self.assertEqual(self.b.__qualname__, 'd')
# __qualname__ must be a string
self.cannot_set_attr(self.b, '__qualname__', 7, TypeError)
def test___code__(self):
num_one, num_two = 7, 8
def a(): pass
def b(): return 12
def c(): return num_one
def d(): return num_two
def e(): return num_one, num_two
for func in [a, b, c, d, e]:
self.assertEqual(type(func.__code__), types.CodeType)
self.assertEqual(c(), 7)
self.assertEqual(d(), 8)
d.__code__ = c.__code__
self.assertEqual(c.__code__, d.__code__)
self.assertEqual(c(), 7)
# self.assertEqual(d(), 7)
try:
b.__code__ = c.__code__
except ValueError:
pass
else:
self.fail("__code__ with different numbers of free vars should "
"not be possible")
try:
e.__code__ = d.__code__
except ValueError:
pass
else:
self.fail("__code__ with different numbers of free vars should "
"not be possible")
def test_blank_func_defaults(self):
self.assertEqual(self.b.__defaults__, None)
del self.b.__defaults__
self.assertEqual(self.b.__defaults__, None)
def test_func_default_args(self):
def first_func(a, b):
return a+b
def second_func(a=1, b=2):
return a+b
self.assertEqual(first_func.__defaults__, None)
self.assertEqual(second_func.__defaults__, (1, 2))
first_func.__defaults__ = (1, 2)
self.assertEqual(first_func.__defaults__, (1, 2))
self.assertEqual(first_func(), 3)
self.assertEqual(first_func(3), 5)
self.assertEqual(first_func(3, 5), 8)
del second_func.__defaults__
self.assertEqual(second_func.__defaults__, None)
try:
second_func()
except TypeError:
pass
else:
self.fail("__defaults__ does not update; deleting it does not "
"remove requirement")
class InstancemethodAttrTest(FuncAttrsTest):
def test___class__(self):
self.assertEqual(self.fi.a.__self__.__class__, self.F)
self.cannot_set_attr(self.fi.a, "__class__", self.F, TypeError)
def test___func__(self):
self.assertEqual(self.fi.a.__func__, self.F.a)
self.cannot_set_attr(self.fi.a, "__func__", self.F.a, AttributeError)
def test___self__(self):
self.assertEqual(self.fi.a.__self__, self.fi)
self.cannot_set_attr(self.fi.a, "__self__", self.fi, AttributeError)
def test___func___non_method(self):
# Behavior should be the same when a method is added via an attr
# assignment
self.fi.id = types.MethodType(id, self.fi)
self.assertEqual(self.fi.id(), id(self.fi))
# Test usage
try:
self.fi.id.unknown_attr
except AttributeError:
pass
else:
self.fail("using unknown attributes should raise AttributeError")
# Test assignment and deletion
self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError)
class ArbitraryFunctionAttrTest(FuncAttrsTest):
def test_set_attr(self):
self.b.known_attr = 7
self.assertEqual(self.b.known_attr, 7)
try:
self.fi.a.known_attr = 7
except AttributeError:
pass
else:
self.fail("setting attributes on methods should raise error")
def test_delete_unknown_attr(self):
try:
del self.b.unknown_attr
except AttributeError:
pass
else:
self.fail("deleting unknown attribute should raise TypeError")
def test_unset_attr(self):
for func in [self.b, self.fi.a]:
try:
func.non_existent_attr
except AttributeError:
pass
else:
self.fail("using unknown attributes should raise "
"AttributeError")
class FunctionDictsTest(FuncAttrsTest):
def test_setting_dict_to_invalid(self):
self.cannot_set_attr(self.b, '__dict__', None, TypeError)
from collections import UserDict
d = UserDict({'known_attr': 7})
self.cannot_set_attr(self.fi.a.__func__, '__dict__', d, TypeError)
def test_setting_dict_to_valid(self):
d = {'known_attr': 7}
self.b.__dict__ = d
# Test assignment
self.assertIs(d, self.b.__dict__)
# ... and on all the different ways of referencing the method's func
self.F.a.__dict__ = d
self.assertIs(d, self.fi.a.__func__.__dict__)
self.assertIs(d, self.fi.a.__dict__)
# Test value
self.assertEqual(self.b.known_attr, 7)
self.assertEqual(self.b.__dict__['known_attr'], 7)
# ... and again, on all the different method's names
self.assertEqual(self.fi.a.__func__.known_attr, 7)
self.assertEqual(self.fi.a.known_attr, 7)
def test_delete___dict__(self):
try:
del self.b.__dict__
except TypeError:
pass
else:
self.fail("deleting function dictionary should raise TypeError")
def test_unassigned_dict(self):
self.assertEqual(self.b.__dict__, {})
def test_func_as_dict_key(self):
value = "Some string"
d = {}
d[self.b] = value
self.assertEqual(d[self.b], value)
class FunctionDocstringTest(FuncAttrsTest):
def test_set_docstring_attr(self):
self.assertEqual(self.b.__doc__, None)
docstr = "A test method that does nothing"
self.b.__doc__ = docstr
self.F.a.__doc__ = docstr
self.assertEqual(self.b.__doc__, docstr)
self.assertEqual(self.fi.a.__doc__, docstr)
self.cannot_set_attr(self.fi.a, "__doc__", docstr, AttributeError)
def test_delete_docstring(self):
self.b.__doc__ = "The docstring"
del self.b.__doc__
self.assertEqual(self.b.__doc__, None)
def cell(value):
"""Create a cell containing the given value."""
def f():
print(a)
a = value
return f.__closure__[0]
def empty_cell(empty=True):
"""Create an empty cell."""
def f():
print(a)
# the intent of the following line is simply "if False:"; it's
# spelt this way to avoid the danger that a future optimization
# might simply remove an "if False:" code block.
if not empty:
a = 1729
return f.__closure__[0]
class CellTest(unittest.TestCase):
def test_comparison(self):
# These tests are here simply to exercise the comparison code;
# their presence should not be interpreted as providing any
# guarantees about the semantics (or even existence) of cell
# comparisons in future versions of CPython.
self.assertTrue(cell(2) < cell(3))
self.assertTrue(empty_cell() < cell('saturday'))
self.assertTrue(empty_cell() == empty_cell())
self.assertTrue(cell(-36) == cell(-36.0))
self.assertTrue(cell(True) > empty_cell())
class StaticMethodAttrsTest(unittest.TestCase):
def test_func_attribute(self):
def f():
pass
c = classmethod(f)
self.assertTrue(c.__func__ is f)
s = staticmethod(f)
self.assertTrue(s.__func__ is f)
class BuiltinFunctionPropertiesTest(unittest.TestCase):
# XXX Not sure where this should really go since I can't find a
# test module specifically for builtin_function_or_method.
def test_builtin__qualname__(self):
import time
# builtin function:
self.assertEqual(len.__qualname__, 'len')
self.assertEqual(time.time.__qualname__, 'time')
# builtin classmethod:
self.assertEqual(dict.fromkeys.__qualname__, 'dict.fromkeys')
self.assertEqual(float.__getformat__.__qualname__,
'float.__getformat__')
# builtin staticmethod:
self.assertEqual(str.maketrans.__qualname__, 'str.maketrans')
self.assertEqual(bytes.maketrans.__qualname__, 'bytes.maketrans')
# builtin bound instance method:
self.assertEqual([1, 2, 3].append.__qualname__, 'list.append')
self.assertEqual({'foo': 'bar'}.pop.__qualname__, 'dict.pop')
if __name__ == "__main__":
unittest.main()
| 13,001 | 378 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_cgi.py | from test.support import check_warnings
import cgi
import os
import sys
import tempfile
import unittest
import warnings
from collections import namedtuple
from io import StringIO, BytesIO
from test import support
class HackedSysModule:
# The regression test will have real values in sys.argv, which
# will completely confuse the test of the cgi module
argv = []
stdin = sys.stdin
cgi.sys = HackedSysModule()
class ComparableException:
def __init__(self, err):
self.err = err
def __str__(self):
return str(self.err)
def __eq__(self, anExc):
if not isinstance(anExc, Exception):
return NotImplemented
return (self.err.__class__ == anExc.__class__ and
self.err.args == anExc.args)
def __getattr__(self, attr):
return getattr(self.err, attr)
def do_test(buf, method):
env = {}
if method == "GET":
fp = None
env['REQUEST_METHOD'] = 'GET'
env['QUERY_STRING'] = buf
elif method == "POST":
fp = BytesIO(buf.encode('latin-1')) # FieldStorage expects bytes
env['REQUEST_METHOD'] = 'POST'
env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
env['CONTENT_LENGTH'] = str(len(buf))
else:
raise ValueError("unknown method: %s" % method)
try:
return cgi.parse(fp, env, strict_parsing=1)
except Exception as err:
return ComparableException(err)
parse_strict_test_cases = [
("", ValueError("bad query field: ''")),
("&", ValueError("bad query field: ''")),
("&&", ValueError("bad query field: ''")),
# Should the next few really be valid?
("=", {}),
("=&=", {}),
# This rest seem to make sense
("=a", {'': ['a']}),
("&=a", ValueError("bad query field: ''")),
("=a&", ValueError("bad query field: ''")),
("=&a", ValueError("bad query field: 'a'")),
("b=a", {'b': ['a']}),
("b+=a", {'b ': ['a']}),
("a=b=a", {'a': ['b=a']}),
("a=+b=a", {'a': [' b=a']}),
("&b=a", ValueError("bad query field: ''")),
("b&=a", ValueError("bad query field: 'b'")),
("a=a+b&b=b+c", {'a': ['a b'], 'b': ['b c']}),
("a=a+b&a=b+a", {'a': ['a b', 'b a']}),
("x=1&y=2.0&z=2-3.%2b0", {'x': ['1'], 'y': ['2.0'], 'z': ['2-3.+0']}),
("Hbc5161168c542333633315dee1182227:key_store_seqid=400006&cuyer=r&view=bustomer&order_id=0bb2e248638833d48cb7fed300000f1b&expire=964546263&lobale=en-US&kid=130003.300038&ss=env",
{'Hbc5161168c542333633315dee1182227:key_store_seqid': ['400006'],
'cuyer': ['r'],
'expire': ['964546263'],
'kid': ['130003.300038'],
'lobale': ['en-US'],
'order_id': ['0bb2e248638833d48cb7fed300000f1b'],
'ss': ['env'],
'view': ['bustomer'],
}),
("group_id=5470&set=custom&_assigned_to=31392&_status=1&_category=100&SUBMIT=Browse",
{'SUBMIT': ['Browse'],
'_assigned_to': ['31392'],
'_category': ['100'],
'_status': ['1'],
'group_id': ['5470'],
'set': ['custom'],
})
]
def norm(seq):
return sorted(seq, key=repr)
def first_elts(list):
return [p[0] for p in list]
def first_second_elts(list):
return [(p[0], p[1][0]) for p in list]
def gen_result(data, environ):
encoding = 'latin-1'
fake_stdin = BytesIO(data.encode(encoding))
fake_stdin.seek(0)
form = cgi.FieldStorage(fp=fake_stdin, environ=environ, encoding=encoding)
result = {}
for k, v in dict(form).items():
result[k] = isinstance(v, list) and form.getlist(k) or v.value
return result
class CgiTests(unittest.TestCase):
def test_parse_multipart(self):
fp = BytesIO(POSTDATA.encode('latin1'))
env = {'boundary': BOUNDARY.encode('latin1'),
'CONTENT-LENGTH': '558'}
result = cgi.parse_multipart(fp, env)
expected = {'submit': [b' Add '], 'id': [b'1234'],
'file': [b'Testing 123.\n'], 'title': [b'']}
self.assertEqual(result, expected)
def test_fieldstorage_properties(self):
fs = cgi.FieldStorage()
self.assertFalse(fs)
self.assertIn("FieldStorage", repr(fs))
self.assertEqual(list(fs), list(fs.keys()))
fs.list.append(namedtuple('MockFieldStorage', 'name')('fieldvalue'))
self.assertTrue(fs)
def test_fieldstorage_invalid(self):
self.assertRaises(TypeError, cgi.FieldStorage, "not-a-file-obj",
environ={"REQUEST_METHOD":"PUT"})
self.assertRaises(TypeError, cgi.FieldStorage, "foo", "bar")
fs = cgi.FieldStorage(headers={'content-type':'text/plain'})
self.assertRaises(TypeError, bool, fs)
def test_escape(self):
# cgi.escape() is deprecated.
with warnings.catch_warnings():
warnings.filterwarnings('ignore', r'cgi\.escape',
DeprecationWarning)
self.assertEqual("test & string", cgi.escape("test & string"))
self.assertEqual("<test string>", cgi.escape("<test string>"))
self.assertEqual(""test string"", cgi.escape('"test string"', True))
def test_strict(self):
for orig, expect in parse_strict_test_cases:
# Test basic parsing
d = do_test(orig, "GET")
self.assertEqual(d, expect, "Error parsing %s method GET" % repr(orig))
d = do_test(orig, "POST")
self.assertEqual(d, expect, "Error parsing %s method POST" % repr(orig))
env = {'QUERY_STRING': orig}
fs = cgi.FieldStorage(environ=env)
if isinstance(expect, dict):
# test dict interface
self.assertEqual(len(expect), len(fs))
self.assertCountEqual(expect.keys(), fs.keys())
##self.assertEqual(norm(expect.values()), norm(fs.values()))
##self.assertEqual(norm(expect.items()), norm(fs.items()))
self.assertEqual(fs.getvalue("nonexistent field", "default"), "default")
# test individual fields
for key in expect.keys():
expect_val = expect[key]
self.assertIn(key, fs)
if len(expect_val) > 1:
self.assertEqual(fs.getvalue(key), expect_val)
else:
self.assertEqual(fs.getvalue(key), expect_val[0])
def test_separator(self):
parse_semicolon = [
("x=1;y=2.0", {'x': ['1'], 'y': ['2.0']}),
("x=1;y=2.0;z=2-3.%2b0", {'x': ['1'], 'y': ['2.0'], 'z': ['2-3.+0']}),
(";", ValueError("bad query field: ''")),
(";;", ValueError("bad query field: ''")),
("=;a", ValueError("bad query field: 'a'")),
(";b=a", ValueError("bad query field: ''")),
("b;=a", ValueError("bad query field: 'b'")),
("a=a+b;b=b+c", {'a': ['a b'], 'b': ['b c']}),
("a=a+b;a=b+a", {'a': ['a b', 'b a']}),
]
for orig, expect in parse_semicolon:
env = {'QUERY_STRING': orig}
fs = cgi.FieldStorage(separator=';', environ=env)
if isinstance(expect, dict):
for key in expect.keys():
expect_val = expect[key]
self.assertIn(key, fs)
if len(expect_val) > 1:
self.assertEqual(fs.getvalue(key), expect_val)
else:
self.assertEqual(fs.getvalue(key), expect_val[0])
def test_log(self):
cgi.log("Testing")
cgi.logfp = StringIO()
cgi.initlog("%s", "Testing initlog 1")
cgi.log("%s", "Testing log 2")
self.assertEqual(cgi.logfp.getvalue(), "Testing initlog 1\nTesting log 2\n")
if os.path.exists(os.devnull):
cgi.logfp = None
cgi.logfile = os.devnull
cgi.initlog("%s", "Testing log 3")
self.addCleanup(cgi.closelog)
cgi.log("Testing log 4")
def test_fieldstorage_readline(self):
# FieldStorage uses readline, which has the capacity to read all
# contents of the input file into memory; we use readline's size argument
# to prevent that for files that do not contain any newlines in
# non-GET/HEAD requests
class TestReadlineFile:
def __init__(self, file):
self.file = file
self.numcalls = 0
def readline(self, size=None):
self.numcalls += 1
if size:
return self.file.readline(size)
else:
return self.file.readline()
def __getattr__(self, name):
file = self.__dict__['file']
a = getattr(file, name)
if not isinstance(a, int):
setattr(self, name, a)
return a
f = TestReadlineFile(tempfile.TemporaryFile("wb+"))
self.addCleanup(f.close)
f.write(b'x' * 256 * 1024)
f.seek(0)
env = {'REQUEST_METHOD':'PUT'}
fs = cgi.FieldStorage(fp=f, environ=env)
self.addCleanup(fs.file.close)
# if we're not chunking properly, readline is only called twice
# (by read_binary); if we are chunking properly, it will be called 5 times
# as long as the chunksize is 1 << 16.
self.assertGreater(f.numcalls, 2)
f.close()
def test_fieldstorage_multipart(self):
#Test basic FieldStorage multipart parsing
env = {
'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY),
'CONTENT_LENGTH': '558'}
fp = BytesIO(POSTDATA.encode('latin-1'))
fs = cgi.FieldStorage(fp, environ=env, encoding="latin-1")
self.assertEqual(len(fs.list), 4)
expect = [{'name':'id', 'filename':None, 'value':'1234'},
{'name':'title', 'filename':None, 'value':''},
{'name':'file', 'filename':'test.txt', 'value':b'Testing 123.\n'},
{'name':'submit', 'filename':None, 'value':' Add '}]
for x in range(len(fs.list)):
for k, exp in expect[x].items():
got = getattr(fs.list[x], k)
self.assertEqual(got, exp)
def test_fieldstorage_multipart_leading_whitespace(self):
env = {
'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY),
'CONTENT_LENGTH': '560'}
# Add some leading whitespace to our post data that will cause the
# first line to not be the innerboundary.
fp = BytesIO(b"\r\n" + POSTDATA.encode('latin-1'))
fs = cgi.FieldStorage(fp, environ=env, encoding="latin-1")
self.assertEqual(len(fs.list), 4)
expect = [{'name':'id', 'filename':None, 'value':'1234'},
{'name':'title', 'filename':None, 'value':''},
{'name':'file', 'filename':'test.txt', 'value':b'Testing 123.\n'},
{'name':'submit', 'filename':None, 'value':' Add '}]
for x in range(len(fs.list)):
for k, exp in expect[x].items():
got = getattr(fs.list[x], k)
self.assertEqual(got, exp)
def test_fieldstorage_multipart_non_ascii(self):
#Test basic FieldStorage multipart parsing
env = {'REQUEST_METHOD':'POST',
'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY),
'CONTENT_LENGTH':'558'}
for encoding in ['iso-8859-1','utf-8']:
fp = BytesIO(POSTDATA_NON_ASCII.encode(encoding))
fs = cgi.FieldStorage(fp, environ=env,encoding=encoding)
self.assertEqual(len(fs.list), 1)
expect = [{'name':'id', 'filename':None, 'value':'\xe7\xf1\x80'}]
for x in range(len(fs.list)):
for k, exp in expect[x].items():
got = getattr(fs.list[x], k)
self.assertEqual(got, exp)
def test_fieldstorage_multipart_maxline(self):
# Issue #18167
maxline = 1 << 16
self.maxDiff = None
def check(content):
data = """---123
Content-Disposition: form-data; name="upload"; filename="fake.txt"
Content-Type: text/plain
%s
---123--
""".replace('\n', '\r\n') % content
environ = {
'CONTENT_LENGTH': str(len(data)),
'CONTENT_TYPE': 'multipart/form-data; boundary=-123',
'REQUEST_METHOD': 'POST',
}
self.assertEqual(gen_result(data, environ),
{'upload': content.encode('latin1')})
check('x' * (maxline - 1))
check('x' * (maxline - 1) + '\r')
check('x' * (maxline - 1) + '\r' + 'y' * (maxline - 1))
def test_fieldstorage_multipart_w3c(self):
# Test basic FieldStorage multipart parsing (W3C sample)
env = {
'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY_W3),
'CONTENT_LENGTH': str(len(POSTDATA_W3))}
fp = BytesIO(POSTDATA_W3.encode('latin-1'))
fs = cgi.FieldStorage(fp, environ=env, encoding="latin-1")
self.assertEqual(len(fs.list), 2)
self.assertEqual(fs.list[0].name, 'submit-name')
self.assertEqual(fs.list[0].value, 'Larry')
self.assertEqual(fs.list[1].name, 'files')
files = fs.list[1].value
self.assertEqual(len(files), 2)
expect = [{'name': None, 'filename': 'file1.txt', 'value': b'... contents of file1.txt ...'},
{'name': None, 'filename': 'file2.gif', 'value': b'...contents of file2.gif...'}]
for x in range(len(files)):
for k, exp in expect[x].items():
got = getattr(files[x], k)
self.assertEqual(got, exp)
def test_fieldstorage_part_content_length(self):
BOUNDARY = "JfISa01"
POSTDATA = """--JfISa01
Content-Disposition: form-data; name="submit-name"
Content-Length: 5
Larry
--JfISa01"""
env = {
'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY),
'CONTENT_LENGTH': str(len(POSTDATA))}
fp = BytesIO(POSTDATA.encode('latin-1'))
fs = cgi.FieldStorage(fp, environ=env, encoding="latin-1")
self.assertEqual(len(fs.list), 1)
self.assertEqual(fs.list[0].name, 'submit-name')
self.assertEqual(fs.list[0].value, 'Larry')
def test_fieldstorage_as_context_manager(self):
fp = BytesIO(b'x' * 10)
env = {'REQUEST_METHOD': 'PUT'}
with cgi.FieldStorage(fp=fp, environ=env) as fs:
content = fs.file.read()
self.assertFalse(fs.file.closed)
self.assertTrue(fs.file.closed)
self.assertEqual(content, 'x' * 10)
with self.assertRaisesRegex(ValueError, 'I/O operation on closed file'):
fs.file.read()
_qs_result = {
'key1': 'value1',
'key2': ['value2x', 'value2y'],
'key3': 'value3',
'key4': 'value4'
}
def testQSAndUrlEncode(self):
data = "key2=value2x&key3=value3&key4=value4"
environ = {
'CONTENT_LENGTH': str(len(data)),
'CONTENT_TYPE': 'application/x-www-form-urlencoded',
'QUERY_STRING': 'key1=value1&key2=value2y',
'REQUEST_METHOD': 'POST',
}
v = gen_result(data, environ)
self.assertEqual(self._qs_result, v)
def test_max_num_fields(self):
# For application/x-www-form-urlencoded
data = '&'.join(['a=a']*11)
environ = {
'CONTENT_LENGTH': str(len(data)),
'CONTENT_TYPE': 'application/x-www-form-urlencoded',
'REQUEST_METHOD': 'POST',
}
with self.assertRaises(ValueError):
cgi.FieldStorage(
fp=BytesIO(data.encode()),
environ=environ,
max_num_fields=10,
)
# For multipart/form-data
data = """---123
Content-Disposition: form-data; name="a"
3
---123
Content-Type: application/x-www-form-urlencoded
a=4
---123
Content-Type: application/x-www-form-urlencoded
a=5
---123--
"""
environ = {
'CONTENT_LENGTH': str(len(data)),
'CONTENT_TYPE': 'multipart/form-data; boundary=-123',
'QUERY_STRING': 'a=1&a=2',
'REQUEST_METHOD': 'POST',
}
# 2 GET entities
# 1 top level POST entities
# 1 entity within the second POST entity
# 1 entity within the third POST entity
with self.assertRaises(ValueError):
cgi.FieldStorage(
fp=BytesIO(data.encode()),
environ=environ,
max_num_fields=4,
)
cgi.FieldStorage(
fp=BytesIO(data.encode()),
environ=environ,
max_num_fields=5,
)
def testQSAndFormData(self):
data = """---123
Content-Disposition: form-data; name="key2"
value2y
---123
Content-Disposition: form-data; name="key3"
value3
---123
Content-Disposition: form-data; name="key4"
value4
---123--
"""
environ = {
'CONTENT_LENGTH': str(len(data)),
'CONTENT_TYPE': 'multipart/form-data; boundary=-123',
'QUERY_STRING': 'key1=value1&key2=value2x',
'REQUEST_METHOD': 'POST',
}
v = gen_result(data, environ)
self.assertEqual(self._qs_result, v)
def testQSAndFormDataFile(self):
data = """---123
Content-Disposition: form-data; name="key2"
value2y
---123
Content-Disposition: form-data; name="key3"
value3
---123
Content-Disposition: form-data; name="key4"
value4
---123
Content-Disposition: form-data; name="upload"; filename="fake.txt"
Content-Type: text/plain
this is the content of the fake file
---123--
"""
environ = {
'CONTENT_LENGTH': str(len(data)),
'CONTENT_TYPE': 'multipart/form-data; boundary=-123',
'QUERY_STRING': 'key1=value1&key2=value2x',
'REQUEST_METHOD': 'POST',
}
result = self._qs_result.copy()
result.update({
'upload': b'this is the content of the fake file\n'
})
v = gen_result(data, environ)
self.assertEqual(result, v)
def test_deprecated_parse_qs(self):
# this func is moved to urllib.parse, this is just a sanity check
with check_warnings(('cgi.parse_qs is deprecated, use urllib.parse.'
'parse_qs instead', DeprecationWarning)):
self.assertEqual({'a': ['A1'], 'B': ['B3'], 'b': ['B2']},
cgi.parse_qs('a=A1&b=B2&B=B3'))
def test_deprecated_parse_qsl(self):
# this func is moved to urllib.parse, this is just a sanity check
with check_warnings(('cgi.parse_qsl is deprecated, use urllib.parse.'
'parse_qsl instead', DeprecationWarning)):
self.assertEqual([('a', 'A1'), ('b', 'B2'), ('B', 'B3')],
cgi.parse_qsl('a=A1&b=B2&B=B3'))
def test_parse_header(self):
self.assertEqual(
cgi.parse_header("text/plain"),
("text/plain", {}))
self.assertEqual(
cgi.parse_header("text/vnd.just.made.this.up ; "),
("text/vnd.just.made.this.up", {}))
self.assertEqual(
cgi.parse_header("text/plain;charset=us-ascii"),
("text/plain", {"charset": "us-ascii"}))
self.assertEqual(
cgi.parse_header('text/plain ; charset="us-ascii"'),
("text/plain", {"charset": "us-ascii"}))
self.assertEqual(
cgi.parse_header('text/plain ; charset="us-ascii"; another=opt'),
("text/plain", {"charset": "us-ascii", "another": "opt"}))
self.assertEqual(
cgi.parse_header('attachment; filename="silly.txt"'),
("attachment", {"filename": "silly.txt"}))
self.assertEqual(
cgi.parse_header('attachment; filename="strange;name"'),
("attachment", {"filename": "strange;name"}))
self.assertEqual(
cgi.parse_header('attachment; filename="strange;name";size=123;'),
("attachment", {"filename": "strange;name", "size": "123"}))
self.assertEqual(
cgi.parse_header('form-data; name="files"; filename="fo\\"o;bar"'),
("form-data", {"name": "files", "filename": 'fo"o;bar'}))
def test_all(self):
blacklist = {"logfile", "logfp", "initlog", "dolog", "nolog",
"closelog", "log", "maxlen", "valid_boundary"}
support.check__all__(self, cgi, blacklist=blacklist)
BOUNDARY = "---------------------------721837373350705526688164684"
POSTDATA = """-----------------------------721837373350705526688164684
Content-Disposition: form-data; name="id"
1234
-----------------------------721837373350705526688164684
Content-Disposition: form-data; name="title"
-----------------------------721837373350705526688164684
Content-Disposition: form-data; name="file"; filename="test.txt"
Content-Type: text/plain
Testing 123.
-----------------------------721837373350705526688164684
Content-Disposition: form-data; name="submit"
Add\x20
-----------------------------721837373350705526688164684--
"""
POSTDATA_NON_ASCII = """-----------------------------721837373350705526688164684
Content-Disposition: form-data; name="id"
\xe7\xf1\x80
-----------------------------721837373350705526688164684
"""
# http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4
BOUNDARY_W3 = "AaB03x"
POSTDATA_W3 = """--AaB03x
Content-Disposition: form-data; name="submit-name"
Larry
--AaB03x
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=BbC04y
--BbC04y
Content-Disposition: file; filename="file1.txt"
Content-Type: text/plain
... contents of file1.txt ...
--BbC04y
Content-Disposition: file; filename="file2.gif"
Content-Type: image/gif
Content-Transfer-Encoding: binary
...contents of file2.gif...
--BbC04y--
--AaB03x--
"""
if __name__ == '__main__':
unittest.main()
| 22,374 | 613 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_tracemalloc.py | import contextlib
import os
import sys
import cosmo
if cosmo.MODE == "dbg":
import tracemalloc
import unittest
from unittest.mock import patch
from test.support.script_helper import (assert_python_ok, assert_python_failure,
interpreter_requires_environment)
from test import support
try:
import _thread
import threading
except ImportError:
threading = None
try:
import _testcapi
except ImportError:
_testcapi = None
EMPTY_STRING_SIZE = sys.getsizeof(b'')
def get_frames(nframe, lineno_delta):
frames = []
frame = sys._getframe(1)
for index in range(nframe):
code = frame.f_code
lineno = frame.f_lineno + lineno_delta
frames.append((code.co_filename, lineno))
lineno_delta = 0
frame = frame.f_back
if frame is None:
break
return tuple(frames)
def allocate_bytes(size):
nframe = tracemalloc.get_traceback_limit()
bytes_len = (size - EMPTY_STRING_SIZE)
frames = get_frames(nframe, 1)
data = b'x' * bytes_len
return data, tracemalloc.Traceback(frames)
def create_snapshots():
traceback_limit = 2
# _tracemalloc._get_traces() returns a list of (domain, size,
# traceback_frames) tuples. traceback_frames is a tuple of (filename,
# line_number) tuples.
raw_traces = [
(0, 10, (('a.py', 2), ('b.py', 4))),
(0, 10, (('a.py', 2), ('b.py', 4))),
(0, 10, (('a.py', 2), ('b.py', 4))),
(1, 2, (('a.py', 5), ('b.py', 4))),
(2, 66, (('b.py', 1),)),
(3, 7, (('<unknown>', 0),)),
]
snapshot = tracemalloc.Snapshot(raw_traces, traceback_limit)
raw_traces2 = [
(0, 10, (('a.py', 2), ('b.py', 4))),
(0, 10, (('a.py', 2), ('b.py', 4))),
(0, 10, (('a.py', 2), ('b.py', 4))),
(2, 2, (('a.py', 5), ('b.py', 4))),
(2, 5000, (('a.py', 5), ('b.py', 4))),
(4, 400, (('c.py', 578),)),
]
snapshot2 = tracemalloc.Snapshot(raw_traces2, traceback_limit)
return (snapshot, snapshot2)
def frame(filename, lineno):
return tracemalloc._Frame((filename, lineno))
def traceback(*frames):
return tracemalloc.Traceback(frames)
def traceback_lineno(filename, lineno):
return traceback((filename, lineno))
def traceback_filename(filename):
return traceback_lineno(filename, 0)
@unittest.skipUnless(cosmo.MODE == "dbg", "requires APE debug build")
class TestTracemallocEnabled(unittest.TestCase):
def setUp(self):
if tracemalloc.is_tracing():
self.skipTest("tracemalloc must be stopped before the test")
tracemalloc.start(1)
def tearDown(self):
tracemalloc.stop()
def test_get_tracemalloc_memory(self):
data = [allocate_bytes(123) for count in range(1000)]
size = tracemalloc.get_tracemalloc_memory()
self.assertGreaterEqual(size, 0)
tracemalloc.clear_traces()
size2 = tracemalloc.get_tracemalloc_memory()
self.assertGreaterEqual(size2, 0)
self.assertLessEqual(size2, size)
def test_get_object_traceback(self):
tracemalloc.clear_traces()
obj_size = 12345
obj, obj_traceback = allocate_bytes(obj_size)
traceback = tracemalloc.get_object_traceback(obj)
self.assertEqual(traceback, obj_traceback)
def test_set_traceback_limit(self):
obj_size = 10
tracemalloc.stop()
self.assertRaises(ValueError, tracemalloc.start, -1)
tracemalloc.stop()
tracemalloc.start(10)
obj2, obj2_traceback = allocate_bytes(obj_size)
traceback = tracemalloc.get_object_traceback(obj2)
self.assertEqual(len(traceback), 10)
self.assertEqual(traceback, obj2_traceback)
tracemalloc.stop()
tracemalloc.start(1)
obj, obj_traceback = allocate_bytes(obj_size)
traceback = tracemalloc.get_object_traceback(obj)
self.assertEqual(len(traceback), 1)
self.assertEqual(traceback, obj_traceback)
def find_trace(self, traces, traceback):
for trace in traces:
if trace[2] == traceback._frames:
return trace
self.fail("trace not found")
def test_get_traces(self):
tracemalloc.clear_traces()
obj_size = 12345
obj, obj_traceback = allocate_bytes(obj_size)
traces = tracemalloc._get_traces()
trace = self.find_trace(traces, obj_traceback)
self.assertIsInstance(trace, tuple)
domain, size, traceback = trace
self.assertEqual(size, obj_size)
self.assertEqual(traceback, obj_traceback._frames)
tracemalloc.stop()
self.assertEqual(tracemalloc._get_traces(), [])
def test_get_traces_intern_traceback(self):
# dummy wrappers to get more useful and identical frames in the traceback
def allocate_bytes2(size):
return allocate_bytes(size)
def allocate_bytes3(size):
return allocate_bytes2(size)
def allocate_bytes4(size):
return allocate_bytes3(size)
# Ensure that two identical tracebacks are not duplicated
tracemalloc.stop()
tracemalloc.start(4)
obj_size = 123
obj1, obj1_traceback = allocate_bytes4(obj_size)
obj2, obj2_traceback = allocate_bytes4(obj_size)
traces = tracemalloc._get_traces()
trace1 = self.find_trace(traces, obj1_traceback)
trace2 = self.find_trace(traces, obj2_traceback)
domain1, size1, traceback1 = trace1
domain2, size2, traceback2 = trace2
self.assertIs(traceback2, traceback1)
def test_get_traced_memory(self):
# Python allocates some internals objects, so the test must tolerate
# a small difference between the expected size and the real usage
max_error = 2048
# allocate one object
obj_size = 1024 * 1024
tracemalloc.clear_traces()
obj, obj_traceback = allocate_bytes(obj_size)
size, peak_size = tracemalloc.get_traced_memory()
self.assertGreaterEqual(size, obj_size)
self.assertGreaterEqual(peak_size, size)
self.assertLessEqual(size - obj_size, max_error)
self.assertLessEqual(peak_size - size, max_error)
# destroy the object
obj = None
size2, peak_size2 = tracemalloc.get_traced_memory()
self.assertLess(size2, size)
self.assertGreaterEqual(size - size2, obj_size - max_error)
self.assertGreaterEqual(peak_size2, peak_size)
# clear_traces() must reset traced memory counters
tracemalloc.clear_traces()
self.assertEqual(tracemalloc.get_traced_memory(), (0, 0))
# allocate another object
obj, obj_traceback = allocate_bytes(obj_size)
size, peak_size = tracemalloc.get_traced_memory()
self.assertGreaterEqual(size, obj_size)
# stop() also resets traced memory counters
tracemalloc.stop()
self.assertEqual(tracemalloc.get_traced_memory(), (0, 0))
def test_clear_traces(self):
obj, obj_traceback = allocate_bytes(123)
traceback = tracemalloc.get_object_traceback(obj)
self.assertIsNotNone(traceback)
tracemalloc.clear_traces()
traceback2 = tracemalloc.get_object_traceback(obj)
self.assertIsNone(traceback2)
def test_is_tracing(self):
tracemalloc.stop()
self.assertFalse(tracemalloc.is_tracing())
tracemalloc.start()
self.assertTrue(tracemalloc.is_tracing())
def test_snapshot(self):
obj, source = allocate_bytes(123)
# take a snapshot
snapshot = tracemalloc.take_snapshot()
# write on disk
snapshot.dump(support.TESTFN)
self.addCleanup(support.unlink, support.TESTFN)
# load from disk
snapshot2 = tracemalloc.Snapshot.load(support.TESTFN)
self.assertEqual(snapshot2.traces, snapshot.traces)
# tracemalloc must be tracing memory allocations to take a snapshot
tracemalloc.stop()
with self.assertRaises(RuntimeError) as cm:
tracemalloc.take_snapshot()
self.assertEqual(str(cm.exception),
"the tracemalloc module must be tracing memory "
"allocations to take a snapshot")
def test_snapshot_save_attr(self):
# take a snapshot with a new attribute
snapshot = tracemalloc.take_snapshot()
snapshot.test_attr = "new"
snapshot.dump(support.TESTFN)
self.addCleanup(support.unlink, support.TESTFN)
# load() should recreate the attribute
snapshot2 = tracemalloc.Snapshot.load(support.TESTFN)
self.assertEqual(snapshot2.test_attr, "new")
def fork_child(self):
if not tracemalloc.is_tracing():
return 2
obj_size = 12345
obj, obj_traceback = allocate_bytes(obj_size)
traceback = tracemalloc.get_object_traceback(obj)
if traceback is None:
return 3
# everything is fine
return 0
@unittest.skipUnless(hasattr(os, 'fork'), 'need os.fork()')
def test_fork(self):
# check that tracemalloc is still working after fork
pid = os.fork()
if not pid:
# child
exitcode = 1
try:
exitcode = self.fork_child()
finally:
os._exit(exitcode)
else:
pid2, status = os.waitpid(pid, 0)
self.assertTrue(os.WIFEXITED(status))
exitcode = os.WEXITSTATUS(status)
self.assertEqual(exitcode, 0)
@unittest.skipUnless(cosmo.MODE == "dbg", "requires APE debug build")
class TestSnapshot(unittest.TestCase):
maxDiff = 4000
def test_create_snapshot(self):
raw_traces = [(0, 5, (('a.py', 2),))]
with contextlib.ExitStack() as stack:
stack.enter_context(patch.object(tracemalloc, 'is_tracing',
return_value=True))
stack.enter_context(patch.object(tracemalloc, 'get_traceback_limit',
return_value=5))
stack.enter_context(patch.object(tracemalloc, '_get_traces',
return_value=raw_traces))
snapshot = tracemalloc.take_snapshot()
self.assertEqual(snapshot.traceback_limit, 5)
self.assertEqual(len(snapshot.traces), 1)
trace = snapshot.traces[0]
self.assertEqual(trace.size, 5)
self.assertEqual(len(trace.traceback), 1)
self.assertEqual(trace.traceback[0].filename, 'a.py')
self.assertEqual(trace.traceback[0].lineno, 2)
def test_filter_traces(self):
snapshot, snapshot2 = create_snapshots()
filter1 = tracemalloc.Filter(False, "b.py")
filter2 = tracemalloc.Filter(True, "a.py", 2)
filter3 = tracemalloc.Filter(True, "a.py", 5)
original_traces = list(snapshot.traces._traces)
# exclude b.py
snapshot3 = snapshot.filter_traces((filter1,))
self.assertEqual(snapshot3.traces._traces, [
(0, 10, (('a.py', 2), ('b.py', 4))),
(0, 10, (('a.py', 2), ('b.py', 4))),
(0, 10, (('a.py', 2), ('b.py', 4))),
(1, 2, (('a.py', 5), ('b.py', 4))),
(3, 7, (('<unknown>', 0),)),
])
# filter_traces() must not touch the original snapshot
self.assertEqual(snapshot.traces._traces, original_traces)
# only include two lines of a.py
snapshot4 = snapshot3.filter_traces((filter2, filter3))
self.assertEqual(snapshot4.traces._traces, [
(0, 10, (('a.py', 2), ('b.py', 4))),
(0, 10, (('a.py', 2), ('b.py', 4))),
(0, 10, (('a.py', 2), ('b.py', 4))),
(1, 2, (('a.py', 5), ('b.py', 4))),
])
# No filter: just duplicate the snapshot
snapshot5 = snapshot.filter_traces(())
self.assertIsNot(snapshot5, snapshot)
self.assertIsNot(snapshot5.traces, snapshot.traces)
self.assertEqual(snapshot5.traces, snapshot.traces)
self.assertRaises(TypeError, snapshot.filter_traces, filter1)
def test_filter_traces_domain(self):
snapshot, snapshot2 = create_snapshots()
filter1 = tracemalloc.Filter(False, "a.py", domain=1)
filter2 = tracemalloc.Filter(True, "a.py", domain=1)
original_traces = list(snapshot.traces._traces)
# exclude a.py of domain 1
snapshot3 = snapshot.filter_traces((filter1,))
self.assertEqual(snapshot3.traces._traces, [
(0, 10, (('a.py', 2), ('b.py', 4))),
(0, 10, (('a.py', 2), ('b.py', 4))),
(0, 10, (('a.py', 2), ('b.py', 4))),
(2, 66, (('b.py', 1),)),
(3, 7, (('<unknown>', 0),)),
])
# include domain 1
snapshot3 = snapshot.filter_traces((filter1,))
self.assertEqual(snapshot3.traces._traces, [
(0, 10, (('a.py', 2), ('b.py', 4))),
(0, 10, (('a.py', 2), ('b.py', 4))),
(0, 10, (('a.py', 2), ('b.py', 4))),
(2, 66, (('b.py', 1),)),
(3, 7, (('<unknown>', 0),)),
])
def test_filter_traces_domain_filter(self):
snapshot, snapshot2 = create_snapshots()
filter1 = tracemalloc.DomainFilter(False, domain=3)
filter2 = tracemalloc.DomainFilter(True, domain=3)
# exclude domain 2
snapshot3 = snapshot.filter_traces((filter1,))
self.assertEqual(snapshot3.traces._traces, [
(0, 10, (('a.py', 2), ('b.py', 4))),
(0, 10, (('a.py', 2), ('b.py', 4))),
(0, 10, (('a.py', 2), ('b.py', 4))),
(1, 2, (('a.py', 5), ('b.py', 4))),
(2, 66, (('b.py', 1),)),
])
# include domain 2
snapshot3 = snapshot.filter_traces((filter2,))
self.assertEqual(snapshot3.traces._traces, [
(3, 7, (('<unknown>', 0),)),
])
def test_snapshot_group_by_line(self):
snapshot, snapshot2 = create_snapshots()
tb_0 = traceback_lineno('<unknown>', 0)
tb_a_2 = traceback_lineno('a.py', 2)
tb_a_5 = traceback_lineno('a.py', 5)
tb_b_1 = traceback_lineno('b.py', 1)
tb_c_578 = traceback_lineno('c.py', 578)
# stats per file and line
stats1 = snapshot.statistics('lineno')
self.assertEqual(stats1, [
tracemalloc.Statistic(tb_b_1, 66, 1),
tracemalloc.Statistic(tb_a_2, 30, 3),
tracemalloc.Statistic(tb_0, 7, 1),
tracemalloc.Statistic(tb_a_5, 2, 1),
])
# stats per file and line (2)
stats2 = snapshot2.statistics('lineno')
self.assertEqual(stats2, [
tracemalloc.Statistic(tb_a_5, 5002, 2),
tracemalloc.Statistic(tb_c_578, 400, 1),
tracemalloc.Statistic(tb_a_2, 30, 3),
])
# stats diff per file and line
statistics = snapshot2.compare_to(snapshot, 'lineno')
self.assertEqual(statistics, [
tracemalloc.StatisticDiff(tb_a_5, 5002, 5000, 2, 1),
tracemalloc.StatisticDiff(tb_c_578, 400, 400, 1, 1),
tracemalloc.StatisticDiff(tb_b_1, 0, -66, 0, -1),
tracemalloc.StatisticDiff(tb_0, 0, -7, 0, -1),
tracemalloc.StatisticDiff(tb_a_2, 30, 0, 3, 0),
])
def test_snapshot_group_by_file(self):
snapshot, snapshot2 = create_snapshots()
tb_0 = traceback_filename('<unknown>')
tb_a = traceback_filename('a.py')
tb_b = traceback_filename('b.py')
tb_c = traceback_filename('c.py')
# stats per file
stats1 = snapshot.statistics('filename')
self.assertEqual(stats1, [
tracemalloc.Statistic(tb_b, 66, 1),
tracemalloc.Statistic(tb_a, 32, 4),
tracemalloc.Statistic(tb_0, 7, 1),
])
# stats per file (2)
stats2 = snapshot2.statistics('filename')
self.assertEqual(stats2, [
tracemalloc.Statistic(tb_a, 5032, 5),
tracemalloc.Statistic(tb_c, 400, 1),
])
# stats diff per file
diff = snapshot2.compare_to(snapshot, 'filename')
self.assertEqual(diff, [
tracemalloc.StatisticDiff(tb_a, 5032, 5000, 5, 1),
tracemalloc.StatisticDiff(tb_c, 400, 400, 1, 1),
tracemalloc.StatisticDiff(tb_b, 0, -66, 0, -1),
tracemalloc.StatisticDiff(tb_0, 0, -7, 0, -1),
])
def test_snapshot_group_by_traceback(self):
snapshot, snapshot2 = create_snapshots()
# stats per file
tb1 = traceback(('a.py', 2), ('b.py', 4))
tb2 = traceback(('a.py', 5), ('b.py', 4))
tb3 = traceback(('b.py', 1))
tb4 = traceback(('<unknown>', 0))
stats1 = snapshot.statistics('traceback')
self.assertEqual(stats1, [
tracemalloc.Statistic(tb3, 66, 1),
tracemalloc.Statistic(tb1, 30, 3),
tracemalloc.Statistic(tb4, 7, 1),
tracemalloc.Statistic(tb2, 2, 1),
])
# stats per file (2)
tb5 = traceback(('c.py', 578))
stats2 = snapshot2.statistics('traceback')
self.assertEqual(stats2, [
tracemalloc.Statistic(tb2, 5002, 2),
tracemalloc.Statistic(tb5, 400, 1),
tracemalloc.Statistic(tb1, 30, 3),
])
# stats diff per file
diff = snapshot2.compare_to(snapshot, 'traceback')
self.assertEqual(diff, [
tracemalloc.StatisticDiff(tb2, 5002, 5000, 2, 1),
tracemalloc.StatisticDiff(tb5, 400, 400, 1, 1),
tracemalloc.StatisticDiff(tb3, 0, -66, 0, -1),
tracemalloc.StatisticDiff(tb4, 0, -7, 0, -1),
tracemalloc.StatisticDiff(tb1, 30, 0, 3, 0),
])
self.assertRaises(ValueError,
snapshot.statistics, 'traceback', cumulative=True)
def test_snapshot_group_by_cumulative(self):
snapshot, snapshot2 = create_snapshots()
tb_0 = traceback_filename('<unknown>')
tb_a = traceback_filename('a.py')
tb_b = traceback_filename('b.py')
tb_a_2 = traceback_lineno('a.py', 2)
tb_a_5 = traceback_lineno('a.py', 5)
tb_b_1 = traceback_lineno('b.py', 1)
tb_b_4 = traceback_lineno('b.py', 4)
# per file
stats = snapshot.statistics('filename', True)
self.assertEqual(stats, [
tracemalloc.Statistic(tb_b, 98, 5),
tracemalloc.Statistic(tb_a, 32, 4),
tracemalloc.Statistic(tb_0, 7, 1),
])
# per line
stats = snapshot.statistics('lineno', True)
self.assertEqual(stats, [
tracemalloc.Statistic(tb_b_1, 66, 1),
tracemalloc.Statistic(tb_b_4, 32, 4),
tracemalloc.Statistic(tb_a_2, 30, 3),
tracemalloc.Statistic(tb_0, 7, 1),
tracemalloc.Statistic(tb_a_5, 2, 1),
])
def test_trace_format(self):
snapshot, snapshot2 = create_snapshots()
trace = snapshot.traces[0]
self.assertEqual(str(trace), 'a.py:2: 10 B')
traceback = trace.traceback
self.assertEqual(str(traceback), 'a.py:2')
frame = traceback[0]
self.assertEqual(str(frame), 'a.py:2')
def test_statistic_format(self):
snapshot, snapshot2 = create_snapshots()
stats = snapshot.statistics('lineno')
stat = stats[0]
self.assertEqual(str(stat),
'b.py:1: size=66 B, count=1, average=66 B')
def test_statistic_diff_format(self):
snapshot, snapshot2 = create_snapshots()
stats = snapshot2.compare_to(snapshot, 'lineno')
stat = stats[0]
self.assertEqual(str(stat),
'a.py:5: size=5002 B (+5000 B), count=2 (+1), average=2501 B')
def test_slices(self):
snapshot, snapshot2 = create_snapshots()
self.assertEqual(snapshot.traces[:2],
(snapshot.traces[0], snapshot.traces[1]))
traceback = snapshot.traces[0].traceback
self.assertEqual(traceback[:2],
(traceback[0], traceback[1]))
def test_format_traceback(self):
snapshot, snapshot2 = create_snapshots()
def getline(filename, lineno):
return ' <%s, %s>' % (filename, lineno)
with unittest.mock.patch('tracemalloc.linecache.getline',
side_effect=getline):
tb = snapshot.traces[0].traceback
self.assertEqual(tb.format(),
[' File "a.py", line 2',
' <a.py, 2>',
' File "b.py", line 4',
' <b.py, 4>'])
self.assertEqual(tb.format(limit=1),
[' File "a.py", line 2',
' <a.py, 2>'])
self.assertEqual(tb.format(limit=-1),
[])
@unittest.skipUnless(cosmo.MODE == "dbg", "requires APE debug build")
class TestFilters(unittest.TestCase):
maxDiff = 2048
def test_filter_attributes(self):
# test default values
f = tracemalloc.Filter(True, "abc")
self.assertEqual(f.inclusive, True)
self.assertEqual(f.filename_pattern, "abc")
self.assertIsNone(f.lineno)
self.assertEqual(f.all_frames, False)
# test custom values
f = tracemalloc.Filter(False, "test.py", 123, True)
self.assertEqual(f.inclusive, False)
self.assertEqual(f.filename_pattern, "test.py")
self.assertEqual(f.lineno, 123)
self.assertEqual(f.all_frames, True)
# parameters passed by keyword
f = tracemalloc.Filter(inclusive=False, filename_pattern="test.py", lineno=123, all_frames=True)
self.assertEqual(f.inclusive, False)
self.assertEqual(f.filename_pattern, "test.py")
self.assertEqual(f.lineno, 123)
self.assertEqual(f.all_frames, True)
# read-only attribute
self.assertRaises(AttributeError, setattr, f, "filename_pattern", "abc")
def test_filter_match(self):
# filter without line number
f = tracemalloc.Filter(True, "abc")
self.assertTrue(f._match_frame("abc", 0))
self.assertTrue(f._match_frame("abc", 5))
self.assertTrue(f._match_frame("abc", 10))
self.assertFalse(f._match_frame("12356", 0))
self.assertFalse(f._match_frame("12356", 5))
self.assertFalse(f._match_frame("12356", 10))
f = tracemalloc.Filter(False, "abc")
self.assertFalse(f._match_frame("abc", 0))
self.assertFalse(f._match_frame("abc", 5))
self.assertFalse(f._match_frame("abc", 10))
self.assertTrue(f._match_frame("12356", 0))
self.assertTrue(f._match_frame("12356", 5))
self.assertTrue(f._match_frame("12356", 10))
# filter with line number > 0
f = tracemalloc.Filter(True, "abc", 5)
self.assertFalse(f._match_frame("abc", 0))
self.assertTrue(f._match_frame("abc", 5))
self.assertFalse(f._match_frame("abc", 10))
self.assertFalse(f._match_frame("12356", 0))
self.assertFalse(f._match_frame("12356", 5))
self.assertFalse(f._match_frame("12356", 10))
f = tracemalloc.Filter(False, "abc", 5)
self.assertTrue(f._match_frame("abc", 0))
self.assertFalse(f._match_frame("abc", 5))
self.assertTrue(f._match_frame("abc", 10))
self.assertTrue(f._match_frame("12356", 0))
self.assertTrue(f._match_frame("12356", 5))
self.assertTrue(f._match_frame("12356", 10))
# filter with line number 0
f = tracemalloc.Filter(True, "abc", 0)
self.assertTrue(f._match_frame("abc", 0))
self.assertFalse(f._match_frame("abc", 5))
self.assertFalse(f._match_frame("abc", 10))
self.assertFalse(f._match_frame("12356", 0))
self.assertFalse(f._match_frame("12356", 5))
self.assertFalse(f._match_frame("12356", 10))
f = tracemalloc.Filter(False, "abc", 0)
self.assertFalse(f._match_frame("abc", 0))
self.assertTrue(f._match_frame("abc", 5))
self.assertTrue(f._match_frame("abc", 10))
self.assertTrue(f._match_frame("12356", 0))
self.assertTrue(f._match_frame("12356", 5))
self.assertTrue(f._match_frame("12356", 10))
def test_filter_match_filename(self):
def fnmatch(inclusive, filename, pattern):
f = tracemalloc.Filter(inclusive, pattern)
return f._match_frame(filename, 0)
self.assertTrue(fnmatch(True, "abc", "abc"))
self.assertFalse(fnmatch(True, "12356", "abc"))
self.assertFalse(fnmatch(True, "<unknown>", "abc"))
self.assertFalse(fnmatch(False, "abc", "abc"))
self.assertTrue(fnmatch(False, "12356", "abc"))
self.assertTrue(fnmatch(False, "<unknown>", "abc"))
def test_filter_match_filename_joker(self):
def fnmatch(filename, pattern):
filter = tracemalloc.Filter(True, pattern)
return filter._match_frame(filename, 0)
# empty string
self.assertFalse(fnmatch('abc', ''))
self.assertFalse(fnmatch('', 'abc'))
self.assertTrue(fnmatch('', ''))
self.assertTrue(fnmatch('', '*'))
# no *
self.assertTrue(fnmatch('abc', 'abc'))
self.assertFalse(fnmatch('abc', 'abcd'))
self.assertFalse(fnmatch('abc', 'def'))
# a*
self.assertTrue(fnmatch('abc', 'a*'))
self.assertTrue(fnmatch('abc', 'abc*'))
self.assertFalse(fnmatch('abc', 'b*'))
self.assertFalse(fnmatch('abc', 'abcd*'))
# a*b
self.assertTrue(fnmatch('abc', 'a*c'))
self.assertTrue(fnmatch('abcdcx', 'a*cx'))
self.assertFalse(fnmatch('abb', 'a*c'))
self.assertFalse(fnmatch('abcdce', 'a*cx'))
# a*b*c
self.assertTrue(fnmatch('abcde', 'a*c*e'))
self.assertTrue(fnmatch('abcbdefeg', 'a*bd*eg'))
self.assertFalse(fnmatch('abcdd', 'a*c*e'))
self.assertFalse(fnmatch('abcbdefef', 'a*bd*eg'))
# replace .pyc suffix with .py
self.assertTrue(fnmatch('a.pyc', 'a.py'))
self.assertTrue(fnmatch('a.py', 'a.pyc'))
if os.name == 'nt':
# case insensitive
self.assertTrue(fnmatch('aBC', 'ABc'))
self.assertTrue(fnmatch('aBcDe', 'Ab*dE'))
self.assertTrue(fnmatch('a.pyc', 'a.PY'))
self.assertTrue(fnmatch('a.py', 'a.PYC'))
else:
# case sensitive
self.assertFalse(fnmatch('aBC', 'ABc'))
self.assertFalse(fnmatch('aBcDe', 'Ab*dE'))
self.assertFalse(fnmatch('a.pyc', 'a.PY'))
self.assertFalse(fnmatch('a.py', 'a.PYC'))
if os.name == 'nt':
# normalize alternate separator "/" to the standard separator "\"
self.assertTrue(fnmatch(r'a/b', r'a\b'))
self.assertTrue(fnmatch(r'a\b', r'a/b'))
self.assertTrue(fnmatch(r'a/b\c', r'a\b/c'))
self.assertTrue(fnmatch(r'a/b/c', r'a\b\c'))
else:
# there is no alternate separator
self.assertFalse(fnmatch(r'a/b', r'a\b'))
self.assertFalse(fnmatch(r'a\b', r'a/b'))
self.assertFalse(fnmatch(r'a/b\c', r'a\b/c'))
self.assertFalse(fnmatch(r'a/b/c', r'a\b\c'))
# as of 3.5, .pyo is no longer munged to .py
self.assertFalse(fnmatch('a.pyo', 'a.py'))
def test_filter_match_trace(self):
t1 = (("a.py", 2), ("b.py", 3))
t2 = (("b.py", 4), ("b.py", 5))
t3 = (("c.py", 5), ('<unknown>', 0))
unknown = (('<unknown>', 0),)
f = tracemalloc.Filter(True, "b.py", all_frames=True)
self.assertTrue(f._match_traceback(t1))
self.assertTrue(f._match_traceback(t2))
self.assertFalse(f._match_traceback(t3))
self.assertFalse(f._match_traceback(unknown))
f = tracemalloc.Filter(True, "b.py", all_frames=False)
self.assertFalse(f._match_traceback(t1))
self.assertTrue(f._match_traceback(t2))
self.assertFalse(f._match_traceback(t3))
self.assertFalse(f._match_traceback(unknown))
f = tracemalloc.Filter(False, "b.py", all_frames=True)
self.assertFalse(f._match_traceback(t1))
self.assertFalse(f._match_traceback(t2))
self.assertTrue(f._match_traceback(t3))
self.assertTrue(f._match_traceback(unknown))
f = tracemalloc.Filter(False, "b.py", all_frames=False)
self.assertTrue(f._match_traceback(t1))
self.assertFalse(f._match_traceback(t2))
self.assertTrue(f._match_traceback(t3))
self.assertTrue(f._match_traceback(unknown))
f = tracemalloc.Filter(False, "<unknown>", all_frames=False)
self.assertTrue(f._match_traceback(t1))
self.assertTrue(f._match_traceback(t2))
self.assertTrue(f._match_traceback(t3))
self.assertFalse(f._match_traceback(unknown))
f = tracemalloc.Filter(True, "<unknown>", all_frames=True)
self.assertFalse(f._match_traceback(t1))
self.assertFalse(f._match_traceback(t2))
self.assertTrue(f._match_traceback(t3))
self.assertTrue(f._match_traceback(unknown))
f = tracemalloc.Filter(False, "<unknown>", all_frames=True)
self.assertTrue(f._match_traceback(t1))
self.assertTrue(f._match_traceback(t2))
self.assertFalse(f._match_traceback(t3))
self.assertFalse(f._match_traceback(unknown))
@unittest.skipUnless(cosmo.MODE == "dbg", "requires APE debug build")
class TestCommandLine(unittest.TestCase):
def test_env_var_disabled_by_default(self):
# not tracing by default
code = 'import tracemalloc; print(tracemalloc.is_tracing())'
ok, stdout, stderr = assert_python_ok('-c', code)
stdout = stdout.rstrip()
self.assertEqual(stdout, b'False')
@unittest.skipIf(interpreter_requires_environment(),
'Cannot run -E tests when PYTHON env vars are required.')
def test_env_var_ignored_with_E(self):
"""PYTHON* environment variables must be ignored when -E is present."""
code = 'import tracemalloc; print(tracemalloc.is_tracing())'
ok, stdout, stderr = assert_python_ok('-E', '-c', code, PYTHONTRACEMALLOC='1')
stdout = stdout.rstrip()
self.assertEqual(stdout, b'False')
def test_env_var_enabled_at_startup(self):
# tracing at startup
code = 'import tracemalloc; print(tracemalloc.is_tracing())'
ok, stdout, stderr = assert_python_ok('-c', code, PYTHONTRACEMALLOC='1')
stdout = stdout.rstrip()
self.assertEqual(stdout, b'True')
def test_env_limit(self):
# start and set the number of frames
code = 'import tracemalloc; print(tracemalloc.get_traceback_limit())'
ok, stdout, stderr = assert_python_ok('-c', code, PYTHONTRACEMALLOC='10')
stdout = stdout.rstrip()
self.assertEqual(stdout, b'10')
def test_env_var_invalid(self):
for nframe in (-1, 0, 2**30):
with self.subTest(nframe=nframe):
with support.SuppressCrashReport():
ok, stdout, stderr = assert_python_failure(
'-c', 'pass',
PYTHONTRACEMALLOC=str(nframe))
self.assertIn(b'PYTHONTRACEMALLOC: invalid '
b'number of frames',
stderr)
def test_sys_xoptions(self):
for xoptions, nframe in (
('tracemalloc', 1),
('tracemalloc=1', 1),
('tracemalloc=15', 15),
):
with self.subTest(xoptions=xoptions, nframe=nframe):
code = 'import tracemalloc; print(tracemalloc.get_traceback_limit())'
ok, stdout, stderr = assert_python_ok('-X', xoptions, '-c', code)
stdout = stdout.rstrip()
self.assertEqual(stdout, str(nframe).encode('ascii'))
def test_sys_xoptions_invalid(self):
for nframe in (-1, 0, 2**30):
with self.subTest(nframe=nframe):
with support.SuppressCrashReport():
args = ('-X', 'tracemalloc=%s' % nframe, '-c', 'pass')
ok, stdout, stderr = assert_python_failure(*args)
self.assertIn(b'-X tracemalloc=NFRAME: invalid '
b'number of frames',
stderr)
@unittest.skipIf(_testcapi is None, 'need _testcapi')
def test_pymem_alloc0(self):
# Issue #21639: Check that PyMem_Malloc(0) with tracemalloc enabled
# does not crash.
code = 'import _testcapi; _testcapi.test_pymem_alloc0(); 1'
assert_python_ok('-X', 'tracemalloc', '-c', code)
@unittest.skipUnless(cosmo.MODE == "dbg", "requires APE debug build")
@unittest.skipIf(_testcapi is None, 'need _testcapi')
class TestCAPI(unittest.TestCase):
maxDiff = 80 * 20
def setUp(self):
if tracemalloc.is_tracing():
self.skipTest("tracemalloc must be stopped before the test")
self.domain = 5
self.size = 123
self.obj = allocate_bytes(self.size)[0]
# for the type "object", id(obj) is the address of its memory block.
# This type is not tracked by the garbage collector
self.ptr = id(self.obj)
def tearDown(self):
tracemalloc.stop()
def get_traceback(self):
frames = _testcapi.tracemalloc_get_traceback(self.domain, self.ptr)
if frames is not None:
return tracemalloc.Traceback(frames)
else:
return None
def track(self, release_gil=False, nframe=1):
frames = get_frames(nframe, 2)
_testcapi.tracemalloc_track(self.domain, self.ptr, self.size,
release_gil)
return frames
def untrack(self):
_testcapi.tracemalloc_untrack(self.domain, self.ptr)
def get_traced_memory(self):
# Get the traced size in the domain
snapshot = tracemalloc.take_snapshot()
domain_filter = tracemalloc.DomainFilter(True, self.domain)
snapshot = snapshot.filter_traces([domain_filter])
return sum(trace.size for trace in snapshot.traces)
def check_track(self, release_gil):
nframe = 5
tracemalloc.start(nframe)
size = tracemalloc.get_traced_memory()[0]
frames = self.track(release_gil, nframe)
self.assertEqual(self.get_traceback(),
tracemalloc.Traceback(frames))
self.assertEqual(self.get_traced_memory(), self.size)
def test_track(self):
self.check_track(False)
def test_track_without_gil(self):
# check that calling _PyTraceMalloc_Track() without holding the GIL
# works too
self.check_track(True)
def test_track_already_tracked(self):
nframe = 5
tracemalloc.start(nframe)
# track a first time
self.track()
# calling _PyTraceMalloc_Track() must remove the old trace and add
# a new trace with the new traceback
frames = self.track(nframe=nframe)
self.assertEqual(self.get_traceback(),
tracemalloc.Traceback(frames))
def test_untrack(self):
tracemalloc.start()
self.track()
self.assertIsNotNone(self.get_traceback())
self.assertEqual(self.get_traced_memory(), self.size)
# untrack must remove the trace
self.untrack()
self.assertIsNone(self.get_traceback())
self.assertEqual(self.get_traced_memory(), 0)
# calling _PyTraceMalloc_Untrack() multiple times must not crash
self.untrack()
self.untrack()
def test_stop_track(self):
tracemalloc.start()
tracemalloc.stop()
with self.assertRaises(RuntimeError):
self.track()
self.assertIsNone(self.get_traceback())
def test_stop_untrack(self):
tracemalloc.start()
self.track()
tracemalloc.stop()
with self.assertRaises(RuntimeError):
self.untrack()
def test_main():
support.run_unittest(
TestTracemallocEnabled,
TestSnapshot,
TestFilters,
TestCommandLine,
TestCAPI,
)
if __name__ == "__main__":
test_main()
| 36,658 | 1,003 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_syslog.py |
from test import support
syslog = support.import_module("syslog") #skip if not supported
import unittest
# XXX(nnorwitz): This test sucks. I don't know of a platform independent way
# to verify that the messages were really logged.
# The only purpose of this test is to verify the code doesn't crash or leak.
class Test(unittest.TestCase):
def test_openlog(self):
syslog.openlog('python')
# Issue #6697.
self.assertRaises(UnicodeEncodeError, syslog.openlog, '\uD800')
def test_syslog(self):
syslog.openlog('python')
syslog.syslog('test message from python test_syslog')
syslog.syslog(syslog.LOG_ERR, 'test error from python test_syslog')
def test_closelog(self):
syslog.openlog('python')
syslog.closelog()
def test_setlogmask(self):
syslog.setlogmask(syslog.LOG_DEBUG)
def test_log_mask(self):
syslog.LOG_MASK(syslog.LOG_INFO)
def test_log_upto(self):
syslog.LOG_UPTO(syslog.LOG_INFO)
def test_openlog_noargs(self):
syslog.openlog()
syslog.syslog('test message from python test_syslog')
if __name__ == "__main__":
unittest.main()
if __name__ == "PYOBJ.COM":
import syslog
| 1,225 | 44 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/_test_multiprocessing.py | #
# Unit tests for the multiprocessing package
#
import unittest
import queue as pyqueue
import contextlib
import time
import io
import itertools
import sys
import os
import gc
import errno
import signal
import array
import socket
import random
import logging
import struct
import operator
import weakref
from test import support
import test.support.script_helper
# Skip tests if _multiprocessing wasn't built.
_multiprocessing = support.import_module('_multiprocessing')
# Skip tests if sem_open implementation is broken.
support.import_module('multiprocessing.synchronize')
# import threading after _multiprocessing to raise a more relevant error
# message: "No module named _multiprocessing". _multiprocessing is not compiled
# without thread support.
import threading
import multiprocessing.connection
import multiprocessing.dummy
import multiprocessing.heap
import multiprocessing.managers
import multiprocessing.pool
import multiprocessing.queues
from multiprocessing import util
try:
from multiprocessing import reduction
HAS_REDUCTION = reduction.HAVE_SEND_HANDLE
except ImportError:
HAS_REDUCTION = False
try:
from multiprocessing.sharedctypes import Value, copy
HAS_SHAREDCTYPES = True
except ImportError:
HAS_SHAREDCTYPES = False
try:
import msvcrt
except ImportError:
msvcrt = None
#
#
#
def latin(s):
return s.encode('latin')
def close_queue(queue):
if isinstance(queue, multiprocessing.queues.Queue):
queue.close()
queue.join_thread()
#
# Constants
#
LOG_LEVEL = util.SUBWARNING
#LOG_LEVEL = logging.DEBUG
DELTA = 0.1
CHECK_TIMINGS = False # making true makes tests take a lot longer
# and can sometimes cause some non-serious
# failures because some calls block a bit
# longer than expected
if CHECK_TIMINGS:
TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.82, 0.35, 1.4
else:
TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.1, 0.1, 0.1
HAVE_GETVALUE = not getattr(_multiprocessing,
'HAVE_BROKEN_SEM_GETVALUE', False)
WIN32 = (sys.platform == "win32")
from multiprocessing.connection import wait
def wait_for_handle(handle, timeout):
if timeout is not None and timeout < 0.0:
timeout = None
return wait([handle], timeout)
try:
MAXFD = os.sysconf("SC_OPEN_MAX")
except:
MAXFD = 256
# To speed up tests when using the forkserver, we can preload these:
PRELOAD = ['__main__', 'test.test_multiprocessing_forkserver']
#
# Some tests require ctypes
#
try:
from ctypes import Structure, c_int, c_double
except ImportError:
Structure = object
c_int = c_double = None
def check_enough_semaphores():
"""Check that the system supports enough semaphores to run the test."""
# minimum number of semaphores available according to POSIX
nsems_min = 256
try:
nsems = os.sysconf("SC_SEM_NSEMS_MAX")
except (AttributeError, ValueError):
# sysconf not available or setting not available
return
if nsems == -1 or nsems >= nsems_min:
return
raise unittest.SkipTest("The OS doesn't support enough semaphores "
"to run the test (required: %d)." % nsems_min)
#
# Creates a wrapper for a function which records the time it takes to finish
#
class TimingWrapper(object):
def __init__(self, func):
self.func = func
self.elapsed = None
def __call__(self, *args, **kwds):
t = time.time()
try:
return self.func(*args, **kwds)
finally:
self.elapsed = time.time() - t
#
# Base class for test cases
#
class BaseTestCase(object):
ALLOWED_TYPES = ('processes', 'manager', 'threads')
def assertTimingAlmostEqual(self, a, b):
if CHECK_TIMINGS:
self.assertAlmostEqual(a, b, 1)
def assertReturnsIfImplemented(self, value, func, *args):
try:
res = func(*args)
except NotImplementedError:
pass
else:
return self.assertEqual(value, res)
# For the sanity of Windows users, rather than crashing or freezing in
# multiple ways.
def __reduce__(self, *args):
raise NotImplementedError("shouldn't try to pickle a test case")
__reduce_ex__ = __reduce__
#
# Return the value of a semaphore
#
def get_value(self):
try:
return self.get_value()
except AttributeError:
try:
return self._Semaphore__value
except AttributeError:
try:
return self._value
except AttributeError:
raise NotImplementedError
#
# Testcases
#
class DummyCallable:
def __call__(self, q, c):
assert isinstance(c, DummyCallable)
q.put(5)
class _TestProcess(BaseTestCase):
ALLOWED_TYPES = ('processes', 'threads')
def test_current(self):
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
current = self.current_process()
authkey = current.authkey
self.assertTrue(current.is_alive())
self.assertTrue(not current.daemon)
self.assertIsInstance(authkey, bytes)
self.assertTrue(len(authkey) > 0)
self.assertEqual(current.ident, os.getpid())
self.assertEqual(current.exitcode, None)
def test_daemon_argument(self):
if self.TYPE == "threads":
self.skipTest('test not appropriate for {}'.format(self.TYPE))
# By default uses the current process's daemon flag.
proc0 = self.Process(target=self._test)
self.assertEqual(proc0.daemon, self.current_process().daemon)
proc1 = self.Process(target=self._test, daemon=True)
self.assertTrue(proc1.daemon)
proc2 = self.Process(target=self._test, daemon=False)
self.assertFalse(proc2.daemon)
@classmethod
def _test(cls, q, *args, **kwds):
current = cls.current_process()
q.put(args)
q.put(kwds)
q.put(current.name)
if cls.TYPE != 'threads':
q.put(bytes(current.authkey))
q.put(current.pid)
def test_process(self):
q = self.Queue(1)
e = self.Event()
args = (q, 1, 2)
kwargs = {'hello':23, 'bye':2.54}
name = 'SomeProcess'
p = self.Process(
target=self._test, args=args, kwargs=kwargs, name=name
)
p.daemon = True
current = self.current_process()
if self.TYPE != 'threads':
self.assertEqual(p.authkey, current.authkey)
self.assertEqual(p.is_alive(), False)
self.assertEqual(p.daemon, True)
self.assertNotIn(p, self.active_children())
self.assertTrue(type(self.active_children()) is list)
self.assertEqual(p.exitcode, None)
p.start()
self.assertEqual(p.exitcode, None)
self.assertEqual(p.is_alive(), True)
self.assertIn(p, self.active_children())
self.assertEqual(q.get(), args[1:])
self.assertEqual(q.get(), kwargs)
self.assertEqual(q.get(), p.name)
if self.TYPE != 'threads':
self.assertEqual(q.get(), current.authkey)
self.assertEqual(q.get(), p.pid)
p.join()
self.assertEqual(p.exitcode, 0)
self.assertEqual(p.is_alive(), False)
self.assertNotIn(p, self.active_children())
close_queue(q)
@classmethod
def _test_terminate(cls):
time.sleep(100)
def test_terminate(self):
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
p = self.Process(target=self._test_terminate)
p.daemon = True
p.start()
self.assertEqual(p.is_alive(), True)
self.assertIn(p, self.active_children())
self.assertEqual(p.exitcode, None)
join = TimingWrapper(p.join)
self.assertEqual(join(0), None)
self.assertTimingAlmostEqual(join.elapsed, 0.0)
self.assertEqual(p.is_alive(), True)
self.assertEqual(join(-1), None)
self.assertTimingAlmostEqual(join.elapsed, 0.0)
self.assertEqual(p.is_alive(), True)
# XXX maybe terminating too soon causes the problems on Gentoo...
time.sleep(1)
p.terminate()
if hasattr(signal, 'alarm'):
# On the Gentoo buildbot waitpid() often seems to block forever.
# We use alarm() to interrupt it if it blocks for too long.
def handler(*args):
raise RuntimeError('join took too long: %s' % p)
old_handler = signal.signal(signal.SIGALRM, handler)
try:
signal.alarm(10)
self.assertEqual(join(), None)
finally:
signal.alarm(0)
signal.signal(signal.SIGALRM, old_handler)
else:
self.assertEqual(join(), None)
self.assertTimingAlmostEqual(join.elapsed, 0.0)
self.assertEqual(p.is_alive(), False)
self.assertNotIn(p, self.active_children())
p.join()
# XXX sometimes get p.exitcode == 0 on Windows ...
#self.assertEqual(p.exitcode, -signal.SIGTERM)
def test_cpu_count(self):
try:
cpus = multiprocessing.cpu_count()
except NotImplementedError:
cpus = 1
self.assertTrue(type(cpus) is int)
self.assertTrue(cpus >= 1)
def test_active_children(self):
self.assertEqual(type(self.active_children()), list)
p = self.Process(target=time.sleep, args=(DELTA,))
self.assertNotIn(p, self.active_children())
p.daemon = True
p.start()
self.assertIn(p, self.active_children())
p.join()
self.assertNotIn(p, self.active_children())
@classmethod
def _test_recursion(cls, wconn, id):
wconn.send(id)
if len(id) < 2:
for i in range(2):
p = cls.Process(
target=cls._test_recursion, args=(wconn, id+[i])
)
p.start()
p.join()
def test_recursion(self):
rconn, wconn = self.Pipe(duplex=False)
self._test_recursion(wconn, [])
time.sleep(DELTA)
result = []
while rconn.poll():
result.append(rconn.recv())
expected = [
[],
[0],
[0, 0],
[0, 1],
[1],
[1, 0],
[1, 1]
]
self.assertEqual(result, expected)
@classmethod
def _test_sentinel(cls, event):
event.wait(10.0)
def test_sentinel(self):
if self.TYPE == "threads":
self.skipTest('test not appropriate for {}'.format(self.TYPE))
event = self.Event()
p = self.Process(target=self._test_sentinel, args=(event,))
with self.assertRaises(ValueError):
p.sentinel
p.start()
self.addCleanup(p.join)
sentinel = p.sentinel
self.assertIsInstance(sentinel, int)
self.assertFalse(wait_for_handle(sentinel, timeout=0.0))
event.set()
p.join()
self.assertTrue(wait_for_handle(sentinel, timeout=1))
def test_lose_target_ref(self):
c = DummyCallable()
wr = weakref.ref(c)
q = self.Queue()
p = self.Process(target=c, args=(q, c))
del c
p.start()
p.join()
self.assertIs(wr(), None)
self.assertEqual(q.get(), 5)
close_queue(q)
@classmethod
def _test_error_on_stdio_flush(self, evt, break_std_streams={}):
for stream_name, action in break_std_streams.items():
if action == 'close':
stream = io.StringIO()
stream.close()
else:
assert action == 'remove'
stream = None
setattr(sys, stream_name, None)
evt.set()
def test_error_on_stdio_flush_1(self):
# Check that Process works with broken standard streams
streams = [io.StringIO(), None]
streams[0].close()
for stream_name in ('stdout', 'stderr'):
for stream in streams:
old_stream = getattr(sys, stream_name)
setattr(sys, stream_name, stream)
try:
evt = self.Event()
proc = self.Process(target=self._test_error_on_stdio_flush,
args=(evt,))
proc.start()
proc.join()
self.assertTrue(evt.is_set())
self.assertEqual(proc.exitcode, 0)
finally:
setattr(sys, stream_name, old_stream)
def test_error_on_stdio_flush_2(self):
# Same as test_error_on_stdio_flush_1(), but standard streams are
# broken by the child process
for stream_name in ('stdout', 'stderr'):
for action in ('close', 'remove'):
old_stream = getattr(sys, stream_name)
try:
evt = self.Event()
proc = self.Process(target=self._test_error_on_stdio_flush,
args=(evt, {stream_name: action}))
proc.start()
proc.join()
self.assertTrue(evt.is_set())
self.assertEqual(proc.exitcode, 0)
finally:
setattr(sys, stream_name, old_stream)
@classmethod
def _sleep_and_set_event(self, evt, delay=0.0):
time.sleep(delay)
evt.set()
def check_forkserver_death(self, signum):
# bpo-31308: if the forkserver process has died, we should still
# be able to create and run new Process instances (the forkserver
# is implicitly restarted).
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
sm = multiprocessing.get_start_method()
if sm != 'forkserver':
# The fork method by design inherits all fds from the parent,
# trying to go against it is a lost battle
self.skipTest('test not appropriate for {}'.format(sm))
from multiprocessing.forkserver import _forkserver
_forkserver.ensure_running()
# First process sleeps 500 ms
delay = 0.5
evt = self.Event()
proc = self.Process(target=self._sleep_and_set_event, args=(evt, delay))
proc.start()
pid = _forkserver._forkserver_pid
os.kill(pid, signum)
# give time to the fork server to die and time to proc to complete
time.sleep(delay * 2.0)
evt2 = self.Event()
proc2 = self.Process(target=self._sleep_and_set_event, args=(evt2,))
proc2.start()
proc2.join()
self.assertTrue(evt2.is_set())
self.assertEqual(proc2.exitcode, 0)
proc.join()
self.assertTrue(evt.is_set())
self.assertIn(proc.exitcode, (0, 255))
def test_forkserver_sigint(self):
# Catchable signal
self.check_forkserver_death(signal.SIGINT)
def test_forkserver_sigkill(self):
# Uncatchable signal
if os.name != 'nt':
self.check_forkserver_death(signal.SIGKILL)
#
#
#
class _UpperCaser(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
self.child_conn, self.parent_conn = multiprocessing.Pipe()
def run(self):
self.parent_conn.close()
for s in iter(self.child_conn.recv, None):
self.child_conn.send(s.upper())
self.child_conn.close()
def submit(self, s):
assert type(s) is str
self.parent_conn.send(s)
return self.parent_conn.recv()
def stop(self):
self.parent_conn.send(None)
self.parent_conn.close()
self.child_conn.close()
class _TestSubclassingProcess(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def test_subclassing(self):
uppercaser = _UpperCaser()
uppercaser.daemon = True
uppercaser.start()
self.assertEqual(uppercaser.submit('hello'), 'HELLO')
self.assertEqual(uppercaser.submit('world'), 'WORLD')
uppercaser.stop()
uppercaser.join()
def test_stderr_flush(self):
# sys.stderr is flushed at process shutdown (issue #13812)
if self.TYPE == "threads":
self.skipTest('test not appropriate for {}'.format(self.TYPE))
testfn = support.TESTFN
self.addCleanup(support.unlink, testfn)
proc = self.Process(target=self._test_stderr_flush, args=(testfn,))
proc.start()
proc.join()
with open(testfn, 'r') as f:
err = f.read()
# The whole traceback was printed
self.assertIn("ZeroDivisionError", err)
self.assertIn("test_multiprocessing.py", err)
self.assertIn("1/0 # MARKER", err)
@classmethod
def _test_stderr_flush(cls, testfn):
fd = os.open(testfn, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
sys.stderr = open(fd, 'w', closefd=False)
1/0 # MARKER
@classmethod
def _test_sys_exit(cls, reason, testfn):
fd = os.open(testfn, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
sys.stderr = open(fd, 'w', closefd=False)
sys.exit(reason)
def test_sys_exit(self):
# See Issue 13854
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
testfn = support.TESTFN
self.addCleanup(support.unlink, testfn)
for reason in (
[1, 2, 3],
'ignore this',
):
p = self.Process(target=self._test_sys_exit, args=(reason, testfn))
p.daemon = True
p.start()
p.join(5)
self.assertEqual(p.exitcode, 1)
with open(testfn, 'r') as f:
content = f.read()
self.assertEqual(content.rstrip(), str(reason))
os.unlink(testfn)
for reason in (True, False, 8):
p = self.Process(target=sys.exit, args=(reason,))
p.daemon = True
p.start()
p.join(5)
self.assertEqual(p.exitcode, reason)
#
#
#
def queue_empty(q):
if hasattr(q, 'empty'):
return q.empty()
else:
return q.qsize() == 0
def queue_full(q, maxsize):
if hasattr(q, 'full'):
return q.full()
else:
return q.qsize() == maxsize
class _TestQueue(BaseTestCase):
@classmethod
def _test_put(cls, queue, child_can_start, parent_can_continue):
child_can_start.wait()
for i in range(6):
queue.get()
parent_can_continue.set()
def test_put(self):
MAXSIZE = 6
queue = self.Queue(maxsize=MAXSIZE)
child_can_start = self.Event()
parent_can_continue = self.Event()
proc = self.Process(
target=self._test_put,
args=(queue, child_can_start, parent_can_continue)
)
proc.daemon = True
proc.start()
self.assertEqual(queue_empty(queue), True)
self.assertEqual(queue_full(queue, MAXSIZE), False)
queue.put(1)
queue.put(2, True)
queue.put(3, True, None)
queue.put(4, False)
queue.put(5, False, None)
queue.put_nowait(6)
# the values may be in buffer but not yet in pipe so sleep a bit
time.sleep(DELTA)
self.assertEqual(queue_empty(queue), False)
self.assertEqual(queue_full(queue, MAXSIZE), True)
put = TimingWrapper(queue.put)
put_nowait = TimingWrapper(queue.put_nowait)
self.assertRaises(pyqueue.Full, put, 7, False)
self.assertTimingAlmostEqual(put.elapsed, 0)
self.assertRaises(pyqueue.Full, put, 7, False, None)
self.assertTimingAlmostEqual(put.elapsed, 0)
self.assertRaises(pyqueue.Full, put_nowait, 7)
self.assertTimingAlmostEqual(put_nowait.elapsed, 0)
self.assertRaises(pyqueue.Full, put, 7, True, TIMEOUT1)
self.assertTimingAlmostEqual(put.elapsed, TIMEOUT1)
self.assertRaises(pyqueue.Full, put, 7, False, TIMEOUT2)
self.assertTimingAlmostEqual(put.elapsed, 0)
self.assertRaises(pyqueue.Full, put, 7, True, timeout=TIMEOUT3)
self.assertTimingAlmostEqual(put.elapsed, TIMEOUT3)
child_can_start.set()
parent_can_continue.wait()
self.assertEqual(queue_empty(queue), True)
self.assertEqual(queue_full(queue, MAXSIZE), False)
proc.join()
close_queue(queue)
@classmethod
def _test_get(cls, queue, child_can_start, parent_can_continue):
child_can_start.wait()
#queue.put(1)
queue.put(2)
queue.put(3)
queue.put(4)
queue.put(5)
parent_can_continue.set()
def test_get(self):
queue = self.Queue()
child_can_start = self.Event()
parent_can_continue = self.Event()
proc = self.Process(
target=self._test_get,
args=(queue, child_can_start, parent_can_continue)
)
proc.daemon = True
proc.start()
self.assertEqual(queue_empty(queue), True)
child_can_start.set()
parent_can_continue.wait()
time.sleep(DELTA)
self.assertEqual(queue_empty(queue), False)
# Hangs unexpectedly, remove for now
#self.assertEqual(queue.get(), 1)
self.assertEqual(queue.get(True, None), 2)
self.assertEqual(queue.get(True), 3)
self.assertEqual(queue.get(timeout=1), 4)
self.assertEqual(queue.get_nowait(), 5)
self.assertEqual(queue_empty(queue), True)
get = TimingWrapper(queue.get)
get_nowait = TimingWrapper(queue.get_nowait)
self.assertRaises(pyqueue.Empty, get, False)
self.assertTimingAlmostEqual(get.elapsed, 0)
self.assertRaises(pyqueue.Empty, get, False, None)
self.assertTimingAlmostEqual(get.elapsed, 0)
self.assertRaises(pyqueue.Empty, get_nowait)
self.assertTimingAlmostEqual(get_nowait.elapsed, 0)
self.assertRaises(pyqueue.Empty, get, True, TIMEOUT1)
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1)
self.assertRaises(pyqueue.Empty, get, False, TIMEOUT2)
self.assertTimingAlmostEqual(get.elapsed, 0)
self.assertRaises(pyqueue.Empty, get, timeout=TIMEOUT3)
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT3)
proc.join()
close_queue(queue)
@classmethod
def _test_fork(cls, queue):
for i in range(10, 20):
queue.put(i)
# note that at this point the items may only be buffered, so the
# process cannot shutdown until the feeder thread has finished
# pushing items onto the pipe.
def test_fork(self):
# Old versions of Queue would fail to create a new feeder
# thread for a forked process if the original process had its
# own feeder thread. This test checks that this no longer
# happens.
queue = self.Queue()
# put items on queue so that main process starts a feeder thread
for i in range(10):
queue.put(i)
# wait to make sure thread starts before we fork a new process
time.sleep(DELTA)
# fork process
p = self.Process(target=self._test_fork, args=(queue,))
p.daemon = True
p.start()
# check that all expected items are in the queue
for i in range(20):
self.assertEqual(queue.get(), i)
self.assertRaises(pyqueue.Empty, queue.get, False)
p.join()
close_queue(queue)
def test_qsize(self):
q = self.Queue()
try:
self.assertEqual(q.qsize(), 0)
except NotImplementedError:
self.skipTest('qsize method not implemented')
q.put(1)
self.assertEqual(q.qsize(), 1)
q.put(5)
self.assertEqual(q.qsize(), 2)
q.get()
self.assertEqual(q.qsize(), 1)
q.get()
self.assertEqual(q.qsize(), 0)
close_queue(q)
@classmethod
def _test_task_done(cls, q):
for obj in iter(q.get, None):
time.sleep(DELTA)
q.task_done()
def test_task_done(self):
queue = self.JoinableQueue()
workers = [self.Process(target=self._test_task_done, args=(queue,))
for i in range(4)]
for p in workers:
p.daemon = True
p.start()
for i in range(10):
queue.put(i)
queue.join()
for p in workers:
queue.put(None)
for p in workers:
p.join()
close_queue(queue)
def test_no_import_lock_contention(self):
with support.temp_cwd():
module_name = 'imported_by_an_imported_module'
with open(module_name + '.py', 'w') as f:
f.write("""if 1:
import multiprocessing
q = multiprocessing.Queue()
q.put('knock knock')
q.get(timeout=3)
q.close()
del q
""")
with support.DirsOnSysPath(os.getcwd()):
try:
__import__(module_name)
except pyqueue.Empty:
self.fail("Probable regression on import lock contention;"
" see Issue #22853")
def test_timeout(self):
q = multiprocessing.Queue()
start = time.time()
self.assertRaises(pyqueue.Empty, q.get, True, 0.200)
delta = time.time() - start
# bpo-30317: Tolerate a delta of 100 ms because of the bad clock
# resolution on Windows (usually 15.6 ms). x86 Windows7 3.x once
# failed because the delta was only 135.8 ms.
self.assertGreaterEqual(delta, 0.100)
close_queue(q)
def test_queue_feeder_donot_stop_onexc(self):
# bpo-30414: verify feeder handles exceptions correctly
if self.TYPE != 'processes':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
class NotSerializable(object):
def __reduce__(self):
raise AttributeError
with support.captured_stderr():
q = self.Queue()
q.put(NotSerializable())
q.put(True)
# bpo-30595: use a timeout of 1 second for slow buildbots
self.assertTrue(q.get(timeout=1.0))
close_queue(q)
#
#
#
class _TestLock(BaseTestCase):
def test_lock(self):
lock = self.Lock()
self.assertEqual(lock.acquire(), True)
self.assertEqual(lock.acquire(False), False)
self.assertEqual(lock.release(), None)
self.assertRaises((ValueError, threading.ThreadError), lock.release)
def test_rlock(self):
lock = self.RLock()
self.assertEqual(lock.acquire(), True)
self.assertEqual(lock.acquire(), True)
self.assertEqual(lock.acquire(), True)
self.assertEqual(lock.release(), None)
self.assertEqual(lock.release(), None)
self.assertEqual(lock.release(), None)
self.assertRaises((AssertionError, RuntimeError), lock.release)
def test_lock_context(self):
with self.Lock():
pass
class _TestSemaphore(BaseTestCase):
def _test_semaphore(self, sem):
self.assertReturnsIfImplemented(2, get_value, sem)
self.assertEqual(sem.acquire(), True)
self.assertReturnsIfImplemented(1, get_value, sem)
self.assertEqual(sem.acquire(), True)
self.assertReturnsIfImplemented(0, get_value, sem)
self.assertEqual(sem.acquire(False), False)
self.assertReturnsIfImplemented(0, get_value, sem)
self.assertEqual(sem.release(), None)
self.assertReturnsIfImplemented(1, get_value, sem)
self.assertEqual(sem.release(), None)
self.assertReturnsIfImplemented(2, get_value, sem)
def test_semaphore(self):
sem = self.Semaphore(2)
self._test_semaphore(sem)
self.assertEqual(sem.release(), None)
self.assertReturnsIfImplemented(3, get_value, sem)
self.assertEqual(sem.release(), None)
self.assertReturnsIfImplemented(4, get_value, sem)
def test_bounded_semaphore(self):
sem = self.BoundedSemaphore(2)
self._test_semaphore(sem)
# Currently fails on OS/X
#if HAVE_GETVALUE:
# self.assertRaises(ValueError, sem.release)
# self.assertReturnsIfImplemented(2, get_value, sem)
def test_timeout(self):
if self.TYPE != 'processes':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
sem = self.Semaphore(0)
acquire = TimingWrapper(sem.acquire)
self.assertEqual(acquire(False), False)
self.assertTimingAlmostEqual(acquire.elapsed, 0.0)
self.assertEqual(acquire(False, None), False)
self.assertTimingAlmostEqual(acquire.elapsed, 0.0)
self.assertEqual(acquire(False, TIMEOUT1), False)
self.assertTimingAlmostEqual(acquire.elapsed, 0)
self.assertEqual(acquire(True, TIMEOUT2), False)
self.assertTimingAlmostEqual(acquire.elapsed, TIMEOUT2)
self.assertEqual(acquire(timeout=TIMEOUT3), False)
self.assertTimingAlmostEqual(acquire.elapsed, TIMEOUT3)
class _TestCondition(BaseTestCase):
@classmethod
def f(cls, cond, sleeping, woken, timeout=None):
cond.acquire()
sleeping.release()
cond.wait(timeout)
woken.release()
cond.release()
def check_invariant(self, cond):
# this is only supposed to succeed when there are no sleepers
if self.TYPE == 'processes':
try:
sleepers = (cond._sleeping_count.get_value() -
cond._woken_count.get_value())
self.assertEqual(sleepers, 0)
self.assertEqual(cond._wait_semaphore.get_value(), 0)
except NotImplementedError:
pass
def test_notify(self):
cond = self.Condition()
sleeping = self.Semaphore(0)
woken = self.Semaphore(0)
p = self.Process(target=self.f, args=(cond, sleeping, woken))
p.daemon = True
p.start()
self.addCleanup(p.join)
p = threading.Thread(target=self.f, args=(cond, sleeping, woken))
p.daemon = True
p.start()
self.addCleanup(p.join)
# wait for both children to start sleeping
sleeping.acquire()
sleeping.acquire()
# check no process/thread has woken up
time.sleep(DELTA)
self.assertReturnsIfImplemented(0, get_value, woken)
# wake up one process/thread
cond.acquire()
cond.notify()
cond.release()
# check one process/thread has woken up
time.sleep(DELTA)
self.assertReturnsIfImplemented(1, get_value, woken)
# wake up another
cond.acquire()
cond.notify()
cond.release()
# check other has woken up
time.sleep(DELTA)
self.assertReturnsIfImplemented(2, get_value, woken)
# check state is not mucked up
self.check_invariant(cond)
p.join()
def test_notify_all(self):
cond = self.Condition()
sleeping = self.Semaphore(0)
woken = self.Semaphore(0)
# start some threads/processes which will timeout
for i in range(3):
p = self.Process(target=self.f,
args=(cond, sleeping, woken, TIMEOUT1))
p.daemon = True
p.start()
self.addCleanup(p.join)
t = threading.Thread(target=self.f,
args=(cond, sleeping, woken, TIMEOUT1))
t.daemon = True
t.start()
self.addCleanup(t.join)
# wait for them all to sleep
for i in range(6):
sleeping.acquire()
# check they have all timed out
for i in range(6):
woken.acquire()
self.assertReturnsIfImplemented(0, get_value, woken)
# check state is not mucked up
self.check_invariant(cond)
# start some more threads/processes
for i in range(3):
p = self.Process(target=self.f, args=(cond, sleeping, woken))
p.daemon = True
p.start()
self.addCleanup(p.join)
t = threading.Thread(target=self.f, args=(cond, sleeping, woken))
t.daemon = True
t.start()
self.addCleanup(t.join)
# wait for them to all sleep
for i in range(6):
sleeping.acquire()
# check no process/thread has woken up
time.sleep(DELTA)
self.assertReturnsIfImplemented(0, get_value, woken)
# wake them all up
cond.acquire()
cond.notify_all()
cond.release()
# check they have all woken
for i in range(10):
try:
if get_value(woken) == 6:
break
except NotImplementedError:
break
time.sleep(DELTA)
self.assertReturnsIfImplemented(6, get_value, woken)
# check state is not mucked up
self.check_invariant(cond)
def test_timeout(self):
cond = self.Condition()
wait = TimingWrapper(cond.wait)
cond.acquire()
res = wait(TIMEOUT1)
cond.release()
self.assertEqual(res, False)
self.assertTimingAlmostEqual(wait.elapsed, TIMEOUT1)
@classmethod
def _test_waitfor_f(cls, cond, state):
with cond:
state.value = 0
cond.notify()
result = cond.wait_for(lambda : state.value==4)
if not result or state.value != 4:
sys.exit(1)
@unittest.skipUnless(HAS_SHAREDCTYPES, 'needs sharedctypes')
def test_waitfor(self):
# based on test in test/lock_tests.py
cond = self.Condition()
state = self.Value('i', -1)
p = self.Process(target=self._test_waitfor_f, args=(cond, state))
p.daemon = True
p.start()
with cond:
result = cond.wait_for(lambda : state.value==0)
self.assertTrue(result)
self.assertEqual(state.value, 0)
for i in range(4):
time.sleep(0.01)
with cond:
state.value += 1
cond.notify()
p.join(5)
self.assertFalse(p.is_alive())
self.assertEqual(p.exitcode, 0)
@classmethod
def _test_waitfor_timeout_f(cls, cond, state, success, sem):
sem.release()
with cond:
expected = 0.1
dt = time.time()
result = cond.wait_for(lambda : state.value==4, timeout=expected)
dt = time.time() - dt
# borrow logic in assertTimeout() from test/lock_tests.py
if not result and expected * 0.6 < dt < expected * 10.0:
success.value = True
@unittest.skipUnless(HAS_SHAREDCTYPES, 'needs sharedctypes')
def test_waitfor_timeout(self):
# based on test in test/lock_tests.py
cond = self.Condition()
state = self.Value('i', 0)
success = self.Value('i', False)
sem = self.Semaphore(0)
p = self.Process(target=self._test_waitfor_timeout_f,
args=(cond, state, success, sem))
p.daemon = True
p.start()
self.assertTrue(sem.acquire(timeout=10))
# Only increment 3 times, so state == 4 is never reached.
for i in range(3):
time.sleep(0.01)
with cond:
state.value += 1
cond.notify()
p.join(5)
self.assertTrue(success.value)
@classmethod
def _test_wait_result(cls, c, pid):
with c:
c.notify()
time.sleep(1)
if pid is not None:
os.kill(pid, signal.SIGINT)
def test_wait_result(self):
if isinstance(self, ProcessesMixin) and sys.platform != 'win32':
pid = os.getpid()
else:
pid = None
c = self.Condition()
with c:
self.assertFalse(c.wait(0))
self.assertFalse(c.wait(0.1))
p = self.Process(target=self._test_wait_result, args=(c, pid))
p.start()
self.assertTrue(c.wait(60))
if pid is not None:
self.assertRaises(KeyboardInterrupt, c.wait, 60)
p.join()
class _TestEvent(BaseTestCase):
@classmethod
def _test_event(cls, event):
time.sleep(TIMEOUT2)
event.set()
def test_event(self):
event = self.Event()
wait = TimingWrapper(event.wait)
# Removed temporarily, due to API shear, this does not
# work with threading._Event objects. is_set == isSet
self.assertEqual(event.is_set(), False)
# Removed, threading.Event.wait() will return the value of the __flag
# instead of None. API Shear with the semaphore backed mp.Event
self.assertEqual(wait(0.0), False)
self.assertTimingAlmostEqual(wait.elapsed, 0.0)
self.assertEqual(wait(TIMEOUT1), False)
self.assertTimingAlmostEqual(wait.elapsed, TIMEOUT1)
event.set()
# See note above on the API differences
self.assertEqual(event.is_set(), True)
self.assertEqual(wait(), True)
self.assertTimingAlmostEqual(wait.elapsed, 0.0)
self.assertEqual(wait(TIMEOUT1), True)
self.assertTimingAlmostEqual(wait.elapsed, 0.0)
# self.assertEqual(event.is_set(), True)
event.clear()
#self.assertEqual(event.is_set(), False)
p = self.Process(target=self._test_event, args=(event,))
p.daemon = True
p.start()
self.assertEqual(wait(), True)
p.join()
#
# Tests for Barrier - adapted from tests in test/lock_tests.py
#
# Many of the tests for threading.Barrier use a list as an atomic
# counter: a value is appended to increment the counter, and the
# length of the list gives the value. We use the class DummyList
# for the same purpose.
class _DummyList(object):
def __init__(self):
wrapper = multiprocessing.heap.BufferWrapper(struct.calcsize('i'))
lock = multiprocessing.Lock()
self.__setstate__((wrapper, lock))
self._lengthbuf[0] = 0
def __setstate__(self, state):
(self._wrapper, self._lock) = state
self._lengthbuf = self._wrapper.create_memoryview().cast('i')
def __getstate__(self):
return (self._wrapper, self._lock)
def append(self, _):
with self._lock:
self._lengthbuf[0] += 1
def __len__(self):
with self._lock:
return self._lengthbuf[0]
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, namespace, f, args, 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.args = args
self.n = n
self.started = namespace.DummyList()
self.finished = namespace.DummyList()
self._can_exit = namespace.Event()
if not wait_before_exit:
self._can_exit.set()
threads = []
for i in range(n):
p = namespace.Process(target=self.task)
p.daemon = True
p.start()
threads.append(p)
def finalize(threads):
for p in threads:
p.join()
self._finalizer = weakref.finalize(self, finalize, threads)
def task(self):
pid = os.getpid()
self.started.append(pid)
try:
self.f(*self.args)
finally:
self.finished.append(pid)
self._can_exit.wait(30)
assert self._can_exit.is_set()
def wait_for_started(self):
while len(self.started) < self.n:
_wait()
def wait_for_finished(self):
while len(self.finished) < self.n:
_wait()
def do_finish(self):
self._can_exit.set()
def close(self):
self._finalizer()
class AppendTrue(object):
def __init__(self, obj):
self.obj = obj
def __call__(self):
self.obj.append(True)
class _TestBarrier(BaseTestCase):
"""
Tests for Barrier objects.
"""
N = 5
defaultTimeout = 30.0 # XXX Slow Windows buildbots need generous timeout
def setUp(self):
self.barrier = self.Barrier(self.N, timeout=self.defaultTimeout)
def tearDown(self):
self.barrier.abort()
self.barrier = None
def DummyList(self):
if self.TYPE == 'threads':
return []
elif self.TYPE == 'manager':
return self.manager.list()
else:
return _DummyList()
def run_threads(self, f, args):
b = Bunch(self, f, args, self.N-1)
try:
f(*args)
b.wait_for_finished()
finally:
b.close()
@classmethod
def multipass(cls, barrier, results, n):
m = barrier.parties
assert m == cls.N
for i in range(n):
results[0].append(True)
assert len(results[1]) == i * m
barrier.wait()
results[1].append(True)
assert len(results[0]) == (i + 1) * m
barrier.wait()
try:
assert barrier.n_waiting == 0
except NotImplementedError:
pass
assert not barrier.broken
def test_barrier(self, passes=1):
"""
Test that a barrier is passed in lockstep
"""
results = [self.DummyList(), self.DummyList()]
self.run_threads(self.multipass, (self.barrier, results, passes))
def test_barrier_10(self):
"""
Test that a barrier works for 10 consecutive runs
"""
return self.test_barrier(10)
@classmethod
def _test_wait_return_f(cls, barrier, queue):
res = barrier.wait()
queue.put(res)
def test_wait_return(self):
"""
test the return value from barrier.wait
"""
queue = self.Queue()
self.run_threads(self._test_wait_return_f, (self.barrier, queue))
results = [queue.get() for i in range(self.N)]
self.assertEqual(results.count(0), 1)
close_queue(queue)
@classmethod
def _test_action_f(cls, barrier, results):
barrier.wait()
if len(results) != 1:
raise RuntimeError
def test_action(self):
"""
Test the 'action' callback
"""
results = self.DummyList()
barrier = self.Barrier(self.N, action=AppendTrue(results))
self.run_threads(self._test_action_f, (barrier, results))
self.assertEqual(len(results), 1)
@classmethod
def _test_abort_f(cls, barrier, results1, results2):
try:
i = barrier.wait()
if i == cls.N//2:
raise RuntimeError
barrier.wait()
results1.append(True)
except threading.BrokenBarrierError:
results2.append(True)
except RuntimeError:
barrier.abort()
def test_abort(self):
"""
Test that an abort will put the barrier in a broken state
"""
results1 = self.DummyList()
results2 = self.DummyList()
self.run_threads(self._test_abort_f,
(self.barrier, results1, results2))
self.assertEqual(len(results1), 0)
self.assertEqual(len(results2), self.N-1)
self.assertTrue(self.barrier.broken)
@classmethod
def _test_reset_f(cls, barrier, results1, results2, results3):
i = barrier.wait()
if i == cls.N//2:
# Wait until the other threads are all in the barrier.
while barrier.n_waiting < cls.N-1:
time.sleep(0.001)
barrier.reset()
else:
try:
barrier.wait()
results1.append(True)
except threading.BrokenBarrierError:
results2.append(True)
# Now, pass the barrier again
barrier.wait()
results3.append(True)
def test_reset(self):
"""
Test that a 'reset' on a barrier frees the waiting threads
"""
results1 = self.DummyList()
results2 = self.DummyList()
results3 = self.DummyList()
self.run_threads(self._test_reset_f,
(self.barrier, results1, results2, results3))
self.assertEqual(len(results1), 0)
self.assertEqual(len(results2), self.N-1)
self.assertEqual(len(results3), self.N)
@classmethod
def _test_abort_and_reset_f(cls, barrier, barrier2,
results1, results2, results3):
try:
i = barrier.wait()
if i == cls.N//2:
raise RuntimeError
barrier.wait()
results1.append(True)
except threading.BrokenBarrierError:
results2.append(True)
except RuntimeError:
barrier.abort()
# 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() == cls.N//2:
barrier.reset()
barrier2.wait()
barrier.wait()
results3.append(True)
def test_abort_and_reset(self):
"""
Test that a barrier can be reset after being broken.
"""
results1 = self.DummyList()
results2 = self.DummyList()
results3 = self.DummyList()
barrier2 = self.Barrier(self.N)
self.run_threads(self._test_abort_and_reset_f,
(self.barrier, barrier2, results1, results2, results3))
self.assertEqual(len(results1), 0)
self.assertEqual(len(results2), self.N-1)
self.assertEqual(len(results3), self.N)
@classmethod
def _test_timeout_f(cls, barrier, results):
i = barrier.wait()
if i == cls.N//2:
# One thread is late!
time.sleep(1.0)
try:
barrier.wait(0.5)
except threading.BrokenBarrierError:
results.append(True)
def test_timeout(self):
"""
Test wait(timeout)
"""
results = self.DummyList()
self.run_threads(self._test_timeout_f, (self.barrier, results))
self.assertEqual(len(results), self.barrier.parties)
@classmethod
def _test_default_timeout_f(cls, barrier, results):
i = barrier.wait(cls.defaultTimeout)
if i == cls.N//2:
# One thread is later than the default timeout
time.sleep(1.0)
try:
barrier.wait()
except threading.BrokenBarrierError:
results.append(True)
def test_default_timeout(self):
"""
Test the barrier's default timeout
"""
barrier = self.Barrier(self.N, timeout=0.5)
results = self.DummyList()
self.run_threads(self._test_default_timeout_f, (barrier, results))
self.assertEqual(len(results), barrier.parties)
def test_single_thread(self):
b = self.Barrier(1)
b.wait()
b.wait()
@classmethod
def _test_thousand_f(cls, barrier, passes, conn, lock):
for i in range(passes):
barrier.wait()
with lock:
conn.send(i)
def test_thousand(self):
if self.TYPE == 'manager':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
passes = 1000
lock = self.Lock()
conn, child_conn = self.Pipe(False)
for j in range(self.N):
p = self.Process(target=self._test_thousand_f,
args=(self.barrier, passes, child_conn, lock))
p.start()
self.addCleanup(p.join)
for i in range(passes):
for j in range(self.N):
self.assertEqual(conn.recv(), i)
#
#
#
class _TestValue(BaseTestCase):
ALLOWED_TYPES = ('processes',)
codes_values = [
('i', 4343, 24234),
('d', 3.625, -4.25),
('h', -232, 234),
('c', latin('x'), latin('y'))
]
def setUp(self):
if not HAS_SHAREDCTYPES:
self.skipTest("requires multiprocessing.sharedctypes")
@classmethod
def _test(cls, values):
for sv, cv in zip(values, cls.codes_values):
sv.value = cv[2]
def test_value(self, raw=False):
if raw:
values = [self.RawValue(code, value)
for code, value, _ in self.codes_values]
else:
values = [self.Value(code, value)
for code, value, _ in self.codes_values]
for sv, cv in zip(values, self.codes_values):
self.assertEqual(sv.value, cv[1])
proc = self.Process(target=self._test, args=(values,))
proc.daemon = True
proc.start()
proc.join()
for sv, cv in zip(values, self.codes_values):
self.assertEqual(sv.value, cv[2])
def test_rawvalue(self):
self.test_value(raw=True)
def test_getobj_getlock(self):
val1 = self.Value('i', 5)
lock1 = val1.get_lock()
obj1 = val1.get_obj()
val2 = self.Value('i', 5, lock=None)
lock2 = val2.get_lock()
obj2 = val2.get_obj()
lock = self.Lock()
val3 = self.Value('i', 5, lock=lock)
lock3 = val3.get_lock()
obj3 = val3.get_obj()
self.assertEqual(lock, lock3)
arr4 = self.Value('i', 5, lock=False)
self.assertFalse(hasattr(arr4, 'get_lock'))
self.assertFalse(hasattr(arr4, 'get_obj'))
self.assertRaises(AttributeError, self.Value, 'i', 5, lock='navalue')
arr5 = self.RawValue('i', 5)
self.assertFalse(hasattr(arr5, 'get_lock'))
self.assertFalse(hasattr(arr5, 'get_obj'))
class _TestArray(BaseTestCase):
ALLOWED_TYPES = ('processes',)
@classmethod
def f(cls, seq):
for i in range(1, len(seq)):
seq[i] += seq[i-1]
@unittest.skipIf(c_int is None, "requires _ctypes")
def test_array(self, raw=False):
seq = [680, 626, 934, 821, 150, 233, 548, 982, 714, 831]
if raw:
arr = self.RawArray('i', seq)
else:
arr = self.Array('i', seq)
self.assertEqual(len(arr), len(seq))
self.assertEqual(arr[3], seq[3])
self.assertEqual(list(arr[2:7]), list(seq[2:7]))
arr[4:8] = seq[4:8] = array.array('i', [1, 2, 3, 4])
self.assertEqual(list(arr[:]), seq)
self.f(seq)
p = self.Process(target=self.f, args=(arr,))
p.daemon = True
p.start()
p.join()
self.assertEqual(list(arr[:]), seq)
@unittest.skipIf(c_int is None, "requires _ctypes")
def test_array_from_size(self):
size = 10
# Test for zeroing (see issue #11675).
# The repetition below strengthens the test by increasing the chances
# of previously allocated non-zero memory being used for the new array
# on the 2nd and 3rd loops.
for _ in range(3):
arr = self.Array('i', size)
self.assertEqual(len(arr), size)
self.assertEqual(list(arr), [0] * size)
arr[:] = range(10)
self.assertEqual(list(arr), list(range(10)))
del arr
@unittest.skipIf(c_int is None, "requires _ctypes")
def test_rawarray(self):
self.test_array(raw=True)
@unittest.skipIf(c_int is None, "requires _ctypes")
def test_getobj_getlock_obj(self):
arr1 = self.Array('i', list(range(10)))
lock1 = arr1.get_lock()
obj1 = arr1.get_obj()
arr2 = self.Array('i', list(range(10)), lock=None)
lock2 = arr2.get_lock()
obj2 = arr2.get_obj()
lock = self.Lock()
arr3 = self.Array('i', list(range(10)), lock=lock)
lock3 = arr3.get_lock()
obj3 = arr3.get_obj()
self.assertEqual(lock, lock3)
arr4 = self.Array('i', range(10), lock=False)
self.assertFalse(hasattr(arr4, 'get_lock'))
self.assertFalse(hasattr(arr4, 'get_obj'))
self.assertRaises(AttributeError,
self.Array, 'i', range(10), lock='notalock')
arr5 = self.RawArray('i', range(10))
self.assertFalse(hasattr(arr5, 'get_lock'))
self.assertFalse(hasattr(arr5, 'get_obj'))
#
#
#
class _TestContainers(BaseTestCase):
ALLOWED_TYPES = ('manager',)
def test_list(self):
a = self.list(list(range(10)))
self.assertEqual(a[:], list(range(10)))
b = self.list()
self.assertEqual(b[:], [])
b.extend(list(range(5)))
self.assertEqual(b[:], list(range(5)))
self.assertEqual(b[2], 2)
self.assertEqual(b[2:10], [2,3,4])
b *= 2
self.assertEqual(b[:], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4])
self.assertEqual(b + [5, 6], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6])
self.assertEqual(a[:], list(range(10)))
d = [a, b]
e = self.list(d)
self.assertEqual(
[element[:] for element in e],
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]]
)
f = self.list([a])
a.append('hello')
self.assertEqual(f[0][:], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'hello'])
def test_list_iter(self):
a = self.list(list(range(10)))
it = iter(a)
self.assertEqual(list(it), list(range(10)))
self.assertEqual(list(it), []) # exhausted
# list modified during iteration
it = iter(a)
a[0] = 100
self.assertEqual(next(it), 100)
def test_list_proxy_in_list(self):
a = self.list([self.list(range(3)) for _i in range(3)])
self.assertEqual([inner[:] for inner in a], [[0, 1, 2]] * 3)
a[0][-1] = 55
self.assertEqual(a[0][:], [0, 1, 55])
for i in range(1, 3):
self.assertEqual(a[i][:], [0, 1, 2])
self.assertEqual(a[1].pop(), 2)
self.assertEqual(len(a[1]), 2)
for i in range(0, 3, 2):
self.assertEqual(len(a[i]), 3)
del a
b = self.list()
b.append(b)
del b
def test_dict(self):
d = self.dict()
indices = list(range(65, 70))
for i in indices:
d[i] = chr(i)
self.assertEqual(d.copy(), dict((i, chr(i)) for i in indices))
self.assertEqual(sorted(d.keys()), indices)
self.assertEqual(sorted(d.values()), [chr(i) for i in indices])
self.assertEqual(sorted(d.items()), [(i, chr(i)) for i in indices])
def test_dict_iter(self):
d = self.dict()
indices = list(range(65, 70))
for i in indices:
d[i] = chr(i)
it = iter(d)
self.assertEqual(list(it), indices)
self.assertEqual(list(it), []) # exhausted
# dictionary changed size during iteration
it = iter(d)
d.clear()
self.assertRaises(RuntimeError, next, it)
def test_dict_proxy_nested(self):
pets = self.dict(ferrets=2, hamsters=4)
supplies = self.dict(water=10, feed=3)
d = self.dict(pets=pets, supplies=supplies)
self.assertEqual(supplies['water'], 10)
self.assertEqual(d['supplies']['water'], 10)
d['supplies']['blankets'] = 5
self.assertEqual(supplies['blankets'], 5)
self.assertEqual(d['supplies']['blankets'], 5)
d['supplies']['water'] = 7
self.assertEqual(supplies['water'], 7)
self.assertEqual(d['supplies']['water'], 7)
del pets
del supplies
self.assertEqual(d['pets']['ferrets'], 2)
d['supplies']['blankets'] = 11
self.assertEqual(d['supplies']['blankets'], 11)
pets = d['pets']
supplies = d['supplies']
supplies['water'] = 7
self.assertEqual(supplies['water'], 7)
self.assertEqual(d['supplies']['water'], 7)
d.clear()
self.assertEqual(len(d), 0)
self.assertEqual(supplies['water'], 7)
self.assertEqual(pets['hamsters'], 4)
l = self.list([pets, supplies])
l[0]['marmots'] = 1
self.assertEqual(pets['marmots'], 1)
self.assertEqual(l[0]['marmots'], 1)
del pets
del supplies
self.assertEqual(l[0]['marmots'], 1)
outer = self.list([[88, 99], l])
self.assertIsInstance(outer[0], list) # Not a ListProxy
self.assertEqual(outer[-1][-1]['feed'], 3)
def test_namespace(self):
n = self.Namespace()
n.name = 'Bob'
n.job = 'Builder'
n._hidden = 'hidden'
self.assertEqual((n.name, n.job), ('Bob', 'Builder'))
del n.job
self.assertEqual(str(n), "Namespace(name='Bob')")
self.assertTrue(hasattr(n, 'name'))
self.assertTrue(not hasattr(n, 'job'))
#
#
#
def sqr(x, wait=0.0):
time.sleep(wait)
return x*x
def mul(x, y):
return x*y
def raise_large_valuerror(wait):
time.sleep(wait)
raise ValueError("x" * 1024**2)
def identity(x):
return x
class CountedObject(object):
n_instances = 0
def __new__(cls):
cls.n_instances += 1
return object.__new__(cls)
def __del__(self):
type(self).n_instances -= 1
class SayWhenError(ValueError): pass
def exception_throwing_generator(total, when):
if when == -1:
raise SayWhenError("Somebody said when")
for i in range(total):
if i == when:
raise SayWhenError("Somebody said when")
yield i
class _TestPool(BaseTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.pool = cls.Pool(4)
@classmethod
def tearDownClass(cls):
cls.pool.terminate()
cls.pool.join()
cls.pool = None
super().tearDownClass()
def test_apply(self):
papply = self.pool.apply
self.assertEqual(papply(sqr, (5,)), sqr(5))
self.assertEqual(papply(sqr, (), {'x':3}), sqr(x=3))
def test_map(self):
pmap = self.pool.map
self.assertEqual(pmap(sqr, list(range(10))), list(map(sqr, list(range(10)))))
self.assertEqual(pmap(sqr, list(range(100)), chunksize=20),
list(map(sqr, list(range(100)))))
def test_starmap(self):
psmap = self.pool.starmap
tuples = list(zip(range(10), range(9,-1, -1)))
self.assertEqual(psmap(mul, tuples),
list(itertools.starmap(mul, tuples)))
tuples = list(zip(range(100), range(99,-1, -1)))
self.assertEqual(psmap(mul, tuples, chunksize=20),
list(itertools.starmap(mul, tuples)))
def test_starmap_async(self):
tuples = list(zip(range(100), range(99,-1, -1)))
self.assertEqual(self.pool.starmap_async(mul, tuples).get(),
list(itertools.starmap(mul, tuples)))
def test_map_async(self):
self.assertEqual(self.pool.map_async(sqr, list(range(10))).get(),
list(map(sqr, list(range(10)))))
def test_map_async_callbacks(self):
call_args = self.manager.list() if self.TYPE == 'manager' else []
self.pool.map_async(int, ['1'],
callback=call_args.append,
error_callback=call_args.append).wait()
self.assertEqual(1, len(call_args))
self.assertEqual([1], call_args[0])
self.pool.map_async(int, ['a'],
callback=call_args.append,
error_callback=call_args.append).wait()
self.assertEqual(2, len(call_args))
self.assertIsInstance(call_args[1], ValueError)
def test_map_unplicklable(self):
# Issue #19425 -- failure to pickle should not cause a hang
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
class A(object):
def __reduce__(self):
raise RuntimeError('cannot pickle')
with self.assertRaises(RuntimeError):
self.pool.map(sqr, [A()]*10)
def test_map_chunksize(self):
try:
self.pool.map_async(sqr, [], chunksize=1).get(timeout=TIMEOUT1)
except multiprocessing.TimeoutError:
self.fail("pool.map_async with chunksize stalled on null list")
def test_map_handle_iterable_exception(self):
if self.TYPE == 'manager':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
# SayWhenError seen at the very first of the iterable
with self.assertRaises(SayWhenError):
self.pool.map(sqr, exception_throwing_generator(1, -1), 1)
# again, make sure it's reentrant
with self.assertRaises(SayWhenError):
self.pool.map(sqr, exception_throwing_generator(1, -1), 1)
with self.assertRaises(SayWhenError):
self.pool.map(sqr, exception_throwing_generator(10, 3), 1)
class SpecialIterable:
def __iter__(self):
return self
def __next__(self):
raise SayWhenError
def __len__(self):
return 1
with self.assertRaises(SayWhenError):
self.pool.map(sqr, SpecialIterable(), 1)
with self.assertRaises(SayWhenError):
self.pool.map(sqr, SpecialIterable(), 1)
def test_async(self):
res = self.pool.apply_async(sqr, (7, TIMEOUT1,))
get = TimingWrapper(res.get)
self.assertEqual(get(), 49)
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1)
def test_async_timeout(self):
res = self.pool.apply_async(sqr, (6, TIMEOUT2 + 1.0))
get = TimingWrapper(res.get)
self.assertRaises(multiprocessing.TimeoutError, get, timeout=TIMEOUT2)
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT2)
def test_imap(self):
it = self.pool.imap(sqr, list(range(10)))
self.assertEqual(list(it), list(map(sqr, list(range(10)))))
it = self.pool.imap(sqr, list(range(10)))
for i in range(10):
self.assertEqual(next(it), i*i)
self.assertRaises(StopIteration, it.__next__)
it = self.pool.imap(sqr, list(range(1000)), chunksize=100)
for i in range(1000):
self.assertEqual(next(it), i*i)
self.assertRaises(StopIteration, it.__next__)
def test_imap_handle_iterable_exception(self):
if self.TYPE == 'manager':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
# SayWhenError seen at the very first of the iterable
it = self.pool.imap(sqr, exception_throwing_generator(1, -1), 1)
self.assertRaises(SayWhenError, it.__next__)
# again, make sure it's reentrant
it = self.pool.imap(sqr, exception_throwing_generator(1, -1), 1)
self.assertRaises(SayWhenError, it.__next__)
it = self.pool.imap(sqr, exception_throwing_generator(10, 3), 1)
for i in range(3):
self.assertEqual(next(it), i*i)
self.assertRaises(SayWhenError, it.__next__)
# SayWhenError seen at start of problematic chunk's results
it = self.pool.imap(sqr, exception_throwing_generator(20, 7), 2)
for i in range(6):
self.assertEqual(next(it), i*i)
self.assertRaises(SayWhenError, it.__next__)
it = self.pool.imap(sqr, exception_throwing_generator(20, 7), 4)
for i in range(4):
self.assertEqual(next(it), i*i)
self.assertRaises(SayWhenError, it.__next__)
def test_imap_unordered(self):
it = self.pool.imap_unordered(sqr, list(range(10)))
self.assertEqual(sorted(it), list(map(sqr, list(range(10)))))
it = self.pool.imap_unordered(sqr, list(range(1000)), chunksize=100)
self.assertEqual(sorted(it), list(map(sqr, list(range(1000)))))
def test_imap_unordered_handle_iterable_exception(self):
if self.TYPE == 'manager':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
# SayWhenError seen at the very first of the iterable
it = self.pool.imap_unordered(sqr,
exception_throwing_generator(1, -1),
1)
self.assertRaises(SayWhenError, it.__next__)
# again, make sure it's reentrant
it = self.pool.imap_unordered(sqr,
exception_throwing_generator(1, -1),
1)
self.assertRaises(SayWhenError, it.__next__)
it = self.pool.imap_unordered(sqr,
exception_throwing_generator(10, 3),
1)
expected_values = list(map(sqr, list(range(10))))
with self.assertRaises(SayWhenError):
# imap_unordered makes it difficult to anticipate the SayWhenError
for i in range(10):
value = next(it)
self.assertIn(value, expected_values)
expected_values.remove(value)
it = self.pool.imap_unordered(sqr,
exception_throwing_generator(20, 7),
2)
expected_values = list(map(sqr, list(range(20))))
with self.assertRaises(SayWhenError):
for i in range(20):
value = next(it)
self.assertIn(value, expected_values)
expected_values.remove(value)
def test_make_pool(self):
expected_error = (RemoteError if self.TYPE == 'manager'
else ValueError)
self.assertRaises(expected_error, self.Pool, -1)
self.assertRaises(expected_error, self.Pool, 0)
if self.TYPE != 'manager':
p = self.Pool(3)
try:
self.assertEqual(3, len(p._pool))
finally:
p.close()
p.join()
def test_terminate(self):
result = self.pool.map_async(
time.sleep, [0.1 for i in range(10000)], chunksize=1
)
self.pool.terminate()
join = TimingWrapper(self.pool.join)
join()
# Sanity check the pool didn't wait for all tasks to finish
self.assertLess(join.elapsed, 2.0)
def test_empty_iterable(self):
# See Issue 12157
p = self.Pool(1)
self.assertEqual(p.map(sqr, []), [])
self.assertEqual(list(p.imap(sqr, [])), [])
self.assertEqual(list(p.imap_unordered(sqr, [])), [])
self.assertEqual(p.map_async(sqr, []).get(), [])
p.close()
p.join()
def test_context(self):
if self.TYPE == 'processes':
L = list(range(10))
expected = [sqr(i) for i in L]
with self.Pool(2) as p:
r = p.map_async(sqr, L)
self.assertEqual(r.get(), expected)
p.join()
self.assertRaises(ValueError, p.map_async, sqr, L)
@classmethod
def _test_traceback(cls):
raise RuntimeError(123) # some comment
def test_traceback(self):
# We want ensure that the traceback from the child process is
# contained in the traceback raised in the main process.
if self.TYPE == 'processes':
with self.Pool(1) as p:
try:
p.apply(self._test_traceback)
except Exception as e:
exc = e
else:
self.fail('expected RuntimeError')
p.join()
self.assertIs(type(exc), RuntimeError)
self.assertEqual(exc.args, (123,))
cause = exc.__cause__
self.assertIs(type(cause), multiprocessing.pool.RemoteTraceback)
self.assertIn('raise RuntimeError(123) # some comment', cause.tb)
with support.captured_stderr() as f1:
try:
raise exc
except RuntimeError:
sys.excepthook(*sys.exc_info())
self.assertIn('raise RuntimeError(123) # some comment',
f1.getvalue())
# _helper_reraises_exception should not make the error
# a remote exception
with self.Pool(1) as p:
try:
p.map(sqr, exception_throwing_generator(1, -1), 1)
except Exception as e:
exc = e
else:
self.fail('expected SayWhenError')
self.assertIs(type(exc), SayWhenError)
self.assertIs(exc.__cause__, None)
p.join()
@classmethod
def _test_wrapped_exception(cls):
raise RuntimeError('foo')
def test_wrapped_exception(self):
# Issue #20980: Should not wrap exception when using thread pool
with self.Pool(1) as p:
with self.assertRaises(RuntimeError):
p.apply(self._test_wrapped_exception)
p.join()
def test_map_no_failfast(self):
# Issue #23992: the fail-fast behaviour when an exception is raised
# during map() would make Pool.join() deadlock, because a worker
# process would fill the result queue (after the result handler thread
# terminated, hence not draining it anymore).
t_start = time.time()
with self.assertRaises(ValueError):
with self.Pool(2) as p:
try:
p.map(raise_large_valuerror, [0, 1])
finally:
time.sleep(0.5)
p.close()
p.join()
# check that we indeed waited for all jobs
self.assertGreater(time.time() - t_start, 0.9)
def test_release_task_refs(self):
# Issue #29861: task arguments and results should not be kept
# alive after we are done with them.
objs = [CountedObject() for i in range(10)]
refs = [weakref.ref(o) for o in objs]
self.pool.map(identity, objs)
del objs
time.sleep(DELTA) # let threaded cleanup code run
self.assertEqual(set(wr() for wr in refs), {None})
# With a process pool, copies of the objects are returned, check
# they were released too.
self.assertEqual(CountedObject.n_instances, 0)
def raising():
raise KeyError("key")
def unpickleable_result():
return lambda: 42
class _TestPoolWorkerErrors(BaseTestCase):
ALLOWED_TYPES = ('processes', )
def test_async_error_callback(self):
p = multiprocessing.Pool(2)
scratchpad = [None]
def errback(exc):
scratchpad[0] = exc
res = p.apply_async(raising, error_callback=errback)
self.assertRaises(KeyError, res.get)
self.assertTrue(scratchpad[0])
self.assertIsInstance(scratchpad[0], KeyError)
p.close()
p.join()
def test_unpickleable_result(self):
from multiprocessing.pool import MaybeEncodingError
p = multiprocessing.Pool(2)
# Make sure we don't lose pool processes because of encoding errors.
for iteration in range(20):
scratchpad = [None]
def errback(exc):
scratchpad[0] = exc
res = p.apply_async(unpickleable_result, error_callback=errback)
self.assertRaises(MaybeEncodingError, res.get)
wrapped = scratchpad[0]
self.assertTrue(wrapped)
self.assertIsInstance(scratchpad[0], MaybeEncodingError)
self.assertIsNotNone(wrapped.exc)
self.assertIsNotNone(wrapped.value)
p.close()
p.join()
class _TestPoolWorkerLifetime(BaseTestCase):
ALLOWED_TYPES = ('processes', )
def test_pool_worker_lifetime(self):
p = multiprocessing.Pool(3, maxtasksperchild=10)
self.assertEqual(3, len(p._pool))
origworkerpids = [w.pid for w in p._pool]
# Run many tasks so each worker gets replaced (hopefully)
results = []
for i in range(100):
results.append(p.apply_async(sqr, (i, )))
# Fetch the results and verify we got the right answers,
# also ensuring all the tasks have completed.
for (j, res) in enumerate(results):
self.assertEqual(res.get(), sqr(j))
# Refill the pool
p._repopulate_pool()
# Wait until all workers are alive
# (countdown * DELTA = 5 seconds max startup process time)
countdown = 50
while countdown and not all(w.is_alive() for w in p._pool):
countdown -= 1
time.sleep(DELTA)
finalworkerpids = [w.pid for w in p._pool]
# All pids should be assigned. See issue #7805.
self.assertNotIn(None, origworkerpids)
self.assertNotIn(None, finalworkerpids)
# Finally, check that the worker pids have changed
self.assertNotEqual(sorted(origworkerpids), sorted(finalworkerpids))
p.close()
p.join()
def test_pool_worker_lifetime_early_close(self):
# Issue #10332: closing a pool whose workers have limited lifetimes
# before all the tasks completed would make join() hang.
p = multiprocessing.Pool(3, maxtasksperchild=1)
results = []
for i in range(6):
results.append(p.apply_async(sqr, (i, 0.3)))
p.close()
p.join()
# check the results
for (j, res) in enumerate(results):
self.assertEqual(res.get(), sqr(j))
#
# Test of creating a customized manager class
#
from multiprocessing.managers import BaseManager, BaseProxy, RemoteError
class FooBar(object):
def f(self):
return 'f()'
def g(self):
raise ValueError
def _h(self):
return '_h()'
def baz():
for i in range(10):
yield i*i
class IteratorProxy(BaseProxy):
_exposed_ = ('__next__',)
def __iter__(self):
return self
def __next__(self):
return self._callmethod('__next__')
class MyManager(BaseManager):
pass
MyManager.register('Foo', callable=FooBar)
MyManager.register('Bar', callable=FooBar, exposed=('f', '_h'))
MyManager.register('baz', callable=baz, proxytype=IteratorProxy)
class _TestMyManager(BaseTestCase):
ALLOWED_TYPES = ('manager',)
def test_mymanager(self):
manager = MyManager()
manager.start()
self.common(manager)
manager.shutdown()
# If the manager process exited cleanly then the exitcode
# will be zero. Otherwise (after a short timeout)
# terminate() is used, resulting in an exitcode of -SIGTERM.
self.assertEqual(manager._process.exitcode, 0)
def test_mymanager_context(self):
with MyManager() as manager:
self.common(manager)
# bpo-30356: BaseManager._finalize_manager() sends SIGTERM
# to the manager process if it takes longer than 1 second to stop.
self.assertIn(manager._process.exitcode, (0, -signal.SIGTERM))
def test_mymanager_context_prestarted(self):
manager = MyManager()
manager.start()
with manager:
self.common(manager)
self.assertEqual(manager._process.exitcode, 0)
def common(self, manager):
foo = manager.Foo()
bar = manager.Bar()
baz = manager.baz()
foo_methods = [name for name in ('f', 'g', '_h') if hasattr(foo, name)]
bar_methods = [name for name in ('f', 'g', '_h') if hasattr(bar, name)]
self.assertEqual(foo_methods, ['f', 'g'])
self.assertEqual(bar_methods, ['f', '_h'])
self.assertEqual(foo.f(), 'f()')
self.assertRaises(ValueError, foo.g)
self.assertEqual(foo._callmethod('f'), 'f()')
self.assertRaises(RemoteError, foo._callmethod, '_h')
self.assertEqual(bar.f(), 'f()')
self.assertEqual(bar._h(), '_h()')
self.assertEqual(bar._callmethod('f'), 'f()')
self.assertEqual(bar._callmethod('_h'), '_h()')
self.assertEqual(list(baz), [i*i for i in range(10)])
#
# Test of connecting to a remote server and using xmlrpclib for serialization
#
_queue = pyqueue.Queue()
def get_queue():
return _queue
class QueueManager(BaseManager):
'''manager class used by server process'''
QueueManager.register('get_queue', callable=get_queue)
class QueueManager2(BaseManager):
'''manager class which specifies the same interface as QueueManager'''
QueueManager2.register('get_queue')
SERIALIZER = 'xmlrpclib'
class _TestRemoteManager(BaseTestCase):
ALLOWED_TYPES = ('manager',)
values = ['hello world', None, True, 2.25,
'hall\xe5 v\xe4rlden',
'\u043f\u0440\u0438\u0432\u0456\u0442 \u0441\u0432\u0456\u0442',
b'hall\xe5 v\xe4rlden',
]
result = values[:]
@classmethod
def _putter(cls, address, authkey):
manager = QueueManager2(
address=address, authkey=authkey, serializer=SERIALIZER
)
manager.connect()
queue = manager.get_queue()
# Note that xmlrpclib will deserialize object as a list not a tuple
queue.put(tuple(cls.values))
def test_remote(self):
authkey = os.urandom(32)
manager = QueueManager(
address=(support.HOST, 0), authkey=authkey, serializer=SERIALIZER
)
manager.start()
p = self.Process(target=self._putter, args=(manager.address, authkey))
p.daemon = True
p.start()
manager2 = QueueManager2(
address=manager.address, authkey=authkey, serializer=SERIALIZER
)
manager2.connect()
queue = manager2.get_queue()
self.assertEqual(queue.get(), self.result)
# Because we are using xmlrpclib for serialization instead of
# pickle this will cause a serialization error.
self.assertRaises(Exception, queue.put, time.sleep)
# Make queue finalizer run before the server is stopped
del queue
manager.shutdown()
class _TestManagerRestart(BaseTestCase):
@classmethod
def _putter(cls, address, authkey):
manager = QueueManager(
address=address, authkey=authkey, serializer=SERIALIZER)
manager.connect()
queue = manager.get_queue()
queue.put('hello world')
def test_rapid_restart(self):
authkey = os.urandom(32)
manager = QueueManager(
address=(support.HOST, 0), authkey=authkey, serializer=SERIALIZER)
srvr = manager.get_server()
addr = srvr.address
# Close the connection.Listener socket which gets opened as a part
# of manager.get_server(). It's not needed for the test.
srvr.listener.close()
manager.start()
p = self.Process(target=self._putter, args=(manager.address, authkey))
p.start()
p.join()
queue = manager.get_queue()
self.assertEqual(queue.get(), 'hello world')
del queue
manager.shutdown()
manager = QueueManager(
address=addr, authkey=authkey, serializer=SERIALIZER)
try:
manager.start()
except OSError as e:
if e.errno != errno.EADDRINUSE:
raise
# Retry after some time, in case the old socket was lingering
# (sporadic failure on buildbots)
time.sleep(1.0)
manager = QueueManager(
address=addr, authkey=authkey, serializer=SERIALIZER)
manager.shutdown()
#
#
#
SENTINEL = latin('')
class _TestConnection(BaseTestCase):
ALLOWED_TYPES = ('processes', 'threads')
@classmethod
def _echo(cls, conn):
for msg in iter(conn.recv_bytes, SENTINEL):
conn.send_bytes(msg)
conn.close()
def test_connection(self):
conn, child_conn = self.Pipe()
p = self.Process(target=self._echo, args=(child_conn,))
p.daemon = True
p.start()
seq = [1, 2.25, None]
msg = latin('hello world')
longmsg = msg * 10
arr = array.array('i', list(range(4)))
if self.TYPE == 'processes':
self.assertEqual(type(conn.fileno()), int)
self.assertEqual(conn.send(seq), None)
self.assertEqual(conn.recv(), seq)
self.assertEqual(conn.send_bytes(msg), None)
self.assertEqual(conn.recv_bytes(), msg)
if self.TYPE == 'processes':
buffer = array.array('i', [0]*10)
expected = list(arr) + [0] * (10 - len(arr))
self.assertEqual(conn.send_bytes(arr), None)
self.assertEqual(conn.recv_bytes_into(buffer),
len(arr) * buffer.itemsize)
self.assertEqual(list(buffer), expected)
buffer = array.array('i', [0]*10)
expected = [0] * 3 + list(arr) + [0] * (10 - 3 - len(arr))
self.assertEqual(conn.send_bytes(arr), None)
self.assertEqual(conn.recv_bytes_into(buffer, 3 * buffer.itemsize),
len(arr) * buffer.itemsize)
self.assertEqual(list(buffer), expected)
buffer = bytearray(latin(' ' * 40))
self.assertEqual(conn.send_bytes(longmsg), None)
try:
res = conn.recv_bytes_into(buffer)
except multiprocessing.BufferTooShort as e:
self.assertEqual(e.args, (longmsg,))
else:
self.fail('expected BufferTooShort, got %s' % res)
poll = TimingWrapper(conn.poll)
self.assertEqual(poll(), False)
self.assertTimingAlmostEqual(poll.elapsed, 0)
self.assertEqual(poll(-1), False)
self.assertTimingAlmostEqual(poll.elapsed, 0)
self.assertEqual(poll(TIMEOUT1), False)
self.assertTimingAlmostEqual(poll.elapsed, TIMEOUT1)
conn.send(None)
time.sleep(.1)
self.assertEqual(poll(TIMEOUT1), True)
self.assertTimingAlmostEqual(poll.elapsed, 0)
self.assertEqual(conn.recv(), None)
really_big_msg = latin('X') * (1024 * 1024 * 16) # 16Mb
conn.send_bytes(really_big_msg)
self.assertEqual(conn.recv_bytes(), really_big_msg)
conn.send_bytes(SENTINEL) # tell child to quit
child_conn.close()
if self.TYPE == 'processes':
self.assertEqual(conn.readable, True)
self.assertEqual(conn.writable, True)
self.assertRaises(EOFError, conn.recv)
self.assertRaises(EOFError, conn.recv_bytes)
p.join()
def test_duplex_false(self):
reader, writer = self.Pipe(duplex=False)
self.assertEqual(writer.send(1), None)
self.assertEqual(reader.recv(), 1)
if self.TYPE == 'processes':
self.assertEqual(reader.readable, True)
self.assertEqual(reader.writable, False)
self.assertEqual(writer.readable, False)
self.assertEqual(writer.writable, True)
self.assertRaises(OSError, reader.send, 2)
self.assertRaises(OSError, writer.recv)
self.assertRaises(OSError, writer.poll)
def test_spawn_close(self):
# We test that a pipe connection can be closed by parent
# process immediately after child is spawned. On Windows this
# would have sometimes failed on old versions because
# child_conn would be closed before the child got a chance to
# duplicate it.
conn, child_conn = self.Pipe()
p = self.Process(target=self._echo, args=(child_conn,))
p.daemon = True
p.start()
child_conn.close() # this might complete before child initializes
msg = latin('hello')
conn.send_bytes(msg)
self.assertEqual(conn.recv_bytes(), msg)
conn.send_bytes(SENTINEL)
conn.close()
p.join()
def test_sendbytes(self):
if self.TYPE != 'processes':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
msg = latin('abcdefghijklmnopqrstuvwxyz')
a, b = self.Pipe()
a.send_bytes(msg)
self.assertEqual(b.recv_bytes(), msg)
a.send_bytes(msg, 5)
self.assertEqual(b.recv_bytes(), msg[5:])
a.send_bytes(msg, 7, 8)
self.assertEqual(b.recv_bytes(), msg[7:7+8])
a.send_bytes(msg, 26)
self.assertEqual(b.recv_bytes(), latin(''))
a.send_bytes(msg, 26, 0)
self.assertEqual(b.recv_bytes(), latin(''))
self.assertRaises(ValueError, a.send_bytes, msg, 27)
self.assertRaises(ValueError, a.send_bytes, msg, 22, 5)
self.assertRaises(ValueError, a.send_bytes, msg, 26, 1)
self.assertRaises(ValueError, a.send_bytes, msg, -1)
self.assertRaises(ValueError, a.send_bytes, msg, 4, -1)
@classmethod
def _is_fd_assigned(cls, fd):
try:
os.fstat(fd)
except OSError as e:
if e.errno == errno.EBADF:
return False
raise
else:
return True
@classmethod
def _writefd(cls, conn, data, create_dummy_fds=False):
if create_dummy_fds:
for i in range(0, 256):
if not cls._is_fd_assigned(i):
os.dup2(conn.fileno(), i)
fd = reduction.recv_handle(conn)
if msvcrt:
fd = msvcrt.open_osfhandle(fd, os.O_WRONLY)
os.write(fd, data)
os.close(fd)
@unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
def test_fd_transfer(self):
if self.TYPE != 'processes':
self.skipTest("only makes sense with processes")
conn, child_conn = self.Pipe(duplex=True)
p = self.Process(target=self._writefd, args=(child_conn, b"foo"))
p.daemon = True
p.start()
self.addCleanup(support.unlink, support.TESTFN)
with open(support.TESTFN, "wb") as f:
fd = f.fileno()
if msvcrt:
fd = msvcrt.get_osfhandle(fd)
reduction.send_handle(conn, fd, p.pid)
p.join()
with open(support.TESTFN, "rb") as f:
self.assertEqual(f.read(), b"foo")
@unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
@unittest.skipIf(sys.platform == "win32",
"test semantics don't make sense on Windows")
@unittest.skipIf(MAXFD <= 256,
"largest assignable fd number is too small")
@unittest.skipUnless(hasattr(os, "dup2"),
"test needs os.dup2()")
def test_large_fd_transfer(self):
# With fd > 256 (issue #11657)
if self.TYPE != 'processes':
self.skipTest("only makes sense with processes")
conn, child_conn = self.Pipe(duplex=True)
p = self.Process(target=self._writefd, args=(child_conn, b"bar", True))
p.daemon = True
p.start()
self.addCleanup(support.unlink, support.TESTFN)
with open(support.TESTFN, "wb") as f:
fd = f.fileno()
for newfd in range(256, MAXFD):
if not self._is_fd_assigned(newfd):
break
else:
self.fail("could not find an unassigned large file descriptor")
os.dup2(fd, newfd)
try:
reduction.send_handle(conn, newfd, p.pid)
finally:
os.close(newfd)
p.join()
with open(support.TESTFN, "rb") as f:
self.assertEqual(f.read(), b"bar")
@classmethod
def _send_data_without_fd(self, conn):
os.write(conn.fileno(), b"\0")
@unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
@unittest.skipIf(sys.platform == "win32", "doesn't make sense on Windows")
def test_missing_fd_transfer(self):
# Check that exception is raised when received data is not
# accompanied by a file descriptor in ancillary data.
if self.TYPE != 'processes':
self.skipTest("only makes sense with processes")
conn, child_conn = self.Pipe(duplex=True)
p = self.Process(target=self._send_data_without_fd, args=(child_conn,))
p.daemon = True
p.start()
self.assertRaises(RuntimeError, reduction.recv_handle, conn)
p.join()
def test_context(self):
a, b = self.Pipe()
with a, b:
a.send(1729)
self.assertEqual(b.recv(), 1729)
if self.TYPE == 'processes':
self.assertFalse(a.closed)
self.assertFalse(b.closed)
if self.TYPE == 'processes':
self.assertTrue(a.closed)
self.assertTrue(b.closed)
self.assertRaises(OSError, a.recv)
self.assertRaises(OSError, b.recv)
class _TestListener(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def test_multiple_bind(self):
for family in self.connection.families:
l = self.connection.Listener(family=family)
self.addCleanup(l.close)
self.assertRaises(OSError, self.connection.Listener,
l.address, family)
def test_context(self):
with self.connection.Listener() as l:
with self.connection.Client(l.address) as c:
with l.accept() as d:
c.send(1729)
self.assertEqual(d.recv(), 1729)
if self.TYPE == 'processes':
self.assertRaises(OSError, l.accept)
class _TestListenerClient(BaseTestCase):
ALLOWED_TYPES = ('processes', 'threads')
@classmethod
def _test(cls, address):
conn = cls.connection.Client(address)
conn.send('hello')
conn.close()
def test_listener_client(self):
for family in self.connection.families:
l = self.connection.Listener(family=family)
p = self.Process(target=self._test, args=(l.address,))
p.daemon = True
p.start()
conn = l.accept()
self.assertEqual(conn.recv(), 'hello')
p.join()
l.close()
def test_issue14725(self):
l = self.connection.Listener()
p = self.Process(target=self._test, args=(l.address,))
p.daemon = True
p.start()
time.sleep(1)
# On Windows the client process should by now have connected,
# written data and closed the pipe handle by now. This causes
# ConnectNamdedPipe() to fail with ERROR_NO_DATA. See Issue
# 14725.
conn = l.accept()
self.assertEqual(conn.recv(), 'hello')
conn.close()
p.join()
l.close()
def test_issue16955(self):
for fam in self.connection.families:
l = self.connection.Listener(family=fam)
c = self.connection.Client(l.address)
a = l.accept()
a.send_bytes(b"hello")
self.assertTrue(c.poll(1))
a.close()
c.close()
l.close()
class _TestPoll(BaseTestCase):
ALLOWED_TYPES = ('processes', 'threads')
def test_empty_string(self):
a, b = self.Pipe()
self.assertEqual(a.poll(), False)
b.send_bytes(b'')
self.assertEqual(a.poll(), True)
self.assertEqual(a.poll(), True)
@classmethod
def _child_strings(cls, conn, strings):
for s in strings:
time.sleep(0.1)
conn.send_bytes(s)
conn.close()
def test_strings(self):
strings = (b'hello', b'', b'a', b'b', b'', b'bye', b'', b'lop')
a, b = self.Pipe()
p = self.Process(target=self._child_strings, args=(b, strings))
p.start()
for s in strings:
for i in range(200):
if a.poll(0.01):
break
x = a.recv_bytes()
self.assertEqual(s, x)
p.join()
@classmethod
def _child_boundaries(cls, r):
# Polling may "pull" a message in to the child process, but we
# don't want it to pull only part of a message, as that would
# corrupt the pipe for any other processes which might later
# read from it.
r.poll(5)
def test_boundaries(self):
r, w = self.Pipe(False)
p = self.Process(target=self._child_boundaries, args=(r,))
p.start()
time.sleep(2)
L = [b"first", b"second"]
for obj in L:
w.send_bytes(obj)
w.close()
p.join()
self.assertIn(r.recv_bytes(), L)
@classmethod
def _child_dont_merge(cls, b):
b.send_bytes(b'a')
b.send_bytes(b'b')
b.send_bytes(b'cd')
def test_dont_merge(self):
a, b = self.Pipe()
self.assertEqual(a.poll(0.0), False)
self.assertEqual(a.poll(0.1), False)
p = self.Process(target=self._child_dont_merge, args=(b,))
p.start()
self.assertEqual(a.recv_bytes(), b'a')
self.assertEqual(a.poll(1.0), True)
self.assertEqual(a.poll(1.0), True)
self.assertEqual(a.recv_bytes(), b'b')
self.assertEqual(a.poll(1.0), True)
self.assertEqual(a.poll(1.0), True)
self.assertEqual(a.poll(0.0), True)
self.assertEqual(a.recv_bytes(), b'cd')
p.join()
#
# Test of sending connection and socket objects between processes
#
@unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
class _TestPicklingConnections(BaseTestCase):
ALLOWED_TYPES = ('processes',)
@classmethod
def tearDownClass(cls):
from multiprocessing import resource_sharer
resource_sharer.stop(timeout=5)
@classmethod
def _listener(cls, conn, families):
for fam in families:
l = cls.connection.Listener(family=fam)
conn.send(l.address)
new_conn = l.accept()
conn.send(new_conn)
new_conn.close()
l.close()
l = socket.socket()
l.bind((support.HOST, 0))
l.listen()
conn.send(l.getsockname())
new_conn, addr = l.accept()
conn.send(new_conn)
new_conn.close()
l.close()
conn.recv()
@classmethod
def _remote(cls, conn):
for (address, msg) in iter(conn.recv, None):
client = cls.connection.Client(address)
client.send(msg.upper())
client.close()
address, msg = conn.recv()
client = socket.socket()
client.connect(address)
client.sendall(msg.upper())
client.close()
conn.close()
def test_pickling(self):
families = self.connection.families
lconn, lconn0 = self.Pipe()
lp = self.Process(target=self._listener, args=(lconn0, families))
lp.daemon = True
lp.start()
lconn0.close()
rconn, rconn0 = self.Pipe()
rp = self.Process(target=self._remote, args=(rconn0,))
rp.daemon = True
rp.start()
rconn0.close()
for fam in families:
msg = ('This connection uses family %s' % fam).encode('ascii')
address = lconn.recv()
rconn.send((address, msg))
new_conn = lconn.recv()
self.assertEqual(new_conn.recv(), msg.upper())
rconn.send(None)
msg = latin('This connection uses a normal socket')
address = lconn.recv()
rconn.send((address, msg))
new_conn = lconn.recv()
buf = []
while True:
s = new_conn.recv(100)
if not s:
break
buf.append(s)
buf = b''.join(buf)
self.assertEqual(buf, msg.upper())
new_conn.close()
lconn.send(None)
rconn.close()
lconn.close()
lp.join()
rp.join()
@classmethod
def child_access(cls, conn):
w = conn.recv()
w.send('all is well')
w.close()
r = conn.recv()
msg = r.recv()
conn.send(msg*2)
conn.close()
def test_access(self):
# On Windows, if we do not specify a destination pid when
# using DupHandle then we need to be careful to use the
# correct access flags for DuplicateHandle(), or else
# DupHandle.detach() will raise PermissionError. For example,
# for a read only pipe handle we should use
# access=FILE_GENERIC_READ. (Unfortunately
# DUPLICATE_SAME_ACCESS does not work.)
conn, child_conn = self.Pipe()
p = self.Process(target=self.child_access, args=(child_conn,))
p.daemon = True
p.start()
child_conn.close()
r, w = self.Pipe(duplex=False)
conn.send(w)
w.close()
self.assertEqual(r.recv(), 'all is well')
r.close()
r, w = self.Pipe(duplex=False)
conn.send(r)
r.close()
w.send('foobar')
w.close()
self.assertEqual(conn.recv(), 'foobar'*2)
p.join()
#
#
#
class _TestHeap(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def test_heap(self):
iterations = 5000
maxblocks = 50
blocks = []
# create and destroy lots of blocks of different sizes
for i in range(iterations):
size = int(random.lognormvariate(0, 1) * 1000)
b = multiprocessing.heap.BufferWrapper(size)
blocks.append(b)
if len(blocks) > maxblocks:
i = random.randrange(maxblocks)
del blocks[i]
# get the heap object
heap = multiprocessing.heap.BufferWrapper._heap
# verify the state of the heap
all = []
occupied = 0
heap._lock.acquire()
self.addCleanup(heap._lock.release)
for L in list(heap._len_to_seq.values()):
for arena, start, stop in L:
all.append((heap._arenas.index(arena), start, stop,
stop-start, 'free'))
for arena, start, stop in heap._allocated_blocks:
all.append((heap._arenas.index(arena), start, stop,
stop-start, 'occupied'))
occupied += (stop-start)
all.sort()
for i in range(len(all)-1):
(arena, start, stop) = all[i][:3]
(narena, nstart, nstop) = all[i+1][:3]
self.assertTrue((arena != narena and nstart == 0) or
(stop == nstart))
def test_free_from_gc(self):
# Check that freeing of blocks by the garbage collector doesn't deadlock
# (issue #12352).
# Make sure the GC is enabled, and set lower collection thresholds to
# make collections more frequent (and increase the probability of
# deadlock).
if not gc.isenabled():
gc.enable()
self.addCleanup(gc.disable)
thresholds = gc.get_threshold()
self.addCleanup(gc.set_threshold, *thresholds)
gc.set_threshold(10)
# perform numerous block allocations, with cyclic references to make
# sure objects are collected asynchronously by the gc
for i in range(5000):
a = multiprocessing.heap.BufferWrapper(1)
b = multiprocessing.heap.BufferWrapper(1)
# circular references
a.buddy = b
b.buddy = a
#
#
#
class _Foo(Structure):
_fields_ = [
('x', c_int),
('y', c_double)
]
class _TestSharedCTypes(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def setUp(self):
if not HAS_SHAREDCTYPES:
self.skipTest("requires multiprocessing.sharedctypes")
@classmethod
def _double(cls, x, y, foo, arr, string):
x.value *= 2
y.value *= 2
foo.x *= 2
foo.y *= 2
string.value *= 2
for i in range(len(arr)):
arr[i] *= 2
def test_sharedctypes(self, lock=False):
x = Value('i', 7, lock=lock)
y = Value(c_double, 1.0/3.0, lock=lock)
foo = Value(_Foo, 3, 2, lock=lock)
arr = self.Array('d', list(range(10)), lock=lock)
string = self.Array('c', 20, lock=lock)
string.value = latin('hello')
p = self.Process(target=self._double, args=(x, y, foo, arr, string))
p.daemon = True
p.start()
p.join()
self.assertEqual(x.value, 14)
self.assertAlmostEqual(y.value, 2.0/3.0)
self.assertEqual(foo.x, 6)
self.assertAlmostEqual(foo.y, 4.0)
for i in range(10):
self.assertAlmostEqual(arr[i], i*2)
self.assertEqual(string.value, latin('hellohello'))
def test_synchronize(self):
self.test_sharedctypes(lock=True)
def test_copy(self):
foo = _Foo(2, 5.0)
bar = copy(foo)
foo.x = 0
foo.y = 0
self.assertEqual(bar.x, 2)
self.assertAlmostEqual(bar.y, 5.0)
#
#
#
class _TestFinalize(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def setUp(self):
self.registry_backup = util._finalizer_registry.copy()
util._finalizer_registry.clear()
def tearDown(self):
self.assertFalse(util._finalizer_registry)
util._finalizer_registry.update(self.registry_backup)
@classmethod
def _test_finalize(cls, conn):
class Foo(object):
pass
a = Foo()
util.Finalize(a, conn.send, args=('a',))
del a # triggers callback for a
b = Foo()
close_b = util.Finalize(b, conn.send, args=('b',))
close_b() # triggers callback for b
close_b() # does nothing because callback has already been called
del b # does nothing because callback has already been called
c = Foo()
util.Finalize(c, conn.send, args=('c',))
d10 = Foo()
util.Finalize(d10, conn.send, args=('d10',), exitpriority=1)
d01 = Foo()
util.Finalize(d01, conn.send, args=('d01',), exitpriority=0)
d02 = Foo()
util.Finalize(d02, conn.send, args=('d02',), exitpriority=0)
d03 = Foo()
util.Finalize(d03, conn.send, args=('d03',), exitpriority=0)
util.Finalize(None, conn.send, args=('e',), exitpriority=-10)
util.Finalize(None, conn.send, args=('STOP',), exitpriority=-100)
# call multiprocessing's cleanup function then exit process without
# garbage collecting locals
util._exit_function()
conn.close()
os._exit(0)
def test_finalize(self):
conn, child_conn = self.Pipe()
p = self.Process(target=self._test_finalize, args=(child_conn,))
p.daemon = True
p.start()
p.join()
result = [obj for obj in iter(conn.recv, 'STOP')]
self.assertEqual(result, ['a', 'b', 'd10', 'd03', 'd02', 'd01', 'e'])
def test_thread_safety(self):
# bpo-24484: _run_finalizers() should be thread-safe
def cb():
pass
class Foo(object):
def __init__(self):
self.ref = self # create reference cycle
# insert finalizer at random key
util.Finalize(self, cb, exitpriority=random.randint(1, 100))
finish = False
exc = None
def run_finalizers():
nonlocal exc
while not finish:
time.sleep(random.random() * 1e-1)
try:
# A GC run will eventually happen during this,
# collecting stale Foo's and mutating the registry
util._run_finalizers()
except Exception as e:
exc = e
def make_finalizers():
nonlocal exc
d = {}
while not finish:
try:
# Old Foo's get gradually replaced and later
# collected by the GC (because of the cyclic ref)
d[random.getrandbits(5)] = {Foo() for i in range(10)}
except Exception as e:
exc = e
d.clear()
old_interval = sys.getswitchinterval()
old_threshold = gc.get_threshold()
try:
sys.setswitchinterval(1e-6)
gc.set_threshold(5, 5, 5)
threads = [threading.Thread(target=run_finalizers),
threading.Thread(target=make_finalizers)]
with support.start_threads(threads):
time.sleep(4.0) # Wait a bit to trigger race condition
finish = True
if exc is not None:
raise exc
finally:
sys.setswitchinterval(old_interval)
gc.set_threshold(*old_threshold)
gc.collect() # Collect remaining Foo's
#
# Test that from ... import * works for each module
#
class _TestImportStar(unittest.TestCase):
def get_module_names(self):
import glob
folder = os.path.dirname(multiprocessing.__file__)
pattern = os.path.join(folder, '*.py')
files = glob.glob(pattern)
modules = [os.path.splitext(os.path.split(f)[1])[0] for f in files]
modules = ['multiprocessing.' + m for m in modules]
modules.remove('multiprocessing.__init__')
modules.append('multiprocessing')
return modules
def test_import(self):
modules = self.get_module_names()
if sys.platform == 'win32':
modules.remove('multiprocessing.popen_fork')
modules.remove('multiprocessing.popen_forkserver')
modules.remove('multiprocessing.popen_spawn_posix')
else:
modules.remove('multiprocessing.popen_spawn_win32')
if not HAS_REDUCTION:
modules.remove('multiprocessing.popen_forkserver')
if c_int is None:
# This module requires _ctypes
modules.remove('multiprocessing.sharedctypes')
for name in modules:
__import__(name)
mod = sys.modules[name]
self.assertTrue(hasattr(mod, '__all__'), name)
for attr in mod.__all__:
self.assertTrue(
hasattr(mod, attr),
'%r does not have attribute %r' % (mod, attr)
)
#
# Quick test that logging works -- does not test logging output
#
class _TestLogging(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def test_enable_logging(self):
logger = multiprocessing.get_logger()
logger.setLevel(util.SUBWARNING)
self.assertTrue(logger is not None)
logger.debug('this will not be printed')
logger.info('nor will this')
logger.setLevel(LOG_LEVEL)
@classmethod
def _test_level(cls, conn):
logger = multiprocessing.get_logger()
conn.send(logger.getEffectiveLevel())
def test_level(self):
LEVEL1 = 32
LEVEL2 = 37
logger = multiprocessing.get_logger()
root_logger = logging.getLogger()
root_level = root_logger.level
reader, writer = multiprocessing.Pipe(duplex=False)
logger.setLevel(LEVEL1)
p = self.Process(target=self._test_level, args=(writer,))
p.start()
self.assertEqual(LEVEL1, reader.recv())
p.join()
logger.setLevel(logging.NOTSET)
root_logger.setLevel(LEVEL2)
p = self.Process(target=self._test_level, args=(writer,))
p.start()
self.assertEqual(LEVEL2, reader.recv())
p.join()
root_logger.setLevel(root_level)
logger.setLevel(level=LOG_LEVEL)
# class _TestLoggingProcessName(BaseTestCase):
#
# def handle(self, record):
# assert record.processName == multiprocessing.current_process().name
# self.__handled = True
#
# def test_logging(self):
# handler = logging.Handler()
# handler.handle = self.handle
# self.__handled = False
# # Bypass getLogger() and side-effects
# logger = logging.getLoggerClass()(
# 'multiprocessing.test.TestLoggingProcessName')
# logger.addHandler(handler)
# logger.propagate = False
#
# logger.warn('foo')
# assert self.__handled
#
# Check that Process.join() retries if os.waitpid() fails with EINTR
#
class _TestPollEintr(BaseTestCase):
ALLOWED_TYPES = ('processes',)
@classmethod
def _killer(cls, pid):
time.sleep(0.1)
os.kill(pid, signal.SIGUSR1)
@unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1')
def test_poll_eintr(self):
got_signal = [False]
def record(*args):
got_signal[0] = True
pid = os.getpid()
oldhandler = signal.signal(signal.SIGUSR1, record)
try:
killer = self.Process(target=self._killer, args=(pid,))
killer.start()
try:
p = self.Process(target=time.sleep, args=(2,))
p.start()
p.join()
finally:
killer.join()
self.assertTrue(got_signal[0])
self.assertEqual(p.exitcode, 0)
finally:
signal.signal(signal.SIGUSR1, oldhandler)
#
# Test to verify handle verification, see issue 3321
#
class TestInvalidHandle(unittest.TestCase):
@unittest.skipIf(WIN32, "skipped on Windows")
def test_invalid_handles(self):
conn = multiprocessing.connection.Connection(44977608)
# check that poll() doesn't crash
try:
conn.poll()
except (ValueError, OSError):
pass
finally:
# Hack private attribute _handle to avoid printing an error
# in conn.__del__
conn._handle = None
self.assertRaises((ValueError, OSError),
multiprocessing.connection.Connection, -1)
class OtherTest(unittest.TestCase):
# TODO: add more tests for deliver/answer challenge.
def test_deliver_challenge_auth_failure(self):
class _FakeConnection(object):
def recv_bytes(self, size):
return b'something bogus'
def send_bytes(self, data):
pass
self.assertRaises(multiprocessing.AuthenticationError,
multiprocessing.connection.deliver_challenge,
_FakeConnection(), b'abc')
def test_answer_challenge_auth_failure(self):
class _FakeConnection(object):
def __init__(self):
self.count = 0
def recv_bytes(self, size):
self.count += 1
if self.count == 1:
return multiprocessing.connection.CHALLENGE
elif self.count == 2:
return b'something bogus'
return b''
def send_bytes(self, data):
pass
self.assertRaises(multiprocessing.AuthenticationError,
multiprocessing.connection.answer_challenge,
_FakeConnection(), b'abc')
#
# Test Manager.start()/Pool.__init__() initializer feature - see issue 5585
#
def initializer(ns):
ns.test += 1
class TestInitializers(unittest.TestCase):
def setUp(self):
self.mgr = multiprocessing.Manager()
self.ns = self.mgr.Namespace()
self.ns.test = 0
def tearDown(self):
self.mgr.shutdown()
self.mgr.join()
def test_manager_initializer(self):
m = multiprocessing.managers.SyncManager()
self.assertRaises(TypeError, m.start, 1)
m.start(initializer, (self.ns,))
self.assertEqual(self.ns.test, 1)
m.shutdown()
m.join()
def test_pool_initializer(self):
self.assertRaises(TypeError, multiprocessing.Pool, initializer=1)
p = multiprocessing.Pool(1, initializer, (self.ns,))
p.close()
p.join()
self.assertEqual(self.ns.test, 1)
#
# Issue 5155, 5313, 5331: Test process in processes
# Verifies os.close(sys.stdin.fileno) vs. sys.stdin.close() behavior
#
def _this_sub_process(q):
try:
item = q.get(block=False)
except pyqueue.Empty:
pass
def _test_process():
queue = multiprocessing.Queue()
subProc = multiprocessing.Process(target=_this_sub_process, args=(queue,))
subProc.daemon = True
subProc.start()
subProc.join()
def _afunc(x):
return x*x
def pool_in_process():
pool = multiprocessing.Pool(processes=4)
x = pool.map(_afunc, [1, 2, 3, 4, 5, 6, 7])
pool.close()
pool.join()
class _file_like(object):
def __init__(self, delegate):
self._delegate = delegate
self._pid = None
@property
def cache(self):
pid = os.getpid()
# There are no race conditions since fork keeps only the running thread
if pid != self._pid:
self._pid = pid
self._cache = []
return self._cache
def write(self, data):
self.cache.append(data)
def flush(self):
self._delegate.write(''.join(self.cache))
self._cache = []
class TestStdinBadfiledescriptor(unittest.TestCase):
def test_queue_in_process(self):
proc = multiprocessing.Process(target=_test_process)
proc.start()
proc.join()
def test_pool_in_process(self):
p = multiprocessing.Process(target=pool_in_process)
p.start()
p.join()
def test_flushing(self):
sio = io.StringIO()
flike = _file_like(sio)
flike.write('foo')
proc = multiprocessing.Process(target=lambda: flike.flush())
flike.flush()
assert sio.getvalue() == 'foo'
class TestWait(unittest.TestCase):
@classmethod
def _child_test_wait(cls, w, slow):
for i in range(10):
if slow:
time.sleep(random.random()*0.1)
w.send((i, os.getpid()))
w.close()
def test_wait(self, slow=False):
from multiprocessing.connection import wait
readers = []
procs = []
messages = []
for i in range(4):
r, w = multiprocessing.Pipe(duplex=False)
p = multiprocessing.Process(target=self._child_test_wait, args=(w, slow))
p.daemon = True
p.start()
w.close()
readers.append(r)
procs.append(p)
self.addCleanup(p.join)
while readers:
for r in wait(readers):
try:
msg = r.recv()
except EOFError:
readers.remove(r)
r.close()
else:
messages.append(msg)
messages.sort()
expected = sorted((i, p.pid) for i in range(10) for p in procs)
self.assertEqual(messages, expected)
@classmethod
def _child_test_wait_socket(cls, address, slow):
s = socket.socket()
s.connect(address)
for i in range(10):
if slow:
time.sleep(random.random()*0.1)
s.sendall(('%s\n' % i).encode('ascii'))
s.close()
def test_wait_socket(self, slow=False):
from multiprocessing.connection import wait
l = socket.socket()
l.bind((support.HOST, 0))
l.listen()
addr = l.getsockname()
readers = []
procs = []
dic = {}
for i in range(4):
p = multiprocessing.Process(target=self._child_test_wait_socket,
args=(addr, slow))
p.daemon = True
p.start()
procs.append(p)
self.addCleanup(p.join)
for i in range(4):
r, _ = l.accept()
readers.append(r)
dic[r] = []
l.close()
while readers:
for r in wait(readers):
msg = r.recv(32)
if not msg:
readers.remove(r)
r.close()
else:
dic[r].append(msg)
expected = ''.join('%s\n' % i for i in range(10)).encode('ascii')
for v in dic.values():
self.assertEqual(b''.join(v), expected)
def test_wait_slow(self):
self.test_wait(True)
def test_wait_socket_slow(self):
self.test_wait_socket(True)
def test_wait_timeout(self):
from multiprocessing.connection import wait
expected = 5
a, b = multiprocessing.Pipe()
start = time.time()
res = wait([a, b], expected)
delta = time.time() - start
self.assertEqual(res, [])
self.assertLess(delta, expected * 2)
self.assertGreater(delta, expected * 0.5)
b.send(None)
start = time.time()
res = wait([a, b], 20)
delta = time.time() - start
self.assertEqual(res, [a])
self.assertLess(delta, 0.4)
@classmethod
def signal_and_sleep(cls, sem, period):
sem.release()
time.sleep(period)
def test_wait_integer(self):
from multiprocessing.connection import wait
expected = 3
sorted_ = lambda l: sorted(l, key=lambda x: id(x))
sem = multiprocessing.Semaphore(0)
a, b = multiprocessing.Pipe()
p = multiprocessing.Process(target=self.signal_and_sleep,
args=(sem, expected))
p.start()
self.assertIsInstance(p.sentinel, int)
self.assertTrue(sem.acquire(timeout=20))
start = time.time()
res = wait([a, p.sentinel, b], expected + 20)
delta = time.time() - start
self.assertEqual(res, [p.sentinel])
self.assertLess(delta, expected + 2)
self.assertGreater(delta, expected - 2)
a.send(None)
start = time.time()
res = wait([a, p.sentinel, b], 20)
delta = time.time() - start
self.assertEqual(sorted_(res), sorted_([p.sentinel, b]))
self.assertLess(delta, 0.4)
b.send(None)
start = time.time()
res = wait([a, p.sentinel, b], 20)
delta = time.time() - start
self.assertEqual(sorted_(res), sorted_([a, p.sentinel, b]))
self.assertLess(delta, 0.4)
p.terminate()
p.join()
def test_neg_timeout(self):
from multiprocessing.connection import wait
a, b = multiprocessing.Pipe()
t = time.time()
res = wait([a], timeout=-1)
t = time.time() - t
self.assertEqual(res, [])
self.assertLess(t, 1)
a.close()
b.close()
#
# Issue 14151: Test invalid family on invalid environment
#
class TestInvalidFamily(unittest.TestCase):
@unittest.skipIf(WIN32, "skipped on Windows")
def test_invalid_family(self):
with self.assertRaises(ValueError):
multiprocessing.connection.Listener(r'\\.\test')
@unittest.skipUnless(WIN32, "skipped on non-Windows platforms")
def test_invalid_family_win32(self):
with self.assertRaises(ValueError):
multiprocessing.connection.Listener('/var/test.pipe')
#
# Issue 12098: check sys.flags of child matches that for parent
#
class TestFlags(unittest.TestCase):
@classmethod
def run_in_grandchild(cls, conn):
conn.send(tuple(sys.flags))
@classmethod
def run_in_child(cls):
import json
r, w = multiprocessing.Pipe(duplex=False)
p = multiprocessing.Process(target=cls.run_in_grandchild, args=(w,))
p.start()
grandchild_flags = r.recv()
p.join()
r.close()
w.close()
flags = (tuple(sys.flags), grandchild_flags)
print(json.dumps(flags))
def test_flags(self):
import json, subprocess
# start child process using unusual flags
prog = ('from test._test_multiprocessing import TestFlags; ' +
'TestFlags.run_in_child()')
data = subprocess.check_output(
[sys.executable, '-E', '-S', '-O', '-c', prog])
child_flags, grandchild_flags = json.loads(data.decode('ascii'))
self.assertEqual(child_flags, grandchild_flags)
#
# Test interaction with socket timeouts - see Issue #6056
#
class TestTimeouts(unittest.TestCase):
@classmethod
def _test_timeout(cls, child, address):
time.sleep(1)
child.send(123)
child.close()
conn = multiprocessing.connection.Client(address)
conn.send(456)
conn.close()
def test_timeout(self):
old_timeout = socket.getdefaulttimeout()
try:
socket.setdefaulttimeout(0.1)
parent, child = multiprocessing.Pipe(duplex=True)
l = multiprocessing.connection.Listener(family='AF_INET')
p = multiprocessing.Process(target=self._test_timeout,
args=(child, l.address))
p.start()
child.close()
self.assertEqual(parent.recv(), 123)
parent.close()
conn = l.accept()
self.assertEqual(conn.recv(), 456)
conn.close()
l.close()
p.join(10)
finally:
socket.setdefaulttimeout(old_timeout)
#
# Test what happens with no "if __name__ == '__main__'"
#
class TestNoForkBomb(unittest.TestCase):
def test_noforkbomb(self):
sm = multiprocessing.get_start_method()
name = os.path.join(os.path.dirname(__file__), 'mp_fork_bomb.py')
if sm != 'fork':
rc, out, err = support.script_helper.assert_python_failure(name, sm)
self.assertEqual(out, b'')
self.assertIn(b'RuntimeError', err)
else:
rc, out, err = support.script_helper.assert_python_ok(name, sm)
self.assertEqual(out.rstrip(), b'123')
self.assertEqual(err, b'')
#
# Issue #17555: ForkAwareThreadLock
#
class TestForkAwareThreadLock(unittest.TestCase):
# We recursively start processes. Issue #17555 meant that the
# after fork registry would get duplicate entries for the same
# lock. The size of the registry at generation n was ~2**n.
@classmethod
def child(cls, n, conn):
if n > 1:
p = multiprocessing.Process(target=cls.child, args=(n-1, conn))
p.start()
conn.close()
p.join(timeout=5)
else:
conn.send(len(util._afterfork_registry))
conn.close()
def test_lock(self):
r, w = multiprocessing.Pipe(False)
l = util.ForkAwareThreadLock()
old_size = len(util._afterfork_registry)
p = multiprocessing.Process(target=self.child, args=(5, w))
p.start()
w.close()
new_size = r.recv()
p.join(timeout=5)
self.assertLessEqual(new_size, old_size)
#
# Check that non-forked child processes do not inherit unneeded fds/handles
#
class TestCloseFds(unittest.TestCase):
def get_high_socket_fd(self):
if WIN32:
# The child process will not have any socket handles, so
# calling socket.fromfd() should produce WSAENOTSOCK even
# if there is a handle of the same number.
return socket.socket().detach()
else:
# We want to produce a socket with an fd high enough that a
# freshly created child process will not have any fds as high.
fd = socket.socket().detach()
to_close = []
while fd < 50:
to_close.append(fd)
fd = os.dup(fd)
for x in to_close:
os.close(x)
return fd
def close(self, fd):
if WIN32:
socket.socket(fileno=fd).close()
else:
os.close(fd)
@classmethod
def _test_closefds(cls, conn, fd):
try:
s = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
except Exception as e:
conn.send(e)
else:
s.close()
conn.send(None)
def test_closefd(self):
if not HAS_REDUCTION:
raise unittest.SkipTest('requires fd pickling')
reader, writer = multiprocessing.Pipe()
fd = self.get_high_socket_fd()
try:
p = multiprocessing.Process(target=self._test_closefds,
args=(writer, fd))
p.start()
writer.close()
e = reader.recv()
p.join(timeout=5)
finally:
self.close(fd)
writer.close()
reader.close()
if multiprocessing.get_start_method() == 'fork':
self.assertIs(e, None)
else:
WSAENOTSOCK = 10038
self.assertIsInstance(e, OSError)
self.assertTrue(e.errno == errno.EBADF or
e.winerror == WSAENOTSOCK, e)
#
# Issue #17097: EINTR should be ignored by recv(), send(), accept() etc
#
class TestIgnoreEINTR(unittest.TestCase):
# Sending CONN_MAX_SIZE bytes into a multiprocessing pipe must block
CONN_MAX_SIZE = max(support.PIPE_MAX_SIZE, support.SOCK_MAX_SIZE)
@classmethod
def _test_ignore(cls, conn):
def handler(signum, frame):
pass
signal.signal(signal.SIGUSR1, handler)
conn.send('ready')
x = conn.recv()
conn.send(x)
conn.send_bytes(b'x' * cls.CONN_MAX_SIZE)
@unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1')
def test_ignore(self):
conn, child_conn = multiprocessing.Pipe()
try:
p = multiprocessing.Process(target=self._test_ignore,
args=(child_conn,))
p.daemon = True
p.start()
child_conn.close()
self.assertEqual(conn.recv(), 'ready')
time.sleep(0.1)
os.kill(p.pid, signal.SIGUSR1)
time.sleep(0.1)
conn.send(1234)
self.assertEqual(conn.recv(), 1234)
time.sleep(0.1)
os.kill(p.pid, signal.SIGUSR1)
self.assertEqual(conn.recv_bytes(), b'x' * self.CONN_MAX_SIZE)
time.sleep(0.1)
p.join()
finally:
conn.close()
@classmethod
def _test_ignore_listener(cls, conn):
def handler(signum, frame):
pass
signal.signal(signal.SIGUSR1, handler)
with multiprocessing.connection.Listener() as l:
conn.send(l.address)
a = l.accept()
a.send('welcome')
@unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1')
def test_ignore_listener(self):
conn, child_conn = multiprocessing.Pipe()
try:
p = multiprocessing.Process(target=self._test_ignore_listener,
args=(child_conn,))
p.daemon = True
p.start()
child_conn.close()
address = conn.recv()
time.sleep(0.1)
os.kill(p.pid, signal.SIGUSR1)
time.sleep(0.1)
client = multiprocessing.connection.Client(address)
self.assertEqual(client.recv(), 'welcome')
p.join()
finally:
conn.close()
class TestStartMethod(unittest.TestCase):
@classmethod
def _check_context(cls, conn):
conn.send(multiprocessing.get_start_method())
def check_context(self, ctx):
r, w = ctx.Pipe(duplex=False)
p = ctx.Process(target=self._check_context, args=(w,))
p.start()
w.close()
child_method = r.recv()
r.close()
p.join()
self.assertEqual(child_method, ctx.get_start_method())
def test_context(self):
for method in ('fork', 'spawn', 'forkserver'):
try:
ctx = multiprocessing.get_context(method)
except ValueError:
continue
self.assertEqual(ctx.get_start_method(), method)
self.assertIs(ctx.get_context(), ctx)
self.assertRaises(ValueError, ctx.set_start_method, 'spawn')
self.assertRaises(ValueError, ctx.set_start_method, None)
self.check_context(ctx)
def test_set_get(self):
multiprocessing.set_forkserver_preload(PRELOAD)
count = 0
old_method = multiprocessing.get_start_method()
try:
for method in ('fork', 'spawn', 'forkserver'):
try:
multiprocessing.set_start_method(method, force=True)
except ValueError:
continue
self.assertEqual(multiprocessing.get_start_method(), method)
ctx = multiprocessing.get_context()
self.assertEqual(ctx.get_start_method(), method)
self.assertTrue(type(ctx).__name__.lower().startswith(method))
self.assertTrue(
ctx.Process.__name__.lower().startswith(method))
self.check_context(multiprocessing)
count += 1
finally:
multiprocessing.set_start_method(old_method, force=True)
self.assertGreaterEqual(count, 1)
def test_get_all(self):
methods = multiprocessing.get_all_start_methods()
if sys.platform == 'win32':
self.assertEqual(methods, ['spawn'])
else:
self.assertTrue(methods == ['fork', 'spawn'] or
methods == ['fork', 'spawn', 'forkserver'])
def test_preload_resources(self):
if multiprocessing.get_start_method() != 'forkserver':
self.skipTest("test only relevant for 'forkserver' method")
name = os.path.join(os.path.dirname(__file__), 'mp_preload.py')
rc, out, err = support.script_helper.assert_python_ok(name)
out = out.decode()
err = err.decode()
if out.rstrip() != 'ok' or err != '':
print(out)
print(err)
self.fail("failed spawning forkserver or grandchild")
@unittest.skipIf(sys.platform == "win32",
"test semantics don't make sense on Windows")
class TestSemaphoreTracker(unittest.TestCase):
def test_semaphore_tracker(self):
#
# Check that killing process does not leak named semaphores
#
import subprocess
cmd = '''if 1:
import multiprocessing as mp, time, os
mp.set_start_method("spawn")
lock1 = mp.Lock()
lock2 = mp.Lock()
os.write(%d, lock1._semlock.name.encode("ascii") + b"\\n")
os.write(%d, lock2._semlock.name.encode("ascii") + b"\\n")
time.sleep(10)
'''
r, w = os.pipe()
p = subprocess.Popen([sys.executable,
'-E', '-c', cmd % (w, w)],
pass_fds=[w],
stderr=subprocess.PIPE)
os.close(w)
with open(r, 'rb', closefd=True) as f:
name1 = f.readline().rstrip().decode('ascii')
name2 = f.readline().rstrip().decode('ascii')
_multiprocessing.sem_unlink(name1)
p.terminate()
p.wait()
time.sleep(2.0)
with self.assertRaises(OSError) as ctx:
_multiprocessing.sem_unlink(name2)
# docs say it should be ENOENT, but OSX seems to give EINVAL
self.assertIn(ctx.exception.errno, (errno.ENOENT, errno.EINVAL))
err = p.stderr.read().decode('utf-8')
p.stderr.close()
expected = 'semaphore_tracker: There appear to be 2 leaked semaphores'
self.assertRegex(err, expected)
self.assertRegex(err, r'semaphore_tracker: %r: \[Errno' % name1)
def check_semaphore_tracker_death(self, signum, should_die):
# bpo-31310: if the semaphore tracker process has died, it should
# be restarted implicitly.
from multiprocessing.semaphore_tracker import _semaphore_tracker
_semaphore_tracker.ensure_running()
pid = _semaphore_tracker._pid
os.kill(pid, signum)
time.sleep(1.0) # give it time to die
ctx = multiprocessing.get_context("spawn")
with contextlib.ExitStack() as stack:
if should_die:
stack.enter_context(self.assertWarnsRegex(
UserWarning,
"semaphore_tracker: process died"))
sem = ctx.Semaphore()
sem.acquire()
sem.release()
wr = weakref.ref(sem)
# ensure `sem` gets collected, which triggers communication with
# the semaphore tracker
del sem
gc.collect()
self.assertIsNone(wr())
def test_semaphore_tracker_sigint(self):
# Catchable signal (ignored by semaphore tracker)
self.check_semaphore_tracker_death(signal.SIGINT, False)
def test_semaphore_tracker_sigkill(self):
# Uncatchable signal.
self.check_semaphore_tracker_death(signal.SIGKILL, True)
class TestSimpleQueue(unittest.TestCase):
@classmethod
def _test_empty(cls, queue, child_can_start, parent_can_continue):
child_can_start.wait()
# issue 30301, could fail under spawn and forkserver
try:
queue.put(queue.empty())
queue.put(queue.empty())
finally:
parent_can_continue.set()
def test_empty(self):
queue = multiprocessing.SimpleQueue()
child_can_start = multiprocessing.Event()
parent_can_continue = multiprocessing.Event()
proc = multiprocessing.Process(
target=self._test_empty,
args=(queue, child_can_start, parent_can_continue)
)
proc.daemon = True
proc.start()
self.assertTrue(queue.empty())
child_can_start.set()
parent_can_continue.wait()
self.assertFalse(queue.empty())
self.assertEqual(queue.get(), True)
self.assertEqual(queue.get(), False)
self.assertTrue(queue.empty())
proc.join()
#
# Mixins
#
class BaseMixin(object):
@classmethod
def setUpClass(cls):
cls.dangling = (multiprocessing.process._dangling.copy(),
threading._dangling.copy())
@classmethod
def tearDownClass(cls):
# bpo-26762: Some multiprocessing objects like Pool create reference
# cycles. Trigger a garbage collection to break these cycles.
support.gc_collect()
processes = set(multiprocessing.process._dangling) - set(cls.dangling[0])
if processes:
print('Warning -- Dangling processes: %s' % processes,
file=sys.stderr)
processes = None
threads = set(threading._dangling) - set(cls.dangling[1])
if threads:
print('Warning -- Dangling threads: %s' % threads,
file=sys.stderr)
threads = None
class ProcessesMixin(BaseMixin):
TYPE = 'processes'
Process = multiprocessing.Process
connection = multiprocessing.connection
current_process = staticmethod(multiprocessing.current_process)
active_children = staticmethod(multiprocessing.active_children)
Pool = staticmethod(multiprocessing.Pool)
Pipe = staticmethod(multiprocessing.Pipe)
Queue = staticmethod(multiprocessing.Queue)
JoinableQueue = staticmethod(multiprocessing.JoinableQueue)
Lock = staticmethod(multiprocessing.Lock)
RLock = staticmethod(multiprocessing.RLock)
Semaphore = staticmethod(multiprocessing.Semaphore)
BoundedSemaphore = staticmethod(multiprocessing.BoundedSemaphore)
Condition = staticmethod(multiprocessing.Condition)
Event = staticmethod(multiprocessing.Event)
Barrier = staticmethod(multiprocessing.Barrier)
Value = staticmethod(multiprocessing.Value)
Array = staticmethod(multiprocessing.Array)
RawValue = staticmethod(multiprocessing.RawValue)
RawArray = staticmethod(multiprocessing.RawArray)
class ManagerMixin(BaseMixin):
TYPE = 'manager'
Process = multiprocessing.Process
Queue = property(operator.attrgetter('manager.Queue'))
JoinableQueue = property(operator.attrgetter('manager.JoinableQueue'))
Lock = property(operator.attrgetter('manager.Lock'))
RLock = property(operator.attrgetter('manager.RLock'))
Semaphore = property(operator.attrgetter('manager.Semaphore'))
BoundedSemaphore = property(operator.attrgetter('manager.BoundedSemaphore'))
Condition = property(operator.attrgetter('manager.Condition'))
Event = property(operator.attrgetter('manager.Event'))
Barrier = property(operator.attrgetter('manager.Barrier'))
Value = property(operator.attrgetter('manager.Value'))
Array = property(operator.attrgetter('manager.Array'))
list = property(operator.attrgetter('manager.list'))
dict = property(operator.attrgetter('manager.dict'))
Namespace = property(operator.attrgetter('manager.Namespace'))
@classmethod
def Pool(cls, *args, **kwds):
return cls.manager.Pool(*args, **kwds)
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.manager = multiprocessing.Manager()
@classmethod
def tearDownClass(cls):
# only the manager process should be returned by active_children()
# but this can take a bit on slow machines, so wait a few seconds
# if there are other children too (see #17395)
start_time = time.monotonic()
t = 0.01
while len(multiprocessing.active_children()) > 1:
time.sleep(t)
t *= 2
dt = time.monotonic() - start_time
if dt >= 5.0:
print("Warning -- multiprocessing.Manager still has %s active "
"children after %s seconds"
% (multiprocessing.active_children(), dt),
file=sys.stderr)
break
gc.collect() # do garbage collection
if cls.manager._number_of_objects() != 0:
# This is not really an error since some tests do not
# ensure that all processes which hold a reference to a
# managed object have been joined.
print('Warning -- Shared objects which still exist at manager '
'shutdown:')
print(cls.manager._debug_info())
cls.manager.shutdown()
cls.manager.join()
cls.manager = None
super().tearDownClass()
class ThreadsMixin(BaseMixin):
TYPE = 'threads'
Process = multiprocessing.dummy.Process
connection = multiprocessing.dummy.connection
current_process = staticmethod(multiprocessing.dummy.current_process)
active_children = staticmethod(multiprocessing.dummy.active_children)
Pool = staticmethod(multiprocessing.dummy.Pool)
Pipe = staticmethod(multiprocessing.dummy.Pipe)
Queue = staticmethod(multiprocessing.dummy.Queue)
JoinableQueue = staticmethod(multiprocessing.dummy.JoinableQueue)
Lock = staticmethod(multiprocessing.dummy.Lock)
RLock = staticmethod(multiprocessing.dummy.RLock)
Semaphore = staticmethod(multiprocessing.dummy.Semaphore)
BoundedSemaphore = staticmethod(multiprocessing.dummy.BoundedSemaphore)
Condition = staticmethod(multiprocessing.dummy.Condition)
Event = staticmethod(multiprocessing.dummy.Event)
Barrier = staticmethod(multiprocessing.dummy.Barrier)
Value = staticmethod(multiprocessing.dummy.Value)
Array = staticmethod(multiprocessing.dummy.Array)
#
# Functions used to create test cases from the base ones in this module
#
def install_tests_in_module_dict(remote_globs, start_method):
__module__ = remote_globs['__name__']
local_globs = globals()
ALL_TYPES = {'processes', 'threads', 'manager'}
for name, base in local_globs.items():
if not isinstance(base, type):
continue
if issubclass(base, BaseTestCase):
if base is BaseTestCase:
continue
assert set(base.ALLOWED_TYPES) <= ALL_TYPES, base.ALLOWED_TYPES
for type_ in base.ALLOWED_TYPES:
newname = 'With' + type_.capitalize() + name[1:]
Mixin = local_globs[type_.capitalize() + 'Mixin']
class Temp(base, Mixin, unittest.TestCase):
pass
Temp.__name__ = Temp.__qualname__ = newname
Temp.__module__ = __module__
remote_globs[newname] = Temp
elif issubclass(base, unittest.TestCase):
class Temp(base, object):
pass
Temp.__name__ = Temp.__qualname__ = name
Temp.__module__ = __module__
remote_globs[name] = Temp
dangling = [None, None]
old_start_method = [None]
def setUpModule():
multiprocessing.set_forkserver_preload(PRELOAD)
multiprocessing.process._cleanup()
dangling[0] = multiprocessing.process._dangling.copy()
dangling[1] = threading._dangling.copy()
old_start_method[0] = multiprocessing.get_start_method(allow_none=True)
try:
multiprocessing.set_start_method(start_method, force=True)
except ValueError:
raise unittest.SkipTest(start_method +
' start method not supported')
if sys.platform.startswith("linux"):
try:
lock = multiprocessing.RLock()
except OSError:
raise unittest.SkipTest("OSError raises on RLock creation, "
"see issue 3111!")
check_enough_semaphores()
util.get_temp_dir() # creates temp directory
multiprocessing.get_logger().setLevel(LOG_LEVEL)
def tearDownModule():
need_sleep = False
# bpo-26762: Some multiprocessing objects like Pool create reference
# cycles. Trigger a garbage collection to break these cycles.
support.gc_collect()
multiprocessing.set_start_method(old_start_method[0], force=True)
# pause a bit so we don't get warning about dangling threads/processes
processes = set(multiprocessing.process._dangling) - set(dangling[0])
if processes:
need_sleep = True
print('Warning -- Dangling processes: %s' % processes,
file=sys.stderr)
processes = None
threads = set(threading._dangling) - set(dangling[1])
if threads:
need_sleep = True
print('Warning -- Dangling threads: %s' % threads,
file=sys.stderr)
threads = None
# Sleep 500 ms to give time to child processes to complete.
if need_sleep:
time.sleep(0.5)
multiprocessing.process._cleanup()
support.gc_collect()
remote_globs['setUpModule'] = setUpModule
remote_globs['tearDownModule'] = tearDownModule
| 143,810 | 4,523 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_quopri.py | import unittest
import sys, io, subprocess
import quopri
ENCSAMPLE = b"""\
Here's a bunch of special=20
=A1=A2=A3=A4=A5=A6=A7=A8=A9
=AA=AB=AC=AD=AE=AF=B0=B1=B2=B3
=B4=B5=B6=B7=B8=B9=BA=BB=BC=BD=BE
=BF=C0=C1=C2=C3=C4=C5=C6
=C7=C8=C9=CA=CB=CC=CD=CE=CF
=D0=D1=D2=D3=D4=D5=D6=D7
=D8=D9=DA=DB=DC=DD=DE=DF
=E0=E1=E2=E3=E4=E5=E6=E7
=E8=E9=EA=EB=EC=ED=EE=EF
=F0=F1=F2=F3=F4=F5=F6=F7
=F8=F9=FA=FB=FC=FD=FE=FF
characters... have fun!
"""
# First line ends with a space
DECSAMPLE = b"Here's a bunch of special \n" + \
b"""\
\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9
\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3
\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe
\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6
\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf
\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7
\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf
\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7
\xe8\xe9\xea\xeb\xec\xed\xee\xef
\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7
\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff
characters... have fun!
"""
def withpythonimplementation(testfunc):
def newtest(self):
# Test default implementation
testfunc(self)
# Test Python implementation
if quopri.b2a_qp is not None or quopri.a2b_qp is not None:
oldencode = quopri.b2a_qp
olddecode = quopri.a2b_qp
try:
quopri.b2a_qp = None
quopri.a2b_qp = None
testfunc(self)
finally:
quopri.b2a_qp = oldencode
quopri.a2b_qp = olddecode
newtest.__name__ = testfunc.__name__
return newtest
class QuopriTestCase(unittest.TestCase):
# Each entry is a tuple of (plaintext, encoded string). These strings are
# used in the "quotetabs=0" tests.
STRINGS = (
# Some normal strings
(b'hello', b'hello'),
(b'''hello
there
world''', b'''hello
there
world'''),
(b'''hello
there
world
''', b'''hello
there
world
'''),
(b'\201\202\203', b'=81=82=83'),
# Add some trailing MUST QUOTE strings
(b'hello ', b'hello=20'),
(b'hello\t', b'hello=09'),
# Some long lines. First, a single line of 108 characters
(b'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\xd8\xd9\xda\xdb\xdc\xdd\xde\xdfxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
b'''xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=D8=D9=DA=DB=DC=DD=DE=DFx=
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'''),
# A line of exactly 76 characters, no soft line break should be needed
(b'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy',
b'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'),
# A line of 77 characters, forcing a soft line break at position 75,
# and a second line of exactly 2 characters (because the soft line
# break `=' sign counts against the line length limit).
(b'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz',
b'''zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz=
zz'''),
# A line of 151 characters, forcing a soft line break at position 75,
# with a second line of exactly 76 characters and no trailing =
(b'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz',
b'''zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz=
zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'''),
# A string containing a hard line break, but which the first line is
# 151 characters and the second line is exactly 76 characters. This
# should leave us with three lines, the first which has a soft line
# break, and which the second and third do not.
(b'''yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz''',
b'''yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy=
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'''),
# Now some really complex stuff ;)
(DECSAMPLE, ENCSAMPLE),
)
# These are used in the "quotetabs=1" tests.
ESTRINGS = (
(b'hello world', b'hello=20world'),
(b'hello\tworld', b'hello=09world'),
)
# These are used in the "header=1" tests.
HSTRINGS = (
(b'hello world', b'hello_world'),
(b'hello_world', b'hello=5Fworld'),
)
@withpythonimplementation
def test_encodestring(self):
for p, e in self.STRINGS:
self.assertEqual(quopri.encodestring(p), e)
@withpythonimplementation
def test_decodestring(self):
for p, e in self.STRINGS:
self.assertEqual(quopri.decodestring(e), p)
@withpythonimplementation
def test_decodestring_double_equals(self):
# Issue 21511 - Ensure that byte string is compared to byte string
# instead of int byte value
decoded_value, encoded_value = (b"123=four", b"123==four")
self.assertEqual(quopri.decodestring(encoded_value), decoded_value)
@withpythonimplementation
def test_idempotent_string(self):
for p, e in self.STRINGS:
self.assertEqual(quopri.decodestring(quopri.encodestring(e)), e)
@withpythonimplementation
def test_encode(self):
for p, e in self.STRINGS:
infp = io.BytesIO(p)
outfp = io.BytesIO()
quopri.encode(infp, outfp, quotetabs=False)
self.assertEqual(outfp.getvalue(), e)
@withpythonimplementation
def test_decode(self):
for p, e in self.STRINGS:
infp = io.BytesIO(e)
outfp = io.BytesIO()
quopri.decode(infp, outfp)
self.assertEqual(outfp.getvalue(), p)
@withpythonimplementation
def test_embedded_ws(self):
for p, e in self.ESTRINGS:
self.assertEqual(quopri.encodestring(p, quotetabs=True), e)
self.assertEqual(quopri.decodestring(e), p)
@withpythonimplementation
def test_encode_header(self):
for p, e in self.HSTRINGS:
self.assertEqual(quopri.encodestring(p, header=True), e)
@withpythonimplementation
def test_decode_header(self):
for p, e in self.HSTRINGS:
self.assertEqual(quopri.decodestring(e, header=True), p)
def test_scriptencode(self):
(p, e) = self.STRINGS[-1]
process = subprocess.Popen([sys.executable, "-mquopri"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
self.addCleanup(process.stdout.close)
cout, cerr = process.communicate(p)
# On Windows, Python will output the result to stdout using
# CRLF, as the mode of stdout is text mode. To compare this
# with the expected result, we need to do a line-by-line comparison.
cout = cout.decode('latin-1').splitlines()
e = e.decode('latin-1').splitlines()
assert len(cout)==len(e)
for i in range(len(cout)):
self.assertEqual(cout[i], e[i])
self.assertEqual(cout, e)
def test_scriptdecode(self):
(p, e) = self.STRINGS[-1]
process = subprocess.Popen([sys.executable, "-mquopri", "-d"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
self.addCleanup(process.stdout.close)
cout, cerr = process.communicate(e)
cout = cout.decode('latin-1')
p = p.decode('latin-1')
self.assertEqual(cout.splitlines(), p.splitlines())
if __name__ == "__main__":
unittest.main()
| 7,962 | 211 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/list_tests.py | """
Tests common to list and UserList.UserList
"""
import sys
import os
import unittest
import cosmo
from functools import cmp_to_key
from test import support, seq_tests
class CommonTest(seq_tests.CommonTest):
def test_init(self):
# Iterable arg is optional
self.assertEqual(self.type2test([]), self.type2test())
# Init clears previous values
a = self.type2test([1, 2, 3])
a.__init__()
self.assertEqual(a, self.type2test([]))
# Init overwrites previous values
a = self.type2test([1, 2, 3])
a.__init__([4, 5, 6])
self.assertEqual(a, self.type2test([4, 5, 6]))
# Mutables always return a new object
b = self.type2test(a)
self.assertNotEqual(id(a), id(b))
self.assertEqual(a, b)
def test_getitem_error(self):
msg = "list indices must be integers or slices"
with self.assertRaisesRegex(TypeError, msg):
a = []
a['a'] = "python"
def test_repr(self):
l0 = []
l2 = [0, 1, 2]
a0 = self.type2test(l0)
a2 = self.type2test(l2)
self.assertEqual(str(a0), str(l0))
self.assertEqual(repr(a0), repr(l0))
self.assertEqual(repr(a2), repr(l2))
self.assertEqual(str(a2), "[0, 1, 2]")
self.assertEqual(repr(a2), "[0, 1, 2]")
a2.append(a2)
a2.append(3)
self.assertEqual(str(a2), "[0, 1, 2, [...], 3]")
self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]")
@unittest.skipUnless(cosmo.MODE == "dbg", "disabled recursion checking")
def test_repr_deep(self):
a = self.type2test([])
for i in range(sys.getrecursionlimit() + 100):
a = self.type2test([a])
self.assertRaises(RecursionError, repr, a)
def test_print(self):
d = self.type2test(range(200))
d.append(d)
d.extend(range(200,400))
d.append(d)
d.append(400)
try:
with open(support.TESTFN, "w") as fo:
fo.write(str(d))
with open(support.TESTFN, "r") as fo:
self.assertEqual(fo.read(), repr(d))
finally:
os.remove(support.TESTFN)
def test_set_subscript(self):
a = self.type2test(range(20))
self.assertRaises(ValueError, a.__setitem__, slice(0, 10, 0), [1,2,3])
self.assertRaises(TypeError, a.__setitem__, slice(0, 10), 1)
self.assertRaises(ValueError, a.__setitem__, slice(0, 10, 2), [1,2])
self.assertRaises(TypeError, a.__getitem__, 'x', 1)
a[slice(2,10,3)] = [1,2,3]
self.assertEqual(a, self.type2test([0, 1, 1, 3, 4, 2, 6, 7, 3,
9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19]))
def test_reversed(self):
a = self.type2test(range(20))
r = reversed(a)
self.assertEqual(list(r), self.type2test(range(19, -1, -1)))
self.assertRaises(StopIteration, next, r)
self.assertEqual(list(reversed(self.type2test())),
self.type2test())
# Bug 3689: make sure list-reversed-iterator doesn't have __len__
self.assertRaises(TypeError, len, reversed([1,2,3]))
def test_setitem(self):
a = self.type2test([0, 1])
a[0] = 0
a[1] = 100
self.assertEqual(a, self.type2test([0, 100]))
a[-1] = 200
self.assertEqual(a, self.type2test([0, 200]))
a[-2] = 100
self.assertEqual(a, self.type2test([100, 200]))
self.assertRaises(IndexError, a.__setitem__, -3, 200)
self.assertRaises(IndexError, a.__setitem__, 2, 200)
a = self.type2test([])
self.assertRaises(IndexError, a.__setitem__, 0, 200)
self.assertRaises(IndexError, a.__setitem__, -1, 200)
self.assertRaises(TypeError, a.__setitem__)
a = self.type2test([0,1,2,3,4])
a[0] = 1
a[1] = 2
a[2] = 3
self.assertEqual(a, self.type2test([1,2,3,3,4]))
a[0] = 5
a[1] = 6
a[2] = 7
self.assertEqual(a, self.type2test([5,6,7,3,4]))
a[-2] = 88
a[-1] = 99
self.assertEqual(a, self.type2test([5,6,7,88,99]))
a[-2] = 8
a[-1] = 9
self.assertEqual(a, self.type2test([5,6,7,8,9]))
msg = "list indices must be integers or slices"
with self.assertRaisesRegex(TypeError, msg):
a['a'] = "python"
def test_delitem(self):
a = self.type2test([0, 1])
del a[1]
self.assertEqual(a, [0])
del a[0]
self.assertEqual(a, [])
a = self.type2test([0, 1])
del a[-2]
self.assertEqual(a, [1])
del a[-1]
self.assertEqual(a, [])
a = self.type2test([0, 1])
self.assertRaises(IndexError, a.__delitem__, -3)
self.assertRaises(IndexError, a.__delitem__, 2)
a = self.type2test([])
self.assertRaises(IndexError, a.__delitem__, 0)
self.assertRaises(TypeError, a.__delitem__)
def test_setslice(self):
l = [0, 1]
a = self.type2test(l)
for i in range(-3, 4):
a[:i] = l[:i]
self.assertEqual(a, l)
a2 = a[:]
a2[:i] = a[:i]
self.assertEqual(a2, a)
a[i:] = l[i:]
self.assertEqual(a, l)
a2 = a[:]
a2[i:] = a[i:]
self.assertEqual(a2, a)
for j in range(-3, 4):
a[i:j] = l[i:j]
self.assertEqual(a, l)
a2 = a[:]
a2[i:j] = a[i:j]
self.assertEqual(a2, a)
aa2 = a2[:]
aa2[:0] = [-2, -1]
self.assertEqual(aa2, [-2, -1, 0, 1])
aa2[0:] = []
self.assertEqual(aa2, [])
a = self.type2test([1, 2, 3, 4, 5])
a[:-1] = a
self.assertEqual(a, self.type2test([1, 2, 3, 4, 5, 5]))
a = self.type2test([1, 2, 3, 4, 5])
a[1:] = a
self.assertEqual(a, self.type2test([1, 1, 2, 3, 4, 5]))
a = self.type2test([1, 2, 3, 4, 5])
a[1:-1] = a
self.assertEqual(a, self.type2test([1, 1, 2, 3, 4, 5, 5]))
a = self.type2test([])
a[:] = tuple(range(10))
self.assertEqual(a, self.type2test(range(10)))
self.assertRaises(TypeError, a.__setitem__, slice(0, 1, 5))
self.assertRaises(TypeError, a.__setitem__)
def test_delslice(self):
a = self.type2test([0, 1])
del a[1:2]
del a[0:1]
self.assertEqual(a, self.type2test([]))
a = self.type2test([0, 1])
del a[1:2]
del a[0:1]
self.assertEqual(a, self.type2test([]))
a = self.type2test([0, 1])
del a[-2:-1]
self.assertEqual(a, self.type2test([1]))
a = self.type2test([0, 1])
del a[-2:-1]
self.assertEqual(a, self.type2test([1]))
a = self.type2test([0, 1])
del a[1:]
del a[:1]
self.assertEqual(a, self.type2test([]))
a = self.type2test([0, 1])
del a[1:]
del a[:1]
self.assertEqual(a, self.type2test([]))
a = self.type2test([0, 1])
del a[-1:]
self.assertEqual(a, self.type2test([0]))
a = self.type2test([0, 1])
del a[-1:]
self.assertEqual(a, self.type2test([0]))
a = self.type2test([0, 1])
del a[:]
self.assertEqual(a, self.type2test([]))
def test_append(self):
a = self.type2test([])
a.append(0)
a.append(1)
a.append(2)
self.assertEqual(a, self.type2test([0, 1, 2]))
self.assertRaises(TypeError, a.append)
def test_extend(self):
a1 = self.type2test([0])
a2 = self.type2test((0, 1))
a = a1[:]
a.extend(a2)
self.assertEqual(a, a1 + a2)
a.extend(self.type2test([]))
self.assertEqual(a, a1 + a2)
a.extend(a)
self.assertEqual(a, self.type2test([0, 0, 1, 0, 0, 1]))
a = self.type2test("spam")
a.extend("eggs")
self.assertEqual(a, list("spameggs"))
self.assertRaises(TypeError, a.extend, None)
self.assertRaises(TypeError, a.extend)
# overflow test. issue1621
class CustomIter:
def __iter__(self):
return self
def __next__(self):
raise StopIteration
def __length_hint__(self):
return sys.maxsize
a = self.type2test([1,2,3,4])
a.extend(CustomIter())
self.assertEqual(a, [1,2,3,4])
def test_insert(self):
a = self.type2test([0, 1, 2])
a.insert(0, -2)
a.insert(1, -1)
a.insert(2, 0)
self.assertEqual(a, [-2, -1, 0, 0, 1, 2])
b = a[:]
b.insert(-2, "foo")
b.insert(-200, "left")
b.insert(200, "right")
self.assertEqual(b, self.type2test(["left",-2,-1,0,0,"foo",1,2,"right"]))
self.assertRaises(TypeError, a.insert)
def test_pop(self):
a = self.type2test([-1, 0, 1])
a.pop()
self.assertEqual(a, [-1, 0])
a.pop(0)
self.assertEqual(a, [0])
self.assertRaises(IndexError, a.pop, 5)
a.pop(0)
self.assertEqual(a, [])
self.assertRaises(IndexError, a.pop)
self.assertRaises(TypeError, a.pop, 42, 42)
a = self.type2test([0, 10, 20, 30, 40])
def test_remove(self):
a = self.type2test([0, 0, 1])
a.remove(1)
self.assertEqual(a, [0, 0])
a.remove(0)
self.assertEqual(a, [0])
a.remove(0)
self.assertEqual(a, [])
self.assertRaises(ValueError, a.remove, 0)
self.assertRaises(TypeError, a.remove)
class BadExc(Exception):
pass
class BadCmp:
def __eq__(self, other):
if other == 2:
raise BadExc()
return False
a = self.type2test([0, 1, 2, 3])
self.assertRaises(BadExc, a.remove, BadCmp())
class BadCmp2:
def __eq__(self, other):
raise BadExc()
d = self.type2test('abcdefghcij')
d.remove('c')
self.assertEqual(d, self.type2test('abdefghcij'))
d.remove('c')
self.assertEqual(d, self.type2test('abdefghij'))
self.assertRaises(ValueError, d.remove, 'c')
self.assertEqual(d, self.type2test('abdefghij'))
# Handle comparison errors
d = self.type2test(['a', 'b', BadCmp2(), 'c'])
e = self.type2test(d)
self.assertRaises(BadExc, d.remove, 'c')
for x, y in zip(d, e):
# verify that original order and values are retained.
self.assertIs(x, y)
def test_count(self):
a = self.type2test([0, 1, 2])*3
self.assertEqual(a.count(0), 3)
self.assertEqual(a.count(1), 3)
self.assertEqual(a.count(3), 0)
self.assertRaises(TypeError, a.count)
class BadExc(Exception):
pass
class BadCmp:
def __eq__(self, other):
if other == 2:
raise BadExc()
return False
self.assertRaises(BadExc, a.count, BadCmp())
def test_index(self):
u = self.type2test([0, 1])
self.assertEqual(u.index(0), 0)
self.assertEqual(u.index(1), 1)
self.assertRaises(ValueError, u.index, 2)
u = self.type2test([-2, -1, 0, 0, 1, 2])
self.assertEqual(u.count(0), 2)
self.assertEqual(u.index(0), 2)
self.assertEqual(u.index(0, 2), 2)
self.assertEqual(u.index(-2, -10), 0)
self.assertEqual(u.index(0, 3), 3)
self.assertEqual(u.index(0, 3, 4), 3)
self.assertRaises(ValueError, u.index, 2, 0, -10)
self.assertRaises(TypeError, u.index)
class BadExc(Exception):
pass
class BadCmp:
def __eq__(self, other):
if other == 2:
raise BadExc()
return False
a = self.type2test([0, 1, 2, 3])
self.assertRaises(BadExc, a.index, BadCmp())
a = self.type2test([-2, -1, 0, 0, 1, 2])
self.assertEqual(a.index(0), 2)
self.assertEqual(a.index(0, 2), 2)
self.assertEqual(a.index(0, -4), 2)
self.assertEqual(a.index(-2, -10), 0)
self.assertEqual(a.index(0, 3), 3)
self.assertEqual(a.index(0, -3), 3)
self.assertEqual(a.index(0, 3, 4), 3)
self.assertEqual(a.index(0, -3, -2), 3)
self.assertEqual(a.index(0, -4*sys.maxsize, 4*sys.maxsize), 2)
self.assertRaises(ValueError, a.index, 0, 4*sys.maxsize,-4*sys.maxsize)
self.assertRaises(ValueError, a.index, 2, 0, -10)
a.remove(0)
self.assertRaises(ValueError, a.index, 2, 0, 4)
self.assertEqual(a, self.type2test([-2, -1, 0, 1, 2]))
# Test modifying the list during index's iteration
class EvilCmp:
def __init__(self, victim):
self.victim = victim
def __eq__(self, other):
del self.victim[:]
return False
a = self.type2test()
a[:] = [EvilCmp(a) for _ in range(100)]
# This used to seg fault before patch #1005778
self.assertRaises(ValueError, a.index, None)
def test_reverse(self):
u = self.type2test([-2, -1, 0, 1, 2])
u2 = u[:]
u.reverse()
self.assertEqual(u, [2, 1, 0, -1, -2])
u.reverse()
self.assertEqual(u, u2)
self.assertRaises(TypeError, u.reverse, 42)
def test_clear(self):
u = self.type2test([2, 3, 4])
u.clear()
self.assertEqual(u, [])
u = self.type2test([])
u.clear()
self.assertEqual(u, [])
u = self.type2test([])
u.append(1)
u.clear()
u.append(2)
self.assertEqual(u, [2])
self.assertRaises(TypeError, u.clear, None)
def test_copy(self):
u = self.type2test([1, 2, 3])
v = u.copy()
self.assertEqual(v, [1, 2, 3])
u = self.type2test([])
v = u.copy()
self.assertEqual(v, [])
# test that it's indeed a copy and not a reference
u = self.type2test(['a', 'b'])
v = u.copy()
v.append('i')
self.assertEqual(u, ['a', 'b'])
self.assertEqual(v, u + ['i'])
# test that it's a shallow, not a deep copy
u = self.type2test([1, 2, [3, 4], 5])
v = u.copy()
self.assertEqual(u, v)
self.assertIs(v[3], u[3])
self.assertRaises(TypeError, u.copy, None)
def test_sort(self):
u = self.type2test([1, 0])
u.sort()
self.assertEqual(u, [0, 1])
u = self.type2test([2,1,0,-1,-2])
u.sort()
self.assertEqual(u, self.type2test([-2,-1,0,1,2]))
self.assertRaises(TypeError, u.sort, 42, 42)
def revcmp(a, b):
if a == b:
return 0
elif a < b:
return 1
else: # a > b
return -1
u.sort(key=cmp_to_key(revcmp))
self.assertEqual(u, self.type2test([2,1,0,-1,-2]))
# The following dumps core in unpatched Python 1.5:
def myComparison(x,y):
xmod, ymod = x%3, y%7
if xmod == ymod:
return 0
elif xmod < ymod:
return -1
else: # xmod > ymod
return 1
z = self.type2test(range(12))
z.sort(key=cmp_to_key(myComparison))
self.assertRaises(TypeError, z.sort, 2)
def selfmodifyingComparison(x,y):
z.append(1)
if x == y:
return 0
elif x < y:
return -1
else: # x > y
return 1
self.assertRaises(ValueError, z.sort,
key=cmp_to_key(selfmodifyingComparison))
self.assertRaises(TypeError, z.sort, 42, 42, 42, 42)
def test_slice(self):
u = self.type2test("spam")
u[:2] = "h"
self.assertEqual(u, list("ham"))
def test_iadd(self):
super().test_iadd()
u = self.type2test([0, 1])
u2 = u
u += [2, 3]
self.assertIs(u, u2)
u = self.type2test("spam")
u += "eggs"
self.assertEqual(u, self.type2test("spameggs"))
self.assertRaises(TypeError, u.__iadd__, None)
def test_imul(self):
u = self.type2test([0, 1])
u *= 3
self.assertEqual(u, self.type2test([0, 1, 0, 1, 0, 1]))
u *= 0
self.assertEqual(u, self.type2test([]))
s = self.type2test([])
oldid = id(s)
s *= 10
self.assertEqual(id(s), oldid)
def test_extendedslicing(self):
# subscript
a = self.type2test([0,1,2,3,4])
# deletion
del a[::2]
self.assertEqual(a, self.type2test([1,3]))
a = self.type2test(range(5))
del a[1::2]
self.assertEqual(a, self.type2test([0,2,4]))
a = self.type2test(range(5))
del a[1::-2]
self.assertEqual(a, self.type2test([0,2,3,4]))
a = self.type2test(range(10))
del a[::1000]
self.assertEqual(a, self.type2test([1, 2, 3, 4, 5, 6, 7, 8, 9]))
# assignment
a = self.type2test(range(10))
a[::2] = [-1]*5
self.assertEqual(a, self.type2test([-1, 1, -1, 3, -1, 5, -1, 7, -1, 9]))
a = self.type2test(range(10))
a[::-4] = [10]*3
self.assertEqual(a, self.type2test([0, 10, 2, 3, 4, 10, 6, 7, 8 ,10]))
a = self.type2test(range(4))
a[::-1] = a
self.assertEqual(a, self.type2test([3, 2, 1, 0]))
a = self.type2test(range(10))
b = a[:]
c = a[:]
a[2:3] = self.type2test(["two", "elements"])
b[slice(2,3)] = self.type2test(["two", "elements"])
c[2:3:] = self.type2test(["two", "elements"])
self.assertEqual(a, b)
self.assertEqual(a, c)
a = self.type2test(range(10))
a[::2] = tuple(range(5))
self.assertEqual(a, self.type2test([0, 1, 1, 3, 2, 5, 3, 7, 4, 9]))
# test issue7788
a = self.type2test(range(10))
del a[9::1<<333]
def test_constructor_exception_handling(self):
# Bug #1242657
class F(object):
def __iter__(self):
raise KeyboardInterrupt
self.assertRaises(KeyboardInterrupt, list, F())
def test_exhausted_iterator(self):
a = self.type2test([1, 2, 3])
exhit = iter(a)
empit = iter(a)
for x in exhit: # exhaust the iterator
next(empit) # not exhausted
a.append(9)
self.assertEqual(list(exhit), [])
self.assertEqual(list(empit), [9])
self.assertEqual(a, self.type2test([1, 2, 3, 9]))
| 18,925 | 623 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_file_eintr.py | # Written to test interrupted system calls interfering with our many buffered
# IO implementations. http://bugs.python.org/issue12268
#
# It was suggested that this code could be merged into test_io and the tests
# made to work using the same method as the existing signal tests in test_io.
# I was unable to get single process tests using alarm or setitimer that way
# to reproduce the EINTR problems. This process based test suite reproduces
# the problems prior to the issue12268 patch reliably on Linux and OSX.
# - gregory.p.smith
import os
import select
import signal
import subprocess
import sys
import time
import unittest
# Test import all of the things we're about to try testing up front.
import _io
import _pyio
@unittest.skipUnless(os.name == 'posix', 'tests requires a posix system.')
class TestFileIOSignalInterrupt:
def setUp(self):
self._process = None
def tearDown(self):
if self._process and self._process.poll() is None:
try:
self._process.kill()
except OSError:
pass
def _generate_infile_setup_code(self):
"""Returns the infile = ... line of code for the reader process.
subclasseses should override this to test different IO objects.
"""
return ('import %s as io ;'
'infile = io.FileIO(sys.stdin.fileno(), "rb")' %
self.modname)
def fail_with_process_info(self, why, stdout=b'', stderr=b'',
communicate=True):
"""A common way to cleanup and fail with useful debug output.
Kills the process if it is still running, collects remaining output
and fails the test with an error message including the output.
Args:
why: Text to go after "Error from IO process" in the message.
stdout, stderr: standard output and error from the process so
far to include in the error message.
communicate: bool, when True we call communicate() on the process
after killing it to gather additional output.
"""
if self._process.poll() is None:
time.sleep(0.1) # give it time to finish printing the error.
try:
self._process.terminate() # Ensure it dies.
except OSError:
pass
if communicate:
stdout_end, stderr_end = self._process.communicate()
stdout += stdout_end
stderr += stderr_end
self.fail('Error from IO process %s:\nSTDOUT:\n%sSTDERR:\n%s\n' %
(why, stdout.decode(), stderr.decode()))
def _test_reading(self, data_to_write, read_and_verify_code):
"""Generic buffered read method test harness to validate EINTR behavior.
Also validates that Python signal handlers are run during the read.
Args:
data_to_write: String to write to the child process for reading
before sending it a signal, confirming the signal was handled,
writing a final newline and closing the infile pipe.
read_and_verify_code: Single "line" of code to read from a file
object named 'infile' and validate the result. This will be
executed as part of a python subprocess fed data_to_write.
"""
infile_setup_code = self._generate_infile_setup_code()
# Total pipe IO in this function is smaller than the minimum posix OS
# pipe buffer size of 512 bytes. No writer should block.
assert len(data_to_write) < 512, 'data_to_write must fit in pipe buf.'
# Start a subprocess to call our read method while handling a signal.
self._process = subprocess.Popen(
[sys.executable, '-u', '-c',
'import signal, sys ;'
'signal.signal(signal.SIGINT, '
'lambda s, f: sys.stderr.write("$\\n")) ;'
+ infile_setup_code + ' ;' +
'sys.stderr.write("Worm Sign!\\n") ;'
+ read_and_verify_code + ' ;' +
'infile.close()'
],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# Wait for the signal handler to be installed.
worm_sign = self._process.stderr.read(len(b'Worm Sign!\n'))
if worm_sign != b'Worm Sign!\n': # See also, Dune by Frank Herbert.
self.fail_with_process_info('while awaiting a sign',
stderr=worm_sign)
self._process.stdin.write(data_to_write)
signals_sent = 0
rlist = []
# We don't know when the read_and_verify_code in our child is actually
# executing within the read system call we want to interrupt. This
# loop waits for a bit before sending the first signal to increase
# the likelihood of that. Implementations without correct EINTR
# and signal handling usually fail this test.
while not rlist:
rlist, _, _ = select.select([self._process.stderr], (), (), 0.05)
self._process.send_signal(signal.SIGINT)
signals_sent += 1
if signals_sent > 200:
self._process.kill()
self.fail('reader process failed to handle our signals.')
# This assumes anything unexpected that writes to stderr will also
# write a newline. That is true of the traceback printing code.
signal_line = self._process.stderr.readline()
if signal_line != b'$\n':
self.fail_with_process_info('while awaiting signal',
stderr=signal_line)
# We append a newline to our input so that a readline call can
# end on its own before the EOF is seen and so that we're testing
# the read call that was interrupted by a signal before the end of
# the data stream has been reached.
stdout, stderr = self._process.communicate(input=b'\n')
if self._process.returncode:
self.fail_with_process_info(
'exited rc=%d' % self._process.returncode,
stdout, stderr, communicate=False)
# PASS!
# String format for the read_and_verify_code used by read methods.
_READING_CODE_TEMPLATE = (
'got = infile.{read_method_name}() ;'
'expected = {expected!r} ;'
'assert got == expected, ('
'"{read_method_name} returned wrong data.\\n"'
'"got data %r\\nexpected %r" % (got, expected))'
)
def test_readline(self):
"""readline() must handle signals and not lose data."""
self._test_reading(
data_to_write=b'hello, world!',
read_and_verify_code=self._READING_CODE_TEMPLATE.format(
read_method_name='readline',
expected=b'hello, world!\n'))
def test_readlines(self):
"""readlines() must handle signals and not lose data."""
self._test_reading(
data_to_write=b'hello\nworld!',
read_and_verify_code=self._READING_CODE_TEMPLATE.format(
read_method_name='readlines',
expected=[b'hello\n', b'world!\n']))
def test_readall(self):
"""readall() must handle signals and not lose data."""
self._test_reading(
data_to_write=b'hello\nworld!',
read_and_verify_code=self._READING_CODE_TEMPLATE.format(
read_method_name='readall',
expected=b'hello\nworld!\n'))
# read() is the same thing as readall().
self._test_reading(
data_to_write=b'hello\nworld!',
read_and_verify_code=self._READING_CODE_TEMPLATE.format(
read_method_name='read',
expected=b'hello\nworld!\n'))
class CTestFileIOSignalInterrupt(TestFileIOSignalInterrupt, unittest.TestCase):
modname = '_io'
class PyTestFileIOSignalInterrupt(TestFileIOSignalInterrupt, unittest.TestCase):
modname = '_pyio'
class TestBufferedIOSignalInterrupt(TestFileIOSignalInterrupt):
def _generate_infile_setup_code(self):
"""Returns the infile = ... line of code to make a BufferedReader."""
return ('import %s as io ;infile = io.open(sys.stdin.fileno(), "rb") ;'
'assert isinstance(infile, io.BufferedReader)' %
self.modname)
def test_readall(self):
"""BufferedReader.read() must handle signals and not lose data."""
self._test_reading(
data_to_write=b'hello\nworld!',
read_and_verify_code=self._READING_CODE_TEMPLATE.format(
read_method_name='read',
expected=b'hello\nworld!\n'))
class CTestBufferedIOSignalInterrupt(TestBufferedIOSignalInterrupt, unittest.TestCase):
modname = '_io'
class PyTestBufferedIOSignalInterrupt(TestBufferedIOSignalInterrupt, unittest.TestCase):
modname = '_pyio'
class TestTextIOSignalInterrupt(TestFileIOSignalInterrupt):
def _generate_infile_setup_code(self):
"""Returns the infile = ... line of code to make a TextIOWrapper."""
return ('import %s as io ;'
'infile = io.open(sys.stdin.fileno(), "rt", newline=None) ;'
'assert isinstance(infile, io.TextIOWrapper)' %
self.modname)
def test_readline(self):
"""readline() must handle signals and not lose data."""
self._test_reading(
data_to_write=b'hello, world!',
read_and_verify_code=self._READING_CODE_TEMPLATE.format(
read_method_name='readline',
expected='hello, world!\n'))
def test_readlines(self):
"""readlines() must handle signals and not lose data."""
self._test_reading(
data_to_write=b'hello\r\nworld!',
read_and_verify_code=self._READING_CODE_TEMPLATE.format(
read_method_name='readlines',
expected=['hello\n', 'world!\n']))
def test_readall(self):
"""read() must handle signals and not lose data."""
self._test_reading(
data_to_write=b'hello\nworld!',
read_and_verify_code=self._READING_CODE_TEMPLATE.format(
read_method_name='read',
expected="hello\nworld!\n"))
class CTestTextIOSignalInterrupt(TestTextIOSignalInterrupt, unittest.TestCase):
modname = '_io'
class PyTestTextIOSignalInterrupt(TestTextIOSignalInterrupt, unittest.TestCase):
modname = '_pyio'
if __name__ == '__main__':
unittest.main()
| 10,854 | 253 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_readline.py | """
Very minimal unittests for parts of the readline module.
"""
from contextlib import ExitStack
from errno import EIO
import locale
import os
import selectors
import subprocess
import sys
import tempfile
import unittest
from test.support import import_module, unlink, temp_dir, TESTFN
from test.support.script_helper import assert_python_ok
# Skip tests if there is no readline module
readline = import_module('readline')
is_editline = readline.__doc__ and "libedit" in readline.__doc__
@unittest.skipUnless(hasattr(readline, "clear_history"),
"The history update test cannot be run because the "
"clear_history method is not available.")
class TestHistoryManipulation (unittest.TestCase):
"""
These tests were added to check that the libedit emulation on OSX and the
"real" readline have the same interface for history manipulation. That's
why the tests cover only a small subset of the interface.
"""
def testHistoryUpdates(self):
readline.clear_history()
readline.add_history("first line")
readline.add_history("second line")
self.assertEqual(readline.get_history_item(0), None)
self.assertEqual(readline.get_history_item(1), "first line")
self.assertEqual(readline.get_history_item(2), "second line")
readline.replace_history_item(0, "replaced line")
self.assertEqual(readline.get_history_item(0), None)
self.assertEqual(readline.get_history_item(1), "replaced line")
self.assertEqual(readline.get_history_item(2), "second line")
self.assertEqual(readline.get_current_history_length(), 2)
readline.remove_history_item(0)
self.assertEqual(readline.get_history_item(0), None)
self.assertEqual(readline.get_history_item(1), "second line")
self.assertEqual(readline.get_current_history_length(), 1)
@unittest.skipUnless(hasattr(readline, "append_history_file"),
"append_history not available")
def test_write_read_append(self):
hfile = tempfile.NamedTemporaryFile(delete=False)
hfile.close()
hfilename = hfile.name
self.addCleanup(unlink, hfilename)
# test write-clear-read == nop
readline.clear_history()
readline.add_history("first line")
readline.add_history("second line")
readline.write_history_file(hfilename)
readline.clear_history()
self.assertEqual(readline.get_current_history_length(), 0)
readline.read_history_file(hfilename)
self.assertEqual(readline.get_current_history_length(), 2)
self.assertEqual(readline.get_history_item(1), "first line")
self.assertEqual(readline.get_history_item(2), "second line")
# test append
readline.append_history_file(1, hfilename)
readline.clear_history()
readline.read_history_file(hfilename)
self.assertEqual(readline.get_current_history_length(), 3)
self.assertEqual(readline.get_history_item(1), "first line")
self.assertEqual(readline.get_history_item(2), "second line")
self.assertEqual(readline.get_history_item(3), "second line")
# test 'no such file' behaviour
os.unlink(hfilename)
with self.assertRaises(FileNotFoundError):
readline.append_history_file(1, hfilename)
# write_history_file can create the target
readline.write_history_file(hfilename)
def test_nonascii_history(self):
readline.clear_history()
try:
readline.add_history("entrée 1")
except UnicodeEncodeError as err:
self.skipTest("Locale cannot encode test data: " + format(err))
readline.add_history("entrée 2")
readline.replace_history_item(1, "entrée 22")
readline.write_history_file(TESTFN)
self.addCleanup(os.remove, TESTFN)
readline.clear_history()
readline.read_history_file(TESTFN)
if is_editline:
# An add_history() call seems to be required for get_history_
# item() to register items from the file
readline.add_history("dummy")
self.assertEqual(readline.get_history_item(1), "entrée 1")
self.assertEqual(readline.get_history_item(2), "entrée 22")
class TestReadline(unittest.TestCase):
@unittest.skipIf(readline._READLINE_VERSION < 0x0601 and not is_editline,
"not supported in this library version")
def test_init(self):
# Issue #19884: Ensure that the ANSI sequence "\033[1034h" is not
# written into stdout when the readline module is imported and stdout
# is redirected to a pipe.
rc, stdout, stderr = assert_python_ok('-c', 'import readline',
TERM='xterm-256color')
self.assertEqual(stdout, b'')
auto_history_script = """\
import readline
readline.set_auto_history({})
input()
print("History length:", readline.get_current_history_length())
"""
def test_auto_history_enabled(self):
output = run_pty(self.auto_history_script.format(True))
self.assertIn(b"History length: 1\r\n", output)
def test_auto_history_disabled(self):
output = run_pty(self.auto_history_script.format(False))
self.assertIn(b"History length: 0\r\n", output)
def test_nonascii(self):
loc = locale.setlocale(locale.LC_CTYPE, None)
if loc in ('C', 'POSIX'):
# bpo-29240: On FreeBSD, if the LC_CTYPE locale is C or POSIX,
# writing and reading non-ASCII bytes into/from a TTY works, but
# readline or ncurses ignores non-ASCII bytes on read.
self.skipTest(f"the LC_CTYPE locale is {loc!r}")
try:
readline.add_history("\xEB\xEF")
except UnicodeEncodeError as err:
self.skipTest("Locale cannot encode test data: " + format(err))
script = r"""import readline
is_editline = readline.__doc__ and "libedit" in readline.__doc__
inserted = "[\xEFnserted]"
macro = "|t\xEB[after]"
set_pre_input_hook = getattr(readline, "set_pre_input_hook", None)
if is_editline or not set_pre_input_hook:
# The insert_line() call via pre_input_hook() does nothing with Editline,
# so include the extra text that would have been inserted here
macro = inserted + macro
if is_editline:
readline.parse_and_bind(r'bind ^B ed-prev-char')
readline.parse_and_bind(r'bind "\t" rl_complete')
readline.parse_and_bind(r'bind -s ^A "{}"'.format(macro))
else:
readline.parse_and_bind(r'Control-b: backward-char')
readline.parse_and_bind(r'"\t": complete')
readline.parse_and_bind(r'set disable-completion off')
readline.parse_and_bind(r'set show-all-if-ambiguous off')
readline.parse_and_bind(r'set show-all-if-unmodified off')
readline.parse_and_bind(r'Control-a: "{}"'.format(macro))
def pre_input_hook():
readline.insert_text(inserted)
readline.redisplay()
if set_pre_input_hook:
set_pre_input_hook(pre_input_hook)
def completer(text, state):
if text == "t\xEB":
if state == 0:
print("text", ascii(text))
print("line", ascii(readline.get_line_buffer()))
print("indexes", readline.get_begidx(), readline.get_endidx())
return "t\xEBnt"
if state == 1:
return "t\xEBxt"
if text == "t\xEBx" and state == 0:
return "t\xEBxt"
return None
readline.set_completer(completer)
def display(substitution, matches, longest_match_length):
print("substitution", ascii(substitution))
print("matches", ascii(matches))
readline.set_completion_display_matches_hook(display)
print("result", ascii(input()))
print("history", ascii(readline.get_history_item(1)))
"""
input = b"\x01" # Ctrl-A, expands to "|t\xEB[after]"
input += b"\x02" * len("[after]") # Move cursor back
input += b"\t\t" # Display possible completions
input += b"x\t" # Complete "t\xEBx" -> "t\xEBxt"
input += b"\r"
output = run_pty(script, input)
self.assertIn(b"text 't\\xeb'\r\n", output)
self.assertIn(b"line '[\\xefnserted]|t\\xeb[after]'\r\n", output)
self.assertIn(b"indexes 11 13\r\n", output)
if not is_editline and hasattr(readline, "set_pre_input_hook"):
self.assertIn(b"substitution 't\\xeb'\r\n", output)
self.assertIn(b"matches ['t\\xebnt', 't\\xebxt']\r\n", output)
expected = br"'[\xefnserted]|t\xebxt[after]'"
self.assertIn(b"result " + expected + b"\r\n", output)
self.assertIn(b"history " + expected + b"\r\n", output)
# We have 2 reasons to skip this test:
# - readline: history size was added in 6.0
# See https://cnswww.cns.cwru.edu/php/chet/readline/CHANGES
# - editline: history size is broken on OS X 10.11.6.
# Newer versions were not tested yet.
@unittest.skipIf(readline._READLINE_VERSION < 0x600,
"this readline version does not support history-size")
@unittest.skipIf(is_editline,
"editline history size configuration is broken")
def test_history_size(self):
history_size = 10
with temp_dir() as test_dir:
inputrc = os.path.join(test_dir, "inputrc")
with open(inputrc, "wb") as f:
f.write(b"set history-size %d\n" % history_size)
history_file = os.path.join(test_dir, "history")
with open(history_file, "wb") as f:
# history_size * 2 items crashes readline
data = b"".join(b"item %d\n" % i
for i in range(history_size * 2))
f.write(data)
script = """
import os
import readline
history_file = os.environ["HISTORY_FILE"]
readline.read_history_file(history_file)
input()
readline.write_history_file(history_file)
"""
env = dict(os.environ)
env["INPUTRC"] = inputrc
env["HISTORY_FILE"] = history_file
run_pty(script, input=b"last input\r", env=env)
with open(history_file, "rb") as f:
lines = f.readlines()
self.assertEqual(len(lines), history_size)
self.assertEqual(lines[-1].strip(), b"last input")
def run_pty(script, input=b"dummy input\r", env=None):
pty = import_module('pty')
output = bytearray()
[master, slave] = pty.openpty()
args = (sys.executable, '-c', script)
proc = subprocess.Popen(args, stdin=slave, stdout=slave, stderr=slave, env=env)
os.close(slave)
with ExitStack() as cleanup:
cleanup.enter_context(proc)
def terminate(proc):
try:
proc.terminate()
except ProcessLookupError:
# Workaround for Open/Net BSD bug (Issue 16762)
pass
cleanup.callback(terminate, proc)
cleanup.callback(os.close, master)
# Avoid using DefaultSelector and PollSelector. Kqueue() does not
# work with pseudo-terminals on OS X < 10.9 (Issue 20365) and Open
# BSD (Issue 20667). Poll() does not work with OS X 10.6 or 10.4
# either (Issue 20472). Hopefully the file descriptor is low enough
# to use with select().
sel = cleanup.enter_context(selectors.SelectSelector())
sel.register(master, selectors.EVENT_READ | selectors.EVENT_WRITE)
os.set_blocking(master, False)
while True:
for [_, events] in sel.select():
if events & selectors.EVENT_READ:
try:
chunk = os.read(master, 0x10000)
except OSError as err:
# Linux raises EIO when slave is closed (Issue 5380)
if err.errno != EIO:
raise
chunk = b""
if not chunk:
return output
output.extend(chunk)
if events & selectors.EVENT_WRITE:
try:
input = input[os.write(master, input):]
except OSError as err:
# Apparently EIO means the slave was closed
if err.errno != EIO:
raise
input = b"" # Stop writing
if not input:
sel.modify(master, selectors.EVENT_READ)
if __name__ == "__main__":
unittest.main()
| 12,558 | 318 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_deque.py | from collections import deque
import unittest
from test import support, seq_tests
import gc
import weakref
import copy
import pickle
from io import StringIO
import random
import struct
BIG = 100000
def fail():
raise SyntaxError
yield 1
class BadCmp:
def __eq__(self, other):
raise RuntimeError
class MutateCmp:
def __init__(self, deque, result):
self.deque = deque
self.result = result
def __eq__(self, other):
self.deque.clear()
return self.result
class TestBasic(unittest.TestCase):
def test_basics(self):
d = deque(range(-5125, -5000))
d.__init__(range(200))
for i in range(200, 400):
d.append(i)
for i in reversed(range(-200, 0)):
d.appendleft(i)
self.assertEqual(list(d), list(range(-200, 400)))
self.assertEqual(len(d), 600)
left = [d.popleft() for i in range(250)]
self.assertEqual(left, list(range(-200, 50)))
self.assertEqual(list(d), list(range(50, 400)))
right = [d.pop() for i in range(250)]
right.reverse()
self.assertEqual(right, list(range(150, 400)))
self.assertEqual(list(d), list(range(50, 150)))
def test_maxlen(self):
self.assertRaises(ValueError, deque, 'abc', -1)
self.assertRaises(ValueError, deque, 'abc', -2)
it = iter(range(10))
d = deque(it, maxlen=3)
self.assertEqual(list(it), [])
self.assertEqual(repr(d), 'deque([7, 8, 9], maxlen=3)')
self.assertEqual(list(d), [7, 8, 9])
self.assertEqual(d, deque(range(10), 3))
d.append(10)
self.assertEqual(list(d), [8, 9, 10])
d.appendleft(7)
self.assertEqual(list(d), [7, 8, 9])
d.extend([10, 11])
self.assertEqual(list(d), [9, 10, 11])
d.extendleft([8, 7])
self.assertEqual(list(d), [7, 8, 9])
d = deque(range(200), maxlen=10)
d.append(d)
support.unlink(support.TESTFN)
fo = open(support.TESTFN, "w")
try:
fo.write(str(d))
fo.close()
fo = open(support.TESTFN, "r")
self.assertEqual(fo.read(), repr(d))
finally:
fo.close()
support.unlink(support.TESTFN)
d = deque(range(10), maxlen=None)
self.assertEqual(repr(d), 'deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])')
fo = open(support.TESTFN, "w")
try:
fo.write(str(d))
fo.close()
fo = open(support.TESTFN, "r")
self.assertEqual(fo.read(), repr(d))
finally:
fo.close()
support.unlink(support.TESTFN)
def test_maxlen_zero(self):
it = iter(range(100))
deque(it, maxlen=0)
self.assertEqual(list(it), [])
it = iter(range(100))
d = deque(maxlen=0)
d.extend(it)
self.assertEqual(list(it), [])
it = iter(range(100))
d = deque(maxlen=0)
d.extendleft(it)
self.assertEqual(list(it), [])
def test_maxlen_attribute(self):
self.assertEqual(deque().maxlen, None)
self.assertEqual(deque('abc').maxlen, None)
self.assertEqual(deque('abc', maxlen=4).maxlen, 4)
self.assertEqual(deque('abc', maxlen=2).maxlen, 2)
self.assertEqual(deque('abc', maxlen=0).maxlen, 0)
with self.assertRaises(AttributeError):
d = deque('abc')
d.maxlen = 10
def test_count(self):
for s in ('', 'abracadabra', 'simsalabim'*500+'abc'):
s = list(s)
d = deque(s)
for letter in 'abcdefghijklmnopqrstuvwxyz':
self.assertEqual(s.count(letter), d.count(letter), (s, d, letter))
self.assertRaises(TypeError, d.count) # too few args
self.assertRaises(TypeError, d.count, 1, 2) # too many args
class BadCompare:
def __eq__(self, other):
raise ArithmeticError
d = deque([1, 2, BadCompare(), 3])
self.assertRaises(ArithmeticError, d.count, 2)
d = deque([1, 2, 3])
self.assertRaises(ArithmeticError, d.count, BadCompare())
class MutatingCompare:
def __eq__(self, other):
self.d.pop()
return True
m = MutatingCompare()
d = deque([1, 2, 3, m, 4, 5])
m.d = d
self.assertRaises(RuntimeError, d.count, 3)
# test issue11004
# block advance failed after rotation aligned elements on right side of block
d = deque([None]*16)
for i in range(len(d)):
d.rotate(-1)
d.rotate(1)
self.assertEqual(d.count(1), 0)
self.assertEqual(d.count(None), 16)
def test_comparisons(self):
d = deque('xabc'); d.popleft()
for e in [d, deque('abc'), deque('ab'), deque(), list(d)]:
self.assertEqual(d==e, type(d)==type(e) and list(d)==list(e))
self.assertEqual(d!=e, not(type(d)==type(e) and list(d)==list(e)))
args = map(deque, ('', 'a', 'b', 'ab', 'ba', 'abc', 'xba', 'xabc', 'cba'))
for x in args:
for y in args:
self.assertEqual(x == y, list(x) == list(y), (x,y))
self.assertEqual(x != y, list(x) != list(y), (x,y))
self.assertEqual(x < y, list(x) < list(y), (x,y))
self.assertEqual(x <= y, list(x) <= list(y), (x,y))
self.assertEqual(x > y, list(x) > list(y), (x,y))
self.assertEqual(x >= y, list(x) >= list(y), (x,y))
def test_contains(self):
n = 200
d = deque(range(n))
for i in range(n):
self.assertTrue(i in d)
self.assertTrue((n+1) not in d)
# Test detection of mutation during iteration
d = deque(range(n))
d[n//2] = MutateCmp(d, False)
with self.assertRaises(RuntimeError):
n in d
# Test detection of comparison exceptions
d = deque(range(n))
d[n//2] = BadCmp()
with self.assertRaises(RuntimeError):
n in d
def test_extend(self):
d = deque('a')
self.assertRaises(TypeError, d.extend, 1)
d.extend('bcd')
self.assertEqual(list(d), list('abcd'))
d.extend(d)
self.assertEqual(list(d), list('abcdabcd'))
def test_add(self):
d = deque()
e = deque('abc')
f = deque('def')
self.assertEqual(d + d, deque())
self.assertEqual(e + f, deque('abcdef'))
self.assertEqual(e + e, deque('abcabc'))
self.assertEqual(e + d, deque('abc'))
self.assertEqual(d + e, deque('abc'))
self.assertIsNot(d + d, deque())
self.assertIsNot(e + d, deque('abc'))
self.assertIsNot(d + e, deque('abc'))
g = deque('abcdef', maxlen=4)
h = deque('gh')
self.assertEqual(g + h, deque('efgh'))
with self.assertRaises(TypeError):
deque('abc') + 'def'
def test_iadd(self):
d = deque('a')
d += 'bcd'
self.assertEqual(list(d), list('abcd'))
d += d
self.assertEqual(list(d), list('abcdabcd'))
def test_extendleft(self):
d = deque('a')
self.assertRaises(TypeError, d.extendleft, 1)
d.extendleft('bcd')
self.assertEqual(list(d), list(reversed('abcd')))
d.extendleft(d)
self.assertEqual(list(d), list('abcddcba'))
d = deque()
d.extendleft(range(1000))
self.assertEqual(list(d), list(reversed(range(1000))))
self.assertRaises(SyntaxError, d.extendleft, fail())
def test_getitem(self):
n = 200
d = deque(range(n))
l = list(range(n))
for i in range(n):
d.popleft()
l.pop(0)
if random.random() < 0.5:
d.append(i)
l.append(i)
for j in range(1-len(l), len(l)):
assert d[j] == l[j]
d = deque('superman')
self.assertEqual(d[0], 's')
self.assertEqual(d[-1], 'n')
d = deque()
self.assertRaises(IndexError, d.__getitem__, 0)
self.assertRaises(IndexError, d.__getitem__, -1)
def test_index(self):
for n in 1, 2, 30, 40, 200:
d = deque(range(n))
for i in range(n):
self.assertEqual(d.index(i), i)
with self.assertRaises(ValueError):
d.index(n+1)
# Test detection of mutation during iteration
d = deque(range(n))
d[n//2] = MutateCmp(d, False)
with self.assertRaises(RuntimeError):
d.index(n)
# Test detection of comparison exceptions
d = deque(range(n))
d[n//2] = BadCmp()
with self.assertRaises(RuntimeError):
d.index(n)
# Test start and stop arguments behavior matches list.index()
elements = 'ABCDEFGHI'
nonelement = 'Z'
d = deque(elements * 2)
s = list(elements * 2)
for start in range(-5 - len(s)*2, 5 + len(s) * 2):
for stop in range(-5 - len(s)*2, 5 + len(s) * 2):
for element in elements + 'Z':
try:
target = s.index(element, start, stop)
except ValueError:
with self.assertRaises(ValueError):
d.index(element, start, stop)
else:
self.assertEqual(d.index(element, start, stop), target)
def test_index_bug_24913(self):
d = deque('A' * 3)
with self.assertRaises(ValueError):
i = d.index("Hello world", 0, 4)
def test_insert(self):
# Test to make sure insert behaves like lists
elements = 'ABCDEFGHI'
for i in range(-5 - len(elements)*2, 5 + len(elements) * 2):
d = deque('ABCDEFGHI')
s = list('ABCDEFGHI')
d.insert(i, 'Z')
s.insert(i, 'Z')
self.assertEqual(list(d), s)
def test_insert_bug_26194(self):
data = 'ABC'
d = deque(data, maxlen=len(data))
with self.assertRaises(IndexError):
d.insert(2, None)
elements = 'ABCDEFGHI'
for i in range(-len(elements), len(elements)):
d = deque(elements, maxlen=len(elements)+1)
d.insert(i, 'Z')
if i >= 0:
self.assertEqual(d[i], 'Z')
else:
self.assertEqual(d[i-1], 'Z')
def test_imul(self):
for n in (-10, -1, 0, 1, 2, 10, 1000):
d = deque()
d *= n
self.assertEqual(d, deque())
self.assertIsNone(d.maxlen)
for n in (-10, -1, 0, 1, 2, 10, 1000):
d = deque('a')
d *= n
self.assertEqual(d, deque('a' * n))
self.assertIsNone(d.maxlen)
for n in (-10, -1, 0, 1, 2, 10, 499, 500, 501, 1000):
d = deque('a', 500)
d *= n
self.assertEqual(d, deque('a' * min(n, 500)))
self.assertEqual(d.maxlen, 500)
for n in (-10, -1, 0, 1, 2, 10, 1000):
d = deque('abcdef')
d *= n
self.assertEqual(d, deque('abcdef' * n))
self.assertIsNone(d.maxlen)
for n in (-10, -1, 0, 1, 2, 10, 499, 500, 501, 1000):
d = deque('abcdef', 500)
d *= n
self.assertEqual(d, deque(('abcdef' * n)[-500:]))
self.assertEqual(d.maxlen, 500)
def test_mul(self):
d = deque('abc')
self.assertEqual(d * -5, deque())
self.assertEqual(d * 0, deque())
self.assertEqual(d * 1, deque('abc'))
self.assertEqual(d * 2, deque('abcabc'))
self.assertEqual(d * 3, deque('abcabcabc'))
self.assertIsNot(d * 1, d)
self.assertEqual(deque() * 0, deque())
self.assertEqual(deque() * 1, deque())
self.assertEqual(deque() * 5, deque())
self.assertEqual(-5 * d, deque())
self.assertEqual(0 * d, deque())
self.assertEqual(1 * d, deque('abc'))
self.assertEqual(2 * d, deque('abcabc'))
self.assertEqual(3 * d, deque('abcabcabc'))
d = deque('abc', maxlen=5)
self.assertEqual(d * -5, deque())
self.assertEqual(d * 0, deque())
self.assertEqual(d * 1, deque('abc'))
self.assertEqual(d * 2, deque('bcabc'))
self.assertEqual(d * 30, deque('bcabc'))
def test_setitem(self):
n = 200
d = deque(range(n))
for i in range(n):
d[i] = 10 * i
self.assertEqual(list(d), [10*i for i in range(n)])
l = list(d)
for i in range(1-n, 0, -1):
d[i] = 7*i
l[i] = 7*i
self.assertEqual(list(d), l)
def test_delitem(self):
n = 500 # O(n**2) test, don't make this too big
d = deque(range(n))
self.assertRaises(IndexError, d.__delitem__, -n-1)
self.assertRaises(IndexError, d.__delitem__, n)
for i in range(n):
self.assertEqual(len(d), n-i)
j = random.randrange(-len(d), len(d))
val = d[j]
self.assertIn(val, d)
del d[j]
self.assertNotIn(val, d)
self.assertEqual(len(d), 0)
def test_reverse(self):
n = 500 # O(n**2) test, don't make this too big
data = [random.random() for i in range(n)]
for i in range(n):
d = deque(data[:i])
r = d.reverse()
self.assertEqual(list(d), list(reversed(data[:i])))
self.assertIs(r, None)
d.reverse()
self.assertEqual(list(d), data[:i])
self.assertRaises(TypeError, d.reverse, 1) # Arity is zero
def test_rotate(self):
s = tuple('abcde')
n = len(s)
d = deque(s)
d.rotate(1) # verify rot(1)
self.assertEqual(''.join(d), 'eabcd')
d = deque(s)
d.rotate(-1) # verify rot(-1)
self.assertEqual(''.join(d), 'bcdea')
d.rotate() # check default to 1
self.assertEqual(tuple(d), s)
for i in range(n*3):
d = deque(s)
e = deque(d)
d.rotate(i) # check vs. rot(1) n times
for j in range(i):
e.rotate(1)
self.assertEqual(tuple(d), tuple(e))
d.rotate(-i) # check that it works in reverse
self.assertEqual(tuple(d), s)
e.rotate(n-i) # check that it wraps forward
self.assertEqual(tuple(e), s)
for i in range(n*3):
d = deque(s)
e = deque(d)
d.rotate(-i)
for j in range(i):
e.rotate(-1) # check vs. rot(-1) n times
self.assertEqual(tuple(d), tuple(e))
d.rotate(i) # check that it works in reverse
self.assertEqual(tuple(d), s)
e.rotate(i-n) # check that it wraps backaround
self.assertEqual(tuple(e), s)
d = deque(s)
e = deque(s)
e.rotate(BIG+17) # verify on long series of rotates
dr = d.rotate
for i in range(BIG+17):
dr()
self.assertEqual(tuple(d), tuple(e))
self.assertRaises(TypeError, d.rotate, 'x') # Wrong arg type
self.assertRaises(TypeError, d.rotate, 1, 10) # Too many args
d = deque()
d.rotate() # rotate an empty deque
self.assertEqual(d, deque())
def test_len(self):
d = deque('ab')
self.assertEqual(len(d), 2)
d.popleft()
self.assertEqual(len(d), 1)
d.pop()
self.assertEqual(len(d), 0)
self.assertRaises(IndexError, d.pop)
self.assertEqual(len(d), 0)
d.append('c')
self.assertEqual(len(d), 1)
d.appendleft('d')
self.assertEqual(len(d), 2)
d.clear()
self.assertEqual(len(d), 0)
def test_underflow(self):
d = deque()
self.assertRaises(IndexError, d.pop)
self.assertRaises(IndexError, d.popleft)
def test_clear(self):
d = deque(range(100))
self.assertEqual(len(d), 100)
d.clear()
self.assertEqual(len(d), 0)
self.assertEqual(list(d), [])
d.clear() # clear an empty deque
self.assertEqual(list(d), [])
def test_remove(self):
d = deque('abcdefghcij')
d.remove('c')
self.assertEqual(d, deque('abdefghcij'))
d.remove('c')
self.assertEqual(d, deque('abdefghij'))
self.assertRaises(ValueError, d.remove, 'c')
self.assertEqual(d, deque('abdefghij'))
# Handle comparison errors
d = deque(['a', 'b', BadCmp(), 'c'])
e = deque(d)
self.assertRaises(RuntimeError, d.remove, 'c')
for x, y in zip(d, e):
# verify that original order and values are retained.
self.assertTrue(x is y)
# Handle evil mutator
for match in (True, False):
d = deque(['ab'])
d.extend([MutateCmp(d, match), 'c'])
self.assertRaises(IndexError, d.remove, 'c')
self.assertEqual(d, deque())
def test_repr(self):
d = deque(range(200))
e = eval(repr(d))
self.assertEqual(list(d), list(e))
d.append(d)
self.assertIn('...', repr(d))
def test_print(self):
d = deque(range(200))
d.append(d)
try:
support.unlink(support.TESTFN)
fo = open(support.TESTFN, "w")
print(d, file=fo, end='')
fo.close()
fo = open(support.TESTFN, "r")
self.assertEqual(fo.read(), repr(d))
finally:
fo.close()
support.unlink(support.TESTFN)
def test_init(self):
self.assertRaises(TypeError, deque, 'abc', 2, 3);
self.assertRaises(TypeError, deque, 1);
def test_hash(self):
self.assertRaises(TypeError, hash, deque('abc'))
def test_long_steadystate_queue_popleft(self):
for size in (0, 1, 2, 100, 1000):
d = deque(range(size))
append, pop = d.append, d.popleft
for i in range(size, BIG):
append(i)
x = pop()
if x != i - size:
self.assertEqual(x, i-size)
self.assertEqual(list(d), list(range(BIG-size, BIG)))
def test_long_steadystate_queue_popright(self):
for size in (0, 1, 2, 100, 1000):
d = deque(reversed(range(size)))
append, pop = d.appendleft, d.pop
for i in range(size, BIG):
append(i)
x = pop()
if x != i - size:
self.assertEqual(x, i-size)
self.assertEqual(list(reversed(list(d))),
list(range(BIG-size, BIG)))
def test_big_queue_popleft(self):
pass
d = deque()
append, pop = d.append, d.popleft
for i in range(BIG):
append(i)
for i in range(BIG):
x = pop()
if x != i:
self.assertEqual(x, i)
def test_big_queue_popright(self):
d = deque()
append, pop = d.appendleft, d.pop
for i in range(BIG):
append(i)
for i in range(BIG):
x = pop()
if x != i:
self.assertEqual(x, i)
def test_big_stack_right(self):
d = deque()
append, pop = d.append, d.pop
for i in range(BIG):
append(i)
for i in reversed(range(BIG)):
x = pop()
if x != i:
self.assertEqual(x, i)
self.assertEqual(len(d), 0)
def test_big_stack_left(self):
d = deque()
append, pop = d.appendleft, d.popleft
for i in range(BIG):
append(i)
for i in reversed(range(BIG)):
x = pop()
if x != i:
self.assertEqual(x, i)
self.assertEqual(len(d), 0)
def test_roundtrip_iter_init(self):
d = deque(range(200))
e = deque(d)
self.assertNotEqual(id(d), id(e))
self.assertEqual(list(d), list(e))
def test_pickle(self):
for d in deque(range(200)), deque(range(200), 100):
for i in range(pickle.HIGHEST_PROTOCOL + 1):
s = pickle.dumps(d, i)
e = pickle.loads(s)
self.assertNotEqual(id(e), id(d))
self.assertEqual(list(e), list(d))
self.assertEqual(e.maxlen, d.maxlen)
def test_pickle_recursive(self):
for d in deque('abc'), deque('abc', 3):
d.append(d)
for i in range(pickle.HIGHEST_PROTOCOL + 1):
e = pickle.loads(pickle.dumps(d, i))
self.assertNotEqual(id(e), id(d))
self.assertEqual(id(e[-1]), id(e))
self.assertEqual(e.maxlen, d.maxlen)
def test_iterator_pickle(self):
orig = deque(range(200))
data = [i*1.01 for i in orig]
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
# initial iterator
itorg = iter(orig)
dump = pickle.dumps((itorg, orig), proto)
it, d = pickle.loads(dump)
for i, x in enumerate(data):
d[i] = x
self.assertEqual(type(it), type(itorg))
self.assertEqual(list(it), data)
# running iterator
next(itorg)
dump = pickle.dumps((itorg, orig), proto)
it, d = pickle.loads(dump)
for i, x in enumerate(data):
d[i] = x
self.assertEqual(type(it), type(itorg))
self.assertEqual(list(it), data[1:])
# empty iterator
for i in range(1, len(data)):
next(itorg)
dump = pickle.dumps((itorg, orig), proto)
it, d = pickle.loads(dump)
for i, x in enumerate(data):
d[i] = x
self.assertEqual(type(it), type(itorg))
self.assertEqual(list(it), [])
# exhausted iterator
self.assertRaises(StopIteration, next, itorg)
dump = pickle.dumps((itorg, orig), proto)
it, d = pickle.loads(dump)
for i, x in enumerate(data):
d[i] = x
self.assertEqual(type(it), type(itorg))
self.assertEqual(list(it), [])
def test_deepcopy(self):
mut = [10]
d = deque([mut])
e = copy.deepcopy(d)
self.assertEqual(list(d), list(e))
mut[0] = 11
self.assertNotEqual(id(d), id(e))
self.assertNotEqual(list(d), list(e))
def test_copy(self):
mut = [10]
d = deque([mut])
e = copy.copy(d)
self.assertEqual(list(d), list(e))
mut[0] = 11
self.assertNotEqual(id(d), id(e))
self.assertEqual(list(d), list(e))
for i in range(5):
for maxlen in range(-1, 6):
s = [random.random() for j in range(i)]
d = deque(s) if maxlen == -1 else deque(s, maxlen)
e = d.copy()
self.assertEqual(d, e)
self.assertEqual(d.maxlen, e.maxlen)
self.assertTrue(all(x is y for x, y in zip(d, e)))
def test_copy_method(self):
mut = [10]
d = deque([mut])
e = d.copy()
self.assertEqual(list(d), list(e))
mut[0] = 11
self.assertNotEqual(id(d), id(e))
self.assertEqual(list(d), list(e))
def test_reversed(self):
for s in ('abcd', range(2000)):
self.assertEqual(list(reversed(deque(s))), list(reversed(s)))
def test_reversed_new(self):
klass = type(reversed(deque()))
for s in ('abcd', range(2000)):
self.assertEqual(list(klass(deque(s))), list(reversed(s)))
def test_gc_doesnt_blowup(self):
import gc
# This used to assert-fail in deque_traverse() under a debug
# build, or run wild with a NULL pointer in a release build.
d = deque()
for i in range(100):
d.append(1)
gc.collect()
def test_container_iterator(self):
# Bug #3680: tp_traverse was not implemented for deque iterator objects
class C(object):
pass
for i in range(2):
obj = C()
ref = weakref.ref(obj)
if i == 0:
container = deque([obj, 1])
else:
container = reversed(deque([obj, 1]))
obj.x = iter(container)
del obj, container
gc.collect()
self.assertTrue(ref() is None, "Cycle was not collected")
check_sizeof = support.check_sizeof
@support.cpython_only
def test_sizeof(self):
BLOCKLEN = 64
basesize = support.calcvobjsize('2P4nP')
blocksize = struct.calcsize('P%dPP' % BLOCKLEN)
self.assertEqual(object.__sizeof__(deque()), basesize)
check = self.check_sizeof
check(deque(), basesize + blocksize)
check(deque('a'), basesize + blocksize)
check(deque('a' * (BLOCKLEN - 1)), basesize + blocksize)
check(deque('a' * BLOCKLEN), basesize + 2 * blocksize)
check(deque('a' * (42 * BLOCKLEN)), basesize + 43 * blocksize)
class TestVariousIteratorArgs(unittest.TestCase):
def test_constructor(self):
for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (seq_tests.Sequence, seq_tests.IterFunc,
seq_tests.IterGen, seq_tests.IterFuncStop,
seq_tests.itermulti, seq_tests.iterfunc):
self.assertEqual(list(deque(g(s))), list(g(s)))
self.assertRaises(TypeError, deque, seq_tests.IterNextOnly(s))
self.assertRaises(TypeError, deque, seq_tests.IterNoNext(s))
self.assertRaises(ZeroDivisionError, deque, seq_tests.IterGenExc(s))
def test_iter_with_altered_data(self):
d = deque('abcdefg')
it = iter(d)
d.pop()
self.assertRaises(RuntimeError, next, it)
def test_runtime_error_on_empty_deque(self):
d = deque()
it = iter(d)
d.append(10)
self.assertRaises(RuntimeError, next, it)
class Deque(deque):
pass
class DequeWithBadIter(deque):
def __iter__(self):
raise TypeError
class TestSubclass(unittest.TestCase):
def test_basics(self):
d = Deque(range(25))
d.__init__(range(200))
for i in range(200, 400):
d.append(i)
for i in reversed(range(-200, 0)):
d.appendleft(i)
self.assertEqual(list(d), list(range(-200, 400)))
self.assertEqual(len(d), 600)
left = [d.popleft() for i in range(250)]
self.assertEqual(left, list(range(-200, 50)))
self.assertEqual(list(d), list(range(50, 400)))
right = [d.pop() for i in range(250)]
right.reverse()
self.assertEqual(right, list(range(150, 400)))
self.assertEqual(list(d), list(range(50, 150)))
d.clear()
self.assertEqual(len(d), 0)
def test_copy_pickle(self):
d = Deque('abc')
e = d.__copy__()
self.assertEqual(type(d), type(e))
self.assertEqual(list(d), list(e))
e = Deque(d)
self.assertEqual(type(d), type(e))
self.assertEqual(list(d), list(e))
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
s = pickle.dumps(d, proto)
e = pickle.loads(s)
self.assertNotEqual(id(d), id(e))
self.assertEqual(type(d), type(e))
self.assertEqual(list(d), list(e))
d = Deque('abcde', maxlen=4)
e = d.__copy__()
self.assertEqual(type(d), type(e))
self.assertEqual(list(d), list(e))
e = Deque(d)
self.assertEqual(type(d), type(e))
self.assertEqual(list(d), list(e))
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
s = pickle.dumps(d, proto)
e = pickle.loads(s)
self.assertNotEqual(id(d), id(e))
self.assertEqual(type(d), type(e))
self.assertEqual(list(d), list(e))
def test_pickle_recursive(self):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
for d in Deque('abc'), Deque('abc', 3):
d.append(d)
e = pickle.loads(pickle.dumps(d, proto))
self.assertNotEqual(id(e), id(d))
self.assertEqual(type(e), type(d))
self.assertEqual(e.maxlen, d.maxlen)
dd = d.pop()
ee = e.pop()
self.assertEqual(id(ee), id(e))
self.assertEqual(e, d)
d.x = d
e = pickle.loads(pickle.dumps(d, proto))
self.assertEqual(id(e.x), id(e))
for d in DequeWithBadIter('abc'), DequeWithBadIter('abc', 2):
self.assertRaises(TypeError, pickle.dumps, d, proto)
def test_weakref(self):
d = deque('gallahad')
p = weakref.proxy(d)
self.assertEqual(str(p), str(d))
d = None
self.assertRaises(ReferenceError, str, p)
def test_strange_subclass(self):
class X(deque):
def __iter__(self):
return iter([])
d1 = X([1,2,3])
d2 = X([4,5,6])
d1 == d2 # not clear if this is supposed to be True or False,
# but it used to give a SystemError
@support.cpython_only
def test_bug_31608(self):
# The interpreter used to crash in specific cases where a deque
# subclass returned a non-deque.
class X(deque):
pass
d = X()
def bad___new__(cls, *args, **kwargs):
return [42]
X.__new__ = bad___new__
with self.assertRaises(TypeError):
d * 42 # shouldn't crash
with self.assertRaises(TypeError):
d + deque([1, 2, 3]) # shouldn't crash
class SubclassWithKwargs(deque):
def __init__(self, newarg=1):
deque.__init__(self)
class TestSubclassWithKwargs(unittest.TestCase):
def test_subclass_with_kwargs(self):
# SF bug #1486663 -- this used to erroneously raise a TypeError
SubclassWithKwargs(newarg=1)
class TestSequence(seq_tests.CommonTest):
type2test = deque
def test_getitem(self):
# For now, bypass tests that require slicing
pass
def test_getslice(self):
# For now, bypass tests that require slicing
pass
def test_subscript(self):
# For now, bypass tests that require slicing
pass
def test_free_after_iterating(self):
# For now, bypass tests that require slicing
self.skipTest("Exhausted deque iterator doesn't free a deque")
#==============================================================================
libreftest = """
Example from the Library Reference: Doc/lib/libcollections.tex
>>> from collections import deque
>>> d = deque('ghi') # make a new deque with three items
>>> for elem in d: # iterate over the deque's elements
... print(elem.upper())
G
H
I
>>> d.append('j') # add a new entry to the right side
>>> d.appendleft('f') # add a new entry to the left side
>>> d # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])
>>> d.pop() # return and remove the rightmost item
'j'
>>> d.popleft() # return and remove the leftmost item
'f'
>>> list(d) # list the contents of the deque
['g', 'h', 'i']
>>> d[0] # peek at leftmost item
'g'
>>> d[-1] # peek at rightmost item
'i'
>>> list(reversed(d)) # list the contents of a deque in reverse
['i', 'h', 'g']
>>> 'h' in d # search the deque
True
>>> d.extend('jkl') # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1) # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1) # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> deque(reversed(d)) # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear() # empty the deque
>>> d.pop() # cannot pop from an empty deque
Traceback (most recent call last):
File "<pyshell#6>", line 1, in -toplevel-
d.pop()
IndexError: pop from an empty deque
>>> d.extendleft('abc') # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])
>>> def delete_nth(d, n):
... d.rotate(-n)
... d.popleft()
... d.rotate(n)
...
>>> d = deque('abcdef')
>>> delete_nth(d, 2) # remove the entry at d[2]
>>> d
deque(['a', 'b', 'd', 'e', 'f'])
>>> def roundrobin(*iterables):
... pending = deque(iter(i) for i in iterables)
... while pending:
... task = pending.popleft()
... try:
... yield next(task)
... except StopIteration:
... continue
... pending.append(task)
...
>>> for value in roundrobin('abc', 'd', 'efgh'):
... print(value)
...
a
d
e
b
f
c
g
h
>>> def maketree(iterable):
... d = deque(iterable)
... while len(d) > 1:
... pair = [d.popleft(), d.popleft()]
... d.append(pair)
... return list(d)
...
>>> print(maketree('abcdefgh'))
[[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]]
"""
#==============================================================================
__test__ = {'libreftest' : libreftest}
def test_main(verbose=None):
import sys
test_classes = (
TestBasic,
TestVariousIteratorArgs,
TestSubclass,
TestSubclassWithKwargs,
TestSequence,
)
support.run_unittest(*test_classes)
# verify reference counting
if verbose and hasattr(sys, "gettotalrefcount"):
import gc
import os
# [jart] it's sooo slow and isn't actually a test
if os.isatty(2):
counts = [None] * 5
for i in range(len(counts)):
support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
print(counts)
# doctests
from test import test_deque
support.run_doctest(test_deque, verbose)
if __name__ == "__main__":
test_main(verbose=True)
| 34,800 | 1,078 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_sched.py | import queue
import sched
import time
import unittest
try:
import _thread
import threading
except ImportError:
threading = None
TIMEOUT = 10
class Timer:
def __init__(self):
self._cond = threading.Condition()
self._time = 0
self._stop = 0
def time(self):
with self._cond:
return self._time
# increase the time but not beyond the established limit
def sleep(self, t):
assert t >= 0
with self._cond:
t += self._time
while self._stop < t:
self._time = self._stop
self._cond.wait()
self._time = t
# advance time limit for user code
def advance(self, t):
assert t >= 0
with self._cond:
self._stop += t
self._cond.notify_all()
class TestCase(unittest.TestCase):
def test_enter(self):
l = []
fun = lambda x: l.append(x)
scheduler = sched.scheduler(time.time, time.sleep)
for x in [0.5, 0.4, 0.3, 0.2, 0.1]:
z = scheduler.enter(x, 1, fun, (x,))
scheduler.run()
self.assertEqual(l, [0.1, 0.2, 0.3, 0.4, 0.5])
def test_enterabs(self):
l = []
fun = lambda x: l.append(x)
scheduler = sched.scheduler(time.time, time.sleep)
for x in [0.05, 0.04, 0.03, 0.02, 0.01]:
z = scheduler.enterabs(x, 1, fun, (x,))
scheduler.run()
self.assertEqual(l, [0.01, 0.02, 0.03, 0.04, 0.05])
@unittest.skipUnless(threading, 'Threading required for this test.')
def test_enter_concurrent(self):
q = queue.Queue()
fun = q.put
timer = Timer()
scheduler = sched.scheduler(timer.time, timer.sleep)
scheduler.enter(1, 1, fun, (1,))
scheduler.enter(3, 1, fun, (3,))
t = threading.Thread(target=scheduler.run)
t.start()
timer.advance(1)
self.assertEqual(q.get(timeout=TIMEOUT), 1)
self.assertTrue(q.empty())
for x in [4, 5, 2]:
z = scheduler.enter(x - 1, 1, fun, (x,))
timer.advance(2)
self.assertEqual(q.get(timeout=TIMEOUT), 2)
self.assertEqual(q.get(timeout=TIMEOUT), 3)
self.assertTrue(q.empty())
timer.advance(1)
self.assertEqual(q.get(timeout=TIMEOUT), 4)
self.assertTrue(q.empty())
timer.advance(1)
self.assertEqual(q.get(timeout=TIMEOUT), 5)
self.assertTrue(q.empty())
timer.advance(1000)
t.join(timeout=TIMEOUT)
self.assertFalse(t.is_alive())
self.assertTrue(q.empty())
self.assertEqual(timer.time(), 5)
def test_priority(self):
l = []
fun = lambda x: l.append(x)
scheduler = sched.scheduler(time.time, time.sleep)
for priority in [1, 2, 3, 4, 5]:
z = scheduler.enterabs(0.01, priority, fun, (priority,))
scheduler.run()
self.assertEqual(l, [1, 2, 3, 4, 5])
def test_cancel(self):
l = []
fun = lambda x: l.append(x)
scheduler = sched.scheduler(time.time, time.sleep)
now = time.time()
event1 = scheduler.enterabs(now + 0.01, 1, fun, (0.01,))
event2 = scheduler.enterabs(now + 0.02, 1, fun, (0.02,))
event3 = scheduler.enterabs(now + 0.03, 1, fun, (0.03,))
event4 = scheduler.enterabs(now + 0.04, 1, fun, (0.04,))
event5 = scheduler.enterabs(now + 0.05, 1, fun, (0.05,))
scheduler.cancel(event1)
scheduler.cancel(event5)
scheduler.run()
self.assertEqual(l, [0.02, 0.03, 0.04])
@unittest.skipUnless(threading, 'Threading required for this test.')
def test_cancel_concurrent(self):
q = queue.Queue()
fun = q.put
timer = Timer()
scheduler = sched.scheduler(timer.time, timer.sleep)
now = timer.time()
event1 = scheduler.enterabs(now + 1, 1, fun, (1,))
event2 = scheduler.enterabs(now + 2, 1, fun, (2,))
event4 = scheduler.enterabs(now + 4, 1, fun, (4,))
event5 = scheduler.enterabs(now + 5, 1, fun, (5,))
event3 = scheduler.enterabs(now + 3, 1, fun, (3,))
t = threading.Thread(target=scheduler.run)
t.start()
timer.advance(1)
self.assertEqual(q.get(timeout=TIMEOUT), 1)
self.assertTrue(q.empty())
scheduler.cancel(event2)
scheduler.cancel(event5)
timer.advance(1)
self.assertTrue(q.empty())
timer.advance(1)
self.assertEqual(q.get(timeout=TIMEOUT), 3)
self.assertTrue(q.empty())
timer.advance(1)
self.assertEqual(q.get(timeout=TIMEOUT), 4)
self.assertTrue(q.empty())
timer.advance(1000)
t.join(timeout=TIMEOUT)
self.assertFalse(t.is_alive())
self.assertTrue(q.empty())
self.assertEqual(timer.time(), 4)
def test_empty(self):
l = []
fun = lambda x: l.append(x)
scheduler = sched.scheduler(time.time, time.sleep)
self.assertTrue(scheduler.empty())
for x in [0.05, 0.04, 0.03, 0.02, 0.01]:
z = scheduler.enterabs(x, 1, fun, (x,))
self.assertFalse(scheduler.empty())
scheduler.run()
self.assertTrue(scheduler.empty())
def test_queue(self):
l = []
fun = lambda x: l.append(x)
scheduler = sched.scheduler(time.time, time.sleep)
now = time.time()
e5 = scheduler.enterabs(now + 0.05, 1, fun)
e1 = scheduler.enterabs(now + 0.01, 1, fun)
e2 = scheduler.enterabs(now + 0.02, 1, fun)
e4 = scheduler.enterabs(now + 0.04, 1, fun)
e3 = scheduler.enterabs(now + 0.03, 1, fun)
# queue property is supposed to return an order list of
# upcoming events
self.assertEqual(scheduler.queue, [e1, e2, e3, e4, e5])
def test_args_kwargs(self):
seq = []
def fun(*a, **b):
seq.append((a, b))
now = time.time()
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enterabs(now, 1, fun)
scheduler.enterabs(now, 1, fun, argument=(1, 2))
scheduler.enterabs(now, 1, fun, argument=('a', 'b'))
scheduler.enterabs(now, 1, fun, argument=(1, 2), kwargs={"foo": 3})
scheduler.run()
self.assertCountEqual(seq, [
((), {}),
((1, 2), {}),
(('a', 'b'), {}),
((1, 2), {'foo': 3})
])
def test_run_non_blocking(self):
l = []
fun = lambda x: l.append(x)
scheduler = sched.scheduler(time.time, time.sleep)
for x in [10, 9, 8, 7, 6]:
scheduler.enter(x, 1, fun, (x,))
scheduler.run(blocking=False)
self.assertEqual(l, [])
if __name__ == "__main__":
unittest.main()
| 6,796 | 206 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_re.py | from test.support import verbose, run_unittest, gc_collect, bigmemtest, _2G, \
cpython_only, captured_stdout
import io
import locale
import re
import sre_compile
import string
import sys
import traceback
import unittest
import warnings
from re import Scanner
from weakref import proxy
# Misc tests from Tim Peters' re.doc
# WARNING: Don't change details in these tests if you don't know
# what you're doing. Some of these tests were carefully modeled to
# cover most of the code.
class S(str):
def __getitem__(self, index):
return S(super().__getitem__(index))
class B(bytes):
def __getitem__(self, index):
return B(super().__getitem__(index))
class ReTests(unittest.TestCase):
def assertTypedEqual(self, actual, expect, msg=None):
self.assertEqual(actual, expect, msg)
def recurse(actual, expect):
if isinstance(expect, (tuple, list)):
for x, y in zip(actual, expect):
recurse(x, y)
else:
self.assertIs(type(actual), type(expect), msg)
recurse(actual, expect)
def checkPatternError(self, pattern, errmsg, pos=None):
with self.assertRaises(re.error) as cm:
re.compile(pattern)
with self.subTest(pattern=pattern):
err = cm.exception
self.assertEqual(err.msg, errmsg)
if pos is not None:
self.assertEqual(err.pos, pos)
def checkTemplateError(self, pattern, repl, string, errmsg, pos=None):
with self.assertRaises(re.error) as cm:
re.sub(pattern, repl, string)
with self.subTest(pattern=pattern, repl=repl):
err = cm.exception
self.assertEqual(err.msg, errmsg)
if pos is not None:
self.assertEqual(err.pos, pos)
def test_keep_buffer(self):
# See bug 14212
b = bytearray(b'x')
it = re.finditer(b'a', b)
with self.assertRaises(BufferError):
b.extend(b'x'*400)
list(it)
del it
gc_collect()
b.extend(b'x'*400)
def test_weakref(self):
s = 'QabbbcR'
x = re.compile('ab+c')
y = proxy(x)
self.assertEqual(x.findall('QabbbcR'), y.findall('QabbbcR'))
def test_search_star_plus(self):
self.assertEqual(re.search('x*', 'axx').span(0), (0, 0))
self.assertEqual(re.search('x*', 'axx').span(), (0, 0))
self.assertEqual(re.search('x+', 'axx').span(0), (1, 3))
self.assertEqual(re.search('x+', 'axx').span(), (1, 3))
self.assertIsNone(re.search('x', 'aaa'))
self.assertEqual(re.match('a*', 'xxx').span(0), (0, 0))
self.assertEqual(re.match('a*', 'xxx').span(), (0, 0))
self.assertEqual(re.match('x*', 'xxxa').span(0), (0, 3))
self.assertEqual(re.match('x*', 'xxxa').span(), (0, 3))
self.assertIsNone(re.match('a+', 'xxx'))
def bump_num(self, matchobj):
int_value = int(matchobj.group(0))
return str(int_value + 1)
def test_basic_re_sub(self):
self.assertTypedEqual(re.sub('y', 'a', 'xyz'), 'xaz')
self.assertTypedEqual(re.sub('y', S('a'), S('xyz')), 'xaz')
self.assertTypedEqual(re.sub(b'y', b'a', b'xyz'), b'xaz')
self.assertTypedEqual(re.sub(b'y', B(b'a'), B(b'xyz')), b'xaz')
self.assertTypedEqual(re.sub(b'y', bytearray(b'a'), bytearray(b'xyz')), b'xaz')
self.assertTypedEqual(re.sub(b'y', memoryview(b'a'), memoryview(b'xyz')), b'xaz')
for y in ("\xe0", "\u0430", "\U0001d49c"):
self.assertEqual(re.sub(y, 'a', 'x%sz' % y), 'xaz')
self.assertEqual(re.sub("(?i)b+", "x", "bbbb BBBB"), 'x x')
self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y'),
'9.3 -3 24x100y')
self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y', 3),
'9.3 -3 23x99y')
self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y', count=3),
'9.3 -3 23x99y')
self.assertEqual(re.sub('.', lambda m: r"\n", 'x'), '\\n')
self.assertEqual(re.sub('.', r"\n", 'x'), '\n')
s = r"\1\1"
self.assertEqual(re.sub('(.)', s, 'x'), 'xx')
self.assertEqual(re.sub('(.)', s.replace('\\', r'\\'), 'x'), s)
self.assertEqual(re.sub('(.)', lambda m: s, 'x'), s)
self.assertEqual(re.sub('(?P<a>x)', r'\g<a>\g<a>', 'xx'), 'xxxx')
self.assertEqual(re.sub('(?P<a>x)', r'\g<a>\g<1>', 'xx'), 'xxxx')
self.assertEqual(re.sub('(?P<unk>x)', r'\g<unk>\g<unk>', 'xx'), 'xxxx')
self.assertEqual(re.sub('(?P<unk>x)', r'\g<1>\g<1>', 'xx'), 'xxxx')
self.assertEqual(re.sub('a', r'\t\n\v\r\f\a\b', 'a'), '\t\n\v\r\f\a\b')
self.assertEqual(re.sub('a', '\t\n\v\r\f\a\b', 'a'), '\t\n\v\r\f\a\b')
self.assertEqual(re.sub('a', '\t\n\v\r\f\a\b', 'a'),
(chr(9)+chr(10)+chr(11)+chr(13)+chr(12)+chr(7)+chr(8)))
for c in 'cdehijklmopqsuwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ':
with self.subTest(c):
with self.assertWarns(DeprecationWarning):
self.assertEqual(re.sub('a', '\\' + c, 'a'), '\\' + c)
self.assertEqual(re.sub(r'^\s*', 'X', 'test'), 'Xtest')
def test_bug_449964(self):
# fails for group followed by other escape
self.assertEqual(re.sub(r'(?P<unk>x)', r'\g<1>\g<1>\b', 'xx'),
'xx\bxx\b')
def test_bug_449000(self):
# Test for sub() on escaped characters
self.assertEqual(re.sub(r'\r\n', r'\n', 'abc\r\ndef\r\n'),
'abc\ndef\n')
self.assertEqual(re.sub('\r\n', r'\n', 'abc\r\ndef\r\n'),
'abc\ndef\n')
self.assertEqual(re.sub(r'\r\n', '\n', 'abc\r\ndef\r\n'),
'abc\ndef\n')
self.assertEqual(re.sub('\r\n', '\n', 'abc\r\ndef\r\n'),
'abc\ndef\n')
def test_bug_1661(self):
# Verify that flags do not get silently ignored with compiled patterns
pattern = re.compile('.')
self.assertRaises(ValueError, re.match, pattern, 'A', re.I)
self.assertRaises(ValueError, re.search, pattern, 'A', re.I)
self.assertRaises(ValueError, re.findall, pattern, 'A', re.I)
self.assertRaises(ValueError, re.compile, pattern, re.I)
def test_bug_3629(self):
# A regex that triggered a bug in the sre-code validator
re.compile("(?P<quote>)(?(quote))")
def test_sub_template_numeric_escape(self):
# bug 776311 and friends
self.assertEqual(re.sub('x', r'\0', 'x'), '\0')
self.assertEqual(re.sub('x', r'\000', 'x'), '\000')
self.assertEqual(re.sub('x', r'\001', 'x'), '\001')
self.assertEqual(re.sub('x', r'\008', 'x'), '\0' + '8')
self.assertEqual(re.sub('x', r'\009', 'x'), '\0' + '9')
self.assertEqual(re.sub('x', r'\111', 'x'), '\111')
self.assertEqual(re.sub('x', r'\117', 'x'), '\117')
self.assertEqual(re.sub('x', r'\377', 'x'), '\377')
self.assertEqual(re.sub('x', r'\1111', 'x'), '\1111')
self.assertEqual(re.sub('x', r'\1111', 'x'), '\111' + '1')
self.assertEqual(re.sub('x', r'\00', 'x'), '\x00')
self.assertEqual(re.sub('x', r'\07', 'x'), '\x07')
self.assertEqual(re.sub('x', r'\08', 'x'), '\0' + '8')
self.assertEqual(re.sub('x', r'\09', 'x'), '\0' + '9')
self.assertEqual(re.sub('x', r'\0a', 'x'), '\0' + 'a')
self.checkTemplateError('x', r'\400', 'x',
r'octal escape value \400 outside of '
r'range 0-0o377', 0)
self.checkTemplateError('x', r'\777', 'x',
r'octal escape value \777 outside of '
r'range 0-0o377', 0)
self.checkTemplateError('x', r'\1', 'x', 'invalid group reference 1', 1)
self.checkTemplateError('x', r'\8', 'x', 'invalid group reference 8', 1)
self.checkTemplateError('x', r'\9', 'x', 'invalid group reference 9', 1)
self.checkTemplateError('x', r'\11', 'x', 'invalid group reference 11', 1)
self.checkTemplateError('x', r'\18', 'x', 'invalid group reference 18', 1)
self.checkTemplateError('x', r'\1a', 'x', 'invalid group reference 1', 1)
self.checkTemplateError('x', r'\90', 'x', 'invalid group reference 90', 1)
self.checkTemplateError('x', r'\99', 'x', 'invalid group reference 99', 1)
self.checkTemplateError('x', r'\118', 'x', 'invalid group reference 11', 1)
self.checkTemplateError('x', r'\11a', 'x', 'invalid group reference 11', 1)
self.checkTemplateError('x', r'\181', 'x', 'invalid group reference 18', 1)
self.checkTemplateError('x', r'\800', 'x', 'invalid group reference 80', 1)
self.checkTemplateError('x', r'\8', '', 'invalid group reference 8', 1)
# in python2.3 (etc), these loop endlessly in sre_parser.py
self.assertEqual(re.sub('(((((((((((x)))))))))))', r'\11', 'x'), 'x')
self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\118', 'xyz'),
'xz8')
self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\11a', 'xyz'),
'xza')
def test_qualified_re_sub(self):
self.assertEqual(re.sub('a', 'b', 'aaaaa'), 'bbbbb')
self.assertEqual(re.sub('a', 'b', 'aaaaa', 1), 'baaaa')
self.assertEqual(re.sub('a', 'b', 'aaaaa', count=1), 'baaaa')
def test_bug_114660(self):
self.assertEqual(re.sub(r'(\S)\s+(\S)', r'\1 \2', 'hello there'),
'hello there')
def test_bug_462270(self):
# Test for empty sub() behaviour, see SF bug #462270
self.assertEqual(re.sub('x*', '-', 'abxd'), '-a-b-d-')
self.assertEqual(re.sub('x+', '-', 'abxd'), 'ab-d')
def test_symbolic_groups(self):
re.compile(r'(?P<a>x)(?P=a)(?(a)y)')
re.compile(r'(?P<a1>x)(?P=a1)(?(a1)y)')
re.compile(r'(?P<a1>x)\1(?(1)y)')
self.checkPatternError(r'(?P<a>)(?P<a>)',
"redefinition of group name 'a' as group 2; "
"was group 1")
self.checkPatternError(r'(?P<a>(?P=a))',
"cannot refer to an open group", 10)
self.checkPatternError(r'(?Pxy)', 'unknown extension ?Px')
self.checkPatternError(r'(?P<a>)(?P=a', 'missing ), unterminated name', 11)
self.checkPatternError(r'(?P=', 'missing group name', 4)
self.checkPatternError(r'(?P=)', 'missing group name', 4)
self.checkPatternError(r'(?P=1)', "bad character in group name '1'", 4)
self.checkPatternError(r'(?P=a)', "unknown group name 'a'")
self.checkPatternError(r'(?P=a1)', "unknown group name 'a1'")
self.checkPatternError(r'(?P=a.)', "bad character in group name 'a.'", 4)
self.checkPatternError(r'(?P<)', 'missing >, unterminated name', 4)
self.checkPatternError(r'(?P<a', 'missing >, unterminated name', 4)
self.checkPatternError(r'(?P<', 'missing group name', 4)
self.checkPatternError(r'(?P<>)', 'missing group name', 4)
self.checkPatternError(r'(?P<1>)', "bad character in group name '1'", 4)
self.checkPatternError(r'(?P<a.>)', "bad character in group name 'a.'", 4)
self.checkPatternError(r'(?(', 'missing group name', 3)
self.checkPatternError(r'(?())', 'missing group name', 3)
self.checkPatternError(r'(?(a))', "unknown group name 'a'", 3)
self.checkPatternError(r'(?(-1))', "bad character in group name '-1'", 3)
self.checkPatternError(r'(?(1a))', "bad character in group name '1a'", 3)
self.checkPatternError(r'(?(a.))', "bad character in group name 'a.'", 3)
# New valid/invalid identifiers in Python 3
re.compile('(?P<µ>x)(?P=µ)(?(µ)y)')
re.compile('(?P<ðð«ð¦ð ð¬ð¡ð¢>x)(?P=ðð«ð¦ð ð¬ð¡ð¢)(?(ðð«ð¦ð ð¬ð¡ð¢)y)')
self.checkPatternError('(?P<©>x)', "bad character in group name '©'", 4)
# Support > 100 groups.
pat = '|'.join('x(?P<a%d>%x)y' % (i, i) for i in range(1, 200 + 1))
pat = '(?:%s)(?(200)z|t)' % pat
self.assertEqual(re.match(pat, 'xc8yz').span(), (0, 5))
def test_symbolic_refs(self):
self.checkTemplateError('(?P<a>x)', r'\g<a', 'xx',
'missing >, unterminated name', 3)
self.checkTemplateError('(?P<a>x)', r'\g<', 'xx',
'missing group name', 3)
self.checkTemplateError('(?P<a>x)', r'\g', 'xx', 'missing <', 2)
self.checkTemplateError('(?P<a>x)', r'\g<a a>', 'xx',
"bad character in group name 'a a'", 3)
self.checkTemplateError('(?P<a>x)', r'\g<>', 'xx',
'missing group name', 3)
self.checkTemplateError('(?P<a>x)', r'\g<1a1>', 'xx',
"bad character in group name '1a1'", 3)
self.checkTemplateError('(?P<a>x)', r'\g<2>', 'xx',
'invalid group reference 2', 3)
self.checkTemplateError('(?P<a>x)', r'\2', 'xx',
'invalid group reference 2', 1)
with self.assertRaisesRegex(IndexError, "unknown group name 'ab'"):
re.sub('(?P<a>x)', r'\g<ab>', 'xx')
self.assertEqual(re.sub('(?P<a>x)|(?P<b>y)', r'\g<b>', 'xx'), '')
self.assertEqual(re.sub('(?P<a>x)|(?P<b>y)', r'\2', 'xx'), '')
self.checkTemplateError('(?P<a>x)', r'\g<-1>', 'xx',
"bad character in group name '-1'", 3)
# New valid/invalid identifiers in Python 3
self.assertEqual(re.sub('(?P<µ>x)', r'\g<µ>', 'xx'), 'xx')
self.assertEqual(re.sub('(?P<ðð«ð¦ð ð¬ð¡ð¢>x)', r'\g<ðð«ð¦ð ð¬ð¡ð¢>', 'xx'), 'xx')
self.checkTemplateError('(?P<a>x)', r'\g<©>', 'xx',
"bad character in group name '©'", 3)
# Support > 100 groups.
pat = '|'.join('x(?P<a%d>%x)y' % (i, i) for i in range(1, 200 + 1))
self.assertEqual(re.sub(pat, r'\g<200>', 'xc8yzxc8y'), 'c8zc8')
def test_re_subn(self):
self.assertEqual(re.subn("(?i)b+", "x", "bbbb BBBB"), ('x x', 2))
self.assertEqual(re.subn("b+", "x", "bbbb BBBB"), ('x BBBB', 1))
self.assertEqual(re.subn("b+", "x", "xyz"), ('xyz', 0))
self.assertEqual(re.subn("b*", "x", "xyz"), ('xxxyxzx', 4))
self.assertEqual(re.subn("b*", "x", "xyz", 2), ('xxxyz', 2))
self.assertEqual(re.subn("b*", "x", "xyz", count=2), ('xxxyz', 2))
def test_re_split(self):
for string in ":a:b::c", S(":a:b::c"):
self.assertTypedEqual(re.split(":", string),
['', 'a', 'b', '', 'c'])
self.assertTypedEqual(re.split(":+", string),
['', 'a', 'b', 'c'])
self.assertTypedEqual(re.split("(:+)", string),
['', ':', 'a', ':', 'b', '::', 'c'])
for string in (b":a:b::c", B(b":a:b::c"), bytearray(b":a:b::c"),
memoryview(b":a:b::c")):
self.assertTypedEqual(re.split(b":", string),
[b'', b'a', b'b', b'', b'c'])
self.assertTypedEqual(re.split(b":+", string),
[b'', b'a', b'b', b'c'])
self.assertTypedEqual(re.split(b"(:+)", string),
[b'', b':', b'a', b':', b'b', b'::', b'c'])
for a, b, c in ("\xe0\xdf\xe7", "\u0430\u0431\u0432",
"\U0001d49c\U0001d49e\U0001d4b5"):
string = ":%s:%s::%s" % (a, b, c)
self.assertEqual(re.split(":", string), ['', a, b, '', c])
self.assertEqual(re.split(":+", string), ['', a, b, c])
self.assertEqual(re.split("(:+)", string),
['', ':', a, ':', b, '::', c])
self.assertEqual(re.split("(?::+)", ":a:b::c"), ['', 'a', 'b', 'c'])
self.assertEqual(re.split("(:)+", ":a:b::c"),
['', ':', 'a', ':', 'b', ':', 'c'])
self.assertEqual(re.split("([b:]+)", ":a:b::c"),
['', ':', 'a', ':b::', 'c'])
self.assertEqual(re.split("(b)|(:+)", ":a:b::c"),
['', None, ':', 'a', None, ':', '', 'b', None, '',
None, '::', 'c'])
self.assertEqual(re.split("(?:b)|(?::+)", ":a:b::c"),
['', 'a', '', '', 'c'])
for sep, expected in [
(':*', ['', 'a', 'b', 'c']),
('(?::*)', ['', 'a', 'b', 'c']),
('(:*)', ['', ':', 'a', ':', 'b', '::', 'c']),
('(:)*', ['', ':', 'a', ':', 'b', ':', 'c']),
]:
with self.subTest(sep=sep), self.assertWarns(FutureWarning):
self.assertTypedEqual(re.split(sep, ':a:b::c'), expected)
for sep, expected in [
('', [':a:b::c']),
(r'\b', [':a:b::c']),
(r'(?=:)', [':a:b::c']),
(r'(?<=:)', [':a:b::c']),
]:
with self.subTest(sep=sep), self.assertRaises(ValueError):
self.assertTypedEqual(re.split(sep, ':a:b::c'), expected)
def test_qualified_re_split(self):
self.assertEqual(re.split(":", ":a:b::c", 2), ['', 'a', 'b::c'])
self.assertEqual(re.split(":", ":a:b::c", maxsplit=2), ['', 'a', 'b::c'])
self.assertEqual(re.split(':', 'a:b:c:d', maxsplit=2), ['a', 'b', 'c:d'])
self.assertEqual(re.split("(:)", ":a:b::c", maxsplit=2),
['', ':', 'a', ':', 'b::c'])
self.assertEqual(re.split("(:+)", ":a:b::c", maxsplit=2),
['', ':', 'a', ':', 'b::c'])
with self.assertWarns(FutureWarning):
self.assertEqual(re.split("(:*)", ":a:b::c", maxsplit=2),
['', ':', 'a', ':', 'b::c'])
def test_re_findall(self):
self.assertEqual(re.findall(":+", "abc"), [])
for string in "a:b::c:::d", S("a:b::c:::d"):
self.assertTypedEqual(re.findall(":+", string),
[":", "::", ":::"])
self.assertTypedEqual(re.findall("(:+)", string),
[":", "::", ":::"])
self.assertTypedEqual(re.findall("(:)(:*)", string),
[(":", ""), (":", ":"), (":", "::")])
for string in (b"a:b::c:::d", B(b"a:b::c:::d"), bytearray(b"a:b::c:::d"),
memoryview(b"a:b::c:::d")):
self.assertTypedEqual(re.findall(b":+", string),
[b":", b"::", b":::"])
self.assertTypedEqual(re.findall(b"(:+)", string),
[b":", b"::", b":::"])
self.assertTypedEqual(re.findall(b"(:)(:*)", string),
[(b":", b""), (b":", b":"), (b":", b"::")])
for x in ("\xe0", "\u0430", "\U0001d49c"):
xx = x * 2
xxx = x * 3
string = "a%sb%sc%sd" % (x, xx, xxx)
self.assertEqual(re.findall("%s+" % x, string), [x, xx, xxx])
self.assertEqual(re.findall("(%s+)" % x, string), [x, xx, xxx])
self.assertEqual(re.findall("(%s)(%s*)" % (x, x), string),
[(x, ""), (x, x), (x, xx)])
def test_bug_117612(self):
self.assertEqual(re.findall(r"(a|(b))", "aba"),
[("a", ""),("b", "b"),("a", "")])
def test_re_match(self):
for string in 'a', S('a'):
self.assertEqual(re.match('a', string).groups(), ())
self.assertEqual(re.match('(a)', string).groups(), ('a',))
self.assertEqual(re.match('(a)', string).group(0), 'a')
self.assertEqual(re.match('(a)', string).group(1), 'a')
self.assertEqual(re.match('(a)', string).group(1, 1), ('a', 'a'))
for string in b'a', B(b'a'), bytearray(b'a'), memoryview(b'a'):
self.assertEqual(re.match(b'a', string).groups(), ())
self.assertEqual(re.match(b'(a)', string).groups(), (b'a',))
self.assertEqual(re.match(b'(a)', string).group(0), b'a')
self.assertEqual(re.match(b'(a)', string).group(1), b'a')
self.assertEqual(re.match(b'(a)', string).group(1, 1), (b'a', b'a'))
for a in ("\xe0", "\u0430", "\U0001d49c"):
self.assertEqual(re.match(a, a).groups(), ())
self.assertEqual(re.match('(%s)' % a, a).groups(), (a,))
self.assertEqual(re.match('(%s)' % a, a).group(0), a)
self.assertEqual(re.match('(%s)' % a, a).group(1), a)
self.assertEqual(re.match('(%s)' % a, a).group(1, 1), (a, a))
pat = re.compile('((a)|(b))(c)?')
self.assertEqual(pat.match('a').groups(), ('a', 'a', None, None))
self.assertEqual(pat.match('b').groups(), ('b', None, 'b', None))
self.assertEqual(pat.match('ac').groups(), ('a', 'a', None, 'c'))
self.assertEqual(pat.match('bc').groups(), ('b', None, 'b', 'c'))
self.assertEqual(pat.match('bc').groups(""), ('b', "", 'b', 'c'))
pat = re.compile('(?:(?P<a1>a)|(?P<b2>b))(?P<c3>c)?')
self.assertEqual(pat.match('a').group(1, 2, 3), ('a', None, None))
self.assertEqual(pat.match('b').group('a1', 'b2', 'c3'),
(None, 'b', None))
self.assertEqual(pat.match('ac').group(1, 'b2', 3), ('a', None, 'c'))
def test_group(self):
class Index:
def __init__(self, value):
self.value = value
def __index__(self):
return self.value
# A single group
m = re.match('(a)(b)', 'ab')
self.assertEqual(m.group(), 'ab')
self.assertEqual(m.group(0), 'ab')
self.assertEqual(m.group(1), 'a')
self.assertEqual(m.group(Index(1)), 'a')
self.assertRaises(IndexError, m.group, -1)
self.assertRaises(IndexError, m.group, 3)
self.assertRaises(IndexError, m.group, 1<<1000)
self.assertRaises(IndexError, m.group, Index(1<<1000))
self.assertRaises(IndexError, m.group, 'x')
# Multiple groups
self.assertEqual(m.group(2, 1), ('b', 'a'))
self.assertEqual(m.group(Index(2), Index(1)), ('b', 'a'))
def test_match_getitem(self):
pat = re.compile('(?:(?P<a1>a)|(?P<b2>b))(?P<c3>c)?')
m = pat.match('a')
self.assertEqual(m['a1'], 'a')
self.assertEqual(m['b2'], None)
self.assertEqual(m['c3'], None)
self.assertEqual('a1={a1} b2={b2} c3={c3}'.format_map(m), 'a1=a b2=None c3=None')
self.assertEqual(m[0], 'a')
self.assertEqual(m[1], 'a')
self.assertEqual(m[2], None)
self.assertEqual(m[3], None)
with self.assertRaisesRegex(IndexError, 'no such group'):
m['X']
with self.assertRaisesRegex(IndexError, 'no such group'):
m[-1]
with self.assertRaisesRegex(IndexError, 'no such group'):
m[4]
with self.assertRaisesRegex(IndexError, 'no such group'):
m[0, 1]
with self.assertRaisesRegex(IndexError, 'no such group'):
m[(0,)]
with self.assertRaisesRegex(IndexError, 'no such group'):
m[(0, 1)]
with self.assertRaisesRegex(IndexError, 'no such group'):
'a1={a2}'.format_map(m)
m = pat.match('ac')
self.assertEqual(m['a1'], 'a')
self.assertEqual(m['b2'], None)
self.assertEqual(m['c3'], 'c')
self.assertEqual('a1={a1} b2={b2} c3={c3}'.format_map(m), 'a1=a b2=None c3=c')
self.assertEqual(m[0], 'ac')
self.assertEqual(m[1], 'a')
self.assertEqual(m[2], None)
self.assertEqual(m[3], 'c')
# Cannot assign.
with self.assertRaises(TypeError):
m[0] = 1
# No len().
self.assertRaises(TypeError, len, m)
def test_re_fullmatch(self):
# Issue 16203: Proposal: add re.fullmatch() method.
self.assertEqual(re.fullmatch(r"a", "a").span(), (0, 1))
for string in "ab", S("ab"):
self.assertEqual(re.fullmatch(r"a|ab", string).span(), (0, 2))
for string in b"ab", B(b"ab"), bytearray(b"ab"), memoryview(b"ab"):
self.assertEqual(re.fullmatch(br"a|ab", string).span(), (0, 2))
for a, b in "\xe0\xdf", "\u0430\u0431", "\U0001d49c\U0001d49e":
r = r"%s|%s" % (a, a + b)
self.assertEqual(re.fullmatch(r, a + b).span(), (0, 2))
self.assertEqual(re.fullmatch(r".*?$", "abc").span(), (0, 3))
self.assertEqual(re.fullmatch(r".*?", "abc").span(), (0, 3))
self.assertEqual(re.fullmatch(r"a.*?b", "ab").span(), (0, 2))
self.assertEqual(re.fullmatch(r"a.*?b", "abb").span(), (0, 3))
self.assertEqual(re.fullmatch(r"a.*?b", "axxb").span(), (0, 4))
self.assertIsNone(re.fullmatch(r"a+", "ab"))
self.assertIsNone(re.fullmatch(r"abc$", "abc\n"))
self.assertIsNone(re.fullmatch(r"abc\Z", "abc\n"))
self.assertIsNone(re.fullmatch(r"(?m)abc$", "abc\n"))
self.assertEqual(re.fullmatch(r"ab(?=c)cd", "abcd").span(), (0, 4))
self.assertEqual(re.fullmatch(r"ab(?<=b)cd", "abcd").span(), (0, 4))
self.assertEqual(re.fullmatch(r"(?=a|ab)ab", "ab").span(), (0, 2))
self.assertEqual(
re.compile(r"bc").fullmatch("abcd", pos=1, endpos=3).span(), (1, 3))
self.assertEqual(
re.compile(r".*?$").fullmatch("abcd", pos=1, endpos=3).span(), (1, 3))
self.assertEqual(
re.compile(r".*?").fullmatch("abcd", pos=1, endpos=3).span(), (1, 3))
def test_re_groupref_exists(self):
self.assertEqual(re.match(r'^(\()?([^()]+)(?(1)\))$', '(a)').groups(),
('(', 'a'))
self.assertEqual(re.match(r'^(\()?([^()]+)(?(1)\))$', 'a').groups(),
(None, 'a'))
self.assertIsNone(re.match(r'^(\()?([^()]+)(?(1)\))$', 'a)'))
self.assertIsNone(re.match(r'^(\()?([^()]+)(?(1)\))$', '(a'))
self.assertEqual(re.match('^(?:(a)|c)((?(1)b|d))$', 'ab').groups(),
('a', 'b'))
self.assertEqual(re.match(r'^(?:(a)|c)((?(1)b|d))$', 'cd').groups(),
(None, 'd'))
self.assertEqual(re.match(r'^(?:(a)|c)((?(1)|d))$', 'cd').groups(),
(None, 'd'))
self.assertEqual(re.match(r'^(?:(a)|c)((?(1)|d))$', 'a').groups(),
('a', ''))
# Tests for bug #1177831: exercise groups other than the first group
p = re.compile('(?P<g1>a)(?P<g2>b)?((?(g2)c|d))')
self.assertEqual(p.match('abc').groups(),
('a', 'b', 'c'))
self.assertEqual(p.match('ad').groups(),
('a', None, 'd'))
self.assertIsNone(p.match('abd'))
self.assertIsNone(p.match('ac'))
# Support > 100 groups.
pat = '|'.join('x(?P<a%d>%x)y' % (i, i) for i in range(1, 200 + 1))
pat = '(?:%s)(?(200)z)' % pat
self.assertEqual(re.match(pat, 'xc8yz').span(), (0, 5))
self.checkPatternError(r'(?P<a>)(?(0))', 'bad group number', 10)
self.checkPatternError(r'()(?(1)a|b',
'missing ), unterminated subpattern', 2)
self.checkPatternError(r'()(?(1)a|b|c)',
'conditional backref with more than '
'two branches', 10)
def test_re_groupref_overflow(self):
from sre_constants import MAXGROUPS
self.checkTemplateError('()', r'\g<%s>' % MAXGROUPS, 'xx',
'invalid group reference %d' % MAXGROUPS, 3)
self.checkPatternError(r'(?P<a>)(?(%d))' % MAXGROUPS,
'invalid group reference %d' % MAXGROUPS, 10)
def test_re_groupref(self):
self.assertEqual(re.match(r'^(\|)?([^()]+)\1$', '|a|').groups(),
('|', 'a'))
self.assertEqual(re.match(r'^(\|)?([^()]+)\1?$', 'a').groups(),
(None, 'a'))
self.assertIsNone(re.match(r'^(\|)?([^()]+)\1$', 'a|'))
self.assertIsNone(re.match(r'^(\|)?([^()]+)\1$', '|a'))
self.assertEqual(re.match(r'^(?:(a)|c)(\1)$', 'aa').groups(),
('a', 'a'))
self.assertEqual(re.match(r'^(?:(a)|c)(\1)?$', 'c').groups(),
(None, None))
self.checkPatternError(r'(abc\1)', 'cannot refer to an open group', 4)
def test_groupdict(self):
self.assertEqual(re.match('(?P<first>first) (?P<second>second)',
'first second').groupdict(),
{'first':'first', 'second':'second'})
def test_expand(self):
self.assertEqual(re.match("(?P<first>first) (?P<second>second)",
"first second")
.expand(r"\2 \1 \g<second> \g<first>"),
"second first second first")
self.assertEqual(re.match("(?P<first>first)|(?P<second>second)",
"first")
.expand(r"\2 \g<second>"),
" ")
def test_repeat_minmax(self):
self.assertIsNone(re.match(r"^(\w){1}$", "abc"))
self.assertIsNone(re.match(r"^(\w){1}?$", "abc"))
self.assertIsNone(re.match(r"^(\w){1,2}$", "abc"))
self.assertIsNone(re.match(r"^(\w){1,2}?$", "abc"))
self.assertEqual(re.match(r"^(\w){3}$", "abc").group(1), "c")
self.assertEqual(re.match(r"^(\w){1,3}$", "abc").group(1), "c")
self.assertEqual(re.match(r"^(\w){1,4}$", "abc").group(1), "c")
self.assertEqual(re.match(r"^(\w){3,4}?$", "abc").group(1), "c")
self.assertEqual(re.match(r"^(\w){3}?$", "abc").group(1), "c")
self.assertEqual(re.match(r"^(\w){1,3}?$", "abc").group(1), "c")
self.assertEqual(re.match(r"^(\w){1,4}?$", "abc").group(1), "c")
self.assertEqual(re.match(r"^(\w){3,4}?$", "abc").group(1), "c")
self.assertIsNone(re.match(r"^x{1}$", "xxx"))
self.assertIsNone(re.match(r"^x{1}?$", "xxx"))
self.assertIsNone(re.match(r"^x{1,2}$", "xxx"))
self.assertIsNone(re.match(r"^x{1,2}?$", "xxx"))
self.assertTrue(re.match(r"^x{3}$", "xxx"))
self.assertTrue(re.match(r"^x{1,3}$", "xxx"))
self.assertTrue(re.match(r"^x{3,3}$", "xxx"))
self.assertTrue(re.match(r"^x{1,4}$", "xxx"))
self.assertTrue(re.match(r"^x{3,4}?$", "xxx"))
self.assertTrue(re.match(r"^x{3}?$", "xxx"))
self.assertTrue(re.match(r"^x{1,3}?$", "xxx"))
self.assertTrue(re.match(r"^x{1,4}?$", "xxx"))
self.assertTrue(re.match(r"^x{3,4}?$", "xxx"))
self.assertIsNone(re.match(r"^x{}$", "xxx"))
self.assertTrue(re.match(r"^x{}$", "x{}"))
self.checkPatternError(r'x{2,1}',
'min repeat greater than max repeat', 2)
def test_getattr(self):
self.assertEqual(re.compile("(?i)(a)(b)").pattern, "(?i)(a)(b)")
self.assertEqual(re.compile("(?i)(a)(b)").flags, re.I | re.U)
self.assertEqual(re.compile("(?i)(a)(b)").groups, 2)
self.assertEqual(re.compile("(?i)(a)(b)").groupindex, {})
self.assertEqual(re.compile("(?i)(?P<first>a)(?P<other>b)").groupindex,
{'first': 1, 'other': 2})
self.assertEqual(re.match("(a)", "a").pos, 0)
self.assertEqual(re.match("(a)", "a").endpos, 1)
self.assertEqual(re.match("(a)", "a").string, "a")
self.assertEqual(re.match("(a)", "a").regs, ((0, 1), (0, 1)))
self.assertTrue(re.match("(a)", "a").re)
# Issue 14260. groupindex should be non-modifiable mapping.
p = re.compile(r'(?i)(?P<first>a)(?P<other>b)')
self.assertEqual(sorted(p.groupindex), ['first', 'other'])
self.assertEqual(p.groupindex['other'], 2)
with self.assertRaises(TypeError):
p.groupindex['other'] = 0
self.assertEqual(p.groupindex['other'], 2)
def test_special_escapes(self):
self.assertEqual(re.search(r"\b(b.)\b",
"abcd abc bcd bx").group(1), "bx")
self.assertEqual(re.search(r"\B(b.)\B",
"abc bcd bc abxd").group(1), "bx")
self.assertEqual(re.search(r"\b(b.)\b",
"abcd abc bcd bx", re.ASCII).group(1), "bx")
self.assertEqual(re.search(r"\B(b.)\B",
"abc bcd bc abxd", re.ASCII).group(1), "bx")
self.assertEqual(re.search(r"^abc$", "\nabc\n", re.M).group(0), "abc")
self.assertEqual(re.search(r"^\Aabc\Z$", "abc", re.M).group(0), "abc")
self.assertIsNone(re.search(r"^\Aabc\Z$", "\nabc\n", re.M))
self.assertEqual(re.search(br"\b(b.)\b",
b"abcd abc bcd bx").group(1), b"bx")
self.assertEqual(re.search(br"\B(b.)\B",
b"abc bcd bc abxd").group(1), b"bx")
self.assertEqual(re.search(br"\b(b.)\b",
b"abcd abc bcd bx", re.LOCALE).group(1), b"bx")
self.assertEqual(re.search(br"\B(b.)\B",
b"abc bcd bc abxd", re.LOCALE).group(1), b"bx")
self.assertEqual(re.search(br"^abc$", b"\nabc\n", re.M).group(0), b"abc")
self.assertEqual(re.search(br"^\Aabc\Z$", b"abc", re.M).group(0), b"abc")
self.assertIsNone(re.search(br"^\Aabc\Z$", b"\nabc\n", re.M))
self.assertEqual(re.search(r"\d\D\w\W\s\S",
"1aa! a").group(0), "1aa! a")
self.assertEqual(re.search(br"\d\D\w\W\s\S",
b"1aa! a").group(0), b"1aa! a")
self.assertEqual(re.search(r"\d\D\w\W\s\S",
"1aa! a", re.ASCII).group(0), "1aa! a")
self.assertEqual(re.search(br"\d\D\w\W\s\S",
b"1aa! a", re.LOCALE).group(0), b"1aa! a")
def test_other_escapes(self):
self.checkPatternError("\\", 'bad escape (end of pattern)', 0)
self.assertEqual(re.match(r"\(", '(').group(), '(')
self.assertIsNone(re.match(r"\(", ')'))
self.assertEqual(re.match(r"\\", '\\').group(), '\\')
self.assertEqual(re.match(r"[\]]", ']').group(), ']')
self.assertIsNone(re.match(r"[\]]", '['))
self.assertEqual(re.match(r"[a\-c]", '-').group(), '-')
self.assertIsNone(re.match(r"[a\-c]", 'b'))
self.assertEqual(re.match(r"[\^a]+", 'a^').group(), 'a^')
self.assertIsNone(re.match(r"[\^a]+", 'b'))
re.purge() # for warnings
for c in 'ceghijklmopqyzCEFGHIJKLMNOPQRTVXY':
with self.subTest(c):
self.assertRaises(re.error, re.compile, '\\%c' % c)
for c in 'ceghijklmopqyzABCEFGHIJKLMNOPQRTVXYZ':
with self.subTest(c):
self.assertRaises(re.error, re.compile, '[\\%c]' % c)
def test_string_boundaries(self):
# See http://bugs.python.org/issue10713
self.assertEqual(re.search(r"\b(abc)\b", "abc").group(1),
"abc")
# There's a word boundary at the start of a string.
self.assertTrue(re.match(r"\b", "abc"))
# A non-empty string includes a non-boundary zero-length match.
self.assertTrue(re.search(r"\B", "abc"))
# There is no non-boundary match at the start of a string.
self.assertFalse(re.match(r"\B", "abc"))
# However, an empty string contains no word boundaries, and also no
# non-boundaries.
self.assertIsNone(re.search(r"\B", ""))
# This one is questionable and different from the perlre behaviour,
# but describes current behavior.
self.assertIsNone(re.search(r"\b", ""))
# A single word-character string has two boundaries, but no
# non-boundary gaps.
self.assertEqual(len(re.findall(r"\b", "a")), 2)
self.assertEqual(len(re.findall(r"\B", "a")), 0)
# If there are no words, there are no boundaries
self.assertEqual(len(re.findall(r"\b", " ")), 0)
self.assertEqual(len(re.findall(r"\b", " ")), 0)
# Can match around the whitespace.
self.assertEqual(len(re.findall(r"\B", " ")), 2)
def test_bigcharset(self):
self.assertEqual(re.match("([\u2222\u2223])",
"\u2222").group(1), "\u2222")
r = '[%s]' % ''.join(map(chr, range(256, 2**16, 255)))
self.assertEqual(re.match(r, "\uff01").group(), "\uff01")
def test_big_codesize(self):
# Issue #1160
r = re.compile('|'.join(('%d'%x for x in range(10000))))
self.assertTrue(r.match('1000'))
self.assertTrue(r.match('9999'))
def test_anyall(self):
self.assertEqual(re.match("a.b", "a\nb", re.DOTALL).group(0),
"a\nb")
self.assertEqual(re.match("a.*b", "a\n\nb", re.DOTALL).group(0),
"a\n\nb")
def test_lookahead(self):
self.assertEqual(re.match(r"(a(?=\s[^a]))", "a b").group(1), "a")
self.assertEqual(re.match(r"(a(?=\s[^a]*))", "a b").group(1), "a")
self.assertEqual(re.match(r"(a(?=\s[abc]))", "a b").group(1), "a")
self.assertEqual(re.match(r"(a(?=\s[abc]*))", "a bc").group(1), "a")
self.assertEqual(re.match(r"(a)(?=\s\1)", "a a").group(1), "a")
self.assertEqual(re.match(r"(a)(?=\s\1*)", "a aa").group(1), "a")
self.assertEqual(re.match(r"(a)(?=\s(abc|a))", "a a").group(1), "a")
self.assertEqual(re.match(r"(a(?!\s[^a]))", "a a").group(1), "a")
self.assertEqual(re.match(r"(a(?!\s[abc]))", "a d").group(1), "a")
self.assertEqual(re.match(r"(a)(?!\s\1)", "a b").group(1), "a")
self.assertEqual(re.match(r"(a)(?!\s(abc|a))", "a b").group(1), "a")
# Group reference.
self.assertTrue(re.match(r'(a)b(?=\1)a', 'aba'))
self.assertIsNone(re.match(r'(a)b(?=\1)c', 'abac'))
# Conditional group reference.
self.assertTrue(re.match(r'(?:(a)|(x))b(?=(?(2)x|c))c', 'abc'))
self.assertIsNone(re.match(r'(?:(a)|(x))b(?=(?(2)c|x))c', 'abc'))
self.assertTrue(re.match(r'(?:(a)|(x))b(?=(?(2)x|c))c', 'abc'))
self.assertIsNone(re.match(r'(?:(a)|(x))b(?=(?(1)b|x))c', 'abc'))
self.assertTrue(re.match(r'(?:(a)|(x))b(?=(?(1)c|x))c', 'abc'))
# Group used before defined.
self.assertTrue(re.match(r'(a)b(?=(?(2)x|c))(c)', 'abc'))
self.assertIsNone(re.match(r'(a)b(?=(?(2)b|x))(c)', 'abc'))
self.assertTrue(re.match(r'(a)b(?=(?(1)c|x))(c)', 'abc'))
def test_lookbehind(self):
self.assertTrue(re.match(r'ab(?<=b)c', 'abc'))
self.assertIsNone(re.match(r'ab(?<=c)c', 'abc'))
self.assertIsNone(re.match(r'ab(?<!b)c', 'abc'))
self.assertTrue(re.match(r'ab(?<!c)c', 'abc'))
# Group reference.
self.assertTrue(re.match(r'(a)a(?<=\1)c', 'aac'))
self.assertIsNone(re.match(r'(a)b(?<=\1)a', 'abaa'))
self.assertIsNone(re.match(r'(a)a(?<!\1)c', 'aac'))
self.assertTrue(re.match(r'(a)b(?<!\1)a', 'abaa'))
# Conditional group reference.
self.assertIsNone(re.match(r'(?:(a)|(x))b(?<=(?(2)x|c))c', 'abc'))
self.assertIsNone(re.match(r'(?:(a)|(x))b(?<=(?(2)b|x))c', 'abc'))
self.assertTrue(re.match(r'(?:(a)|(x))b(?<=(?(2)x|b))c', 'abc'))
self.assertIsNone(re.match(r'(?:(a)|(x))b(?<=(?(1)c|x))c', 'abc'))
self.assertTrue(re.match(r'(?:(a)|(x))b(?<=(?(1)b|x))c', 'abc'))
# Group used before defined.
self.assertRaises(re.error, re.compile, r'(a)b(?<=(?(2)b|x))(c)')
self.assertIsNone(re.match(r'(a)b(?<=(?(1)c|x))(c)', 'abc'))
self.assertTrue(re.match(r'(a)b(?<=(?(1)b|x))(c)', 'abc'))
# Group defined in the same lookbehind pattern
self.assertRaises(re.error, re.compile, r'(a)b(?<=(.)\2)(c)')
self.assertRaises(re.error, re.compile, r'(a)b(?<=(?P<a>.)(?P=a))(c)')
self.assertRaises(re.error, re.compile, r'(a)b(?<=(a)(?(2)b|x))(c)')
self.assertRaises(re.error, re.compile, r'(a)b(?<=(.)(?<=\2))(c)')
def test_ignore_case(self):
self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC")
self.assertEqual(re.match(b"abc", b"ABC", re.I).group(0), b"ABC")
self.assertEqual(re.match(r"(a\s[^a])", "a b", re.I).group(1), "a b")
self.assertEqual(re.match(r"(a\s[^a]*)", "a bb", re.I).group(1), "a bb")
self.assertEqual(re.match(r"(a\s[abc])", "a b", re.I).group(1), "a b")
self.assertEqual(re.match(r"(a\s[abc]*)", "a bb", re.I).group(1), "a bb")
self.assertEqual(re.match(r"((a)\s\2)", "a a", re.I).group(1), "a a")
self.assertEqual(re.match(r"((a)\s\2*)", "a aa", re.I).group(1), "a aa")
self.assertEqual(re.match(r"((a)\s(abc|a))", "a a", re.I).group(1), "a a")
self.assertEqual(re.match(r"((a)\s(abc|a)*)", "a aa", re.I).group(1), "a aa")
assert '\u212a'.lower() == 'k' # 'âª'
self.assertTrue(re.match(r'K', '\u212a', re.I))
self.assertTrue(re.match(r'k', '\u212a', re.I))
self.assertTrue(re.match(r'\u212a', 'K', re.I))
self.assertTrue(re.match(r'\u212a', 'k', re.I))
assert '\u017f'.upper() == 'S' # 'Å¿'
self.assertTrue(re.match(r'S', '\u017f', re.I))
self.assertTrue(re.match(r's', '\u017f', re.I))
self.assertTrue(re.match(r'\u017f', 'S', re.I))
self.assertTrue(re.match(r'\u017f', 's', re.I))
assert '\ufb05'.upper() == '\ufb06'.upper() == 'ST' # 'ï¬
', 'ï¬'
self.assertTrue(re.match(r'\ufb05', '\ufb06', re.I))
self.assertTrue(re.match(r'\ufb06', '\ufb05', re.I))
def test_ignore_case_set(self):
self.assertTrue(re.match(r'[19A]', 'A', re.I))
self.assertTrue(re.match(r'[19a]', 'a', re.I))
self.assertTrue(re.match(r'[19a]', 'A', re.I))
self.assertTrue(re.match(r'[19A]', 'a', re.I))
self.assertTrue(re.match(br'[19A]', b'A', re.I))
self.assertTrue(re.match(br'[19a]', b'a', re.I))
self.assertTrue(re.match(br'[19a]', b'A', re.I))
self.assertTrue(re.match(br'[19A]', b'a', re.I))
assert '\u212a'.lower() == 'k' # 'âª'
self.assertTrue(re.match(r'[19K]', '\u212a', re.I))
self.assertTrue(re.match(r'[19k]', '\u212a', re.I))
self.assertTrue(re.match(r'[19\u212a]', 'K', re.I))
self.assertTrue(re.match(r'[19\u212a]', 'k', re.I))
assert '\u017f'.upper() == 'S' # 'Å¿'
self.assertTrue(re.match(r'[19S]', '\u017f', re.I))
self.assertTrue(re.match(r'[19s]', '\u017f', re.I))
self.assertTrue(re.match(r'[19\u017f]', 'S', re.I))
self.assertTrue(re.match(r'[19\u017f]', 's', re.I))
assert '\ufb05'.upper() == '\ufb06'.upper() == 'ST' # 'ï¬
', 'ï¬'
self.assertTrue(re.match(r'[19\ufb05]', '\ufb06', re.I))
self.assertTrue(re.match(r'[19\ufb06]', '\ufb05', re.I))
def test_ignore_case_range(self):
# Issues #3511, #17381.
self.assertTrue(re.match(r'[9-a]', '_', re.I))
self.assertIsNone(re.match(r'[9-A]', '_', re.I))
self.assertTrue(re.match(br'[9-a]', b'_', re.I))
self.assertIsNone(re.match(br'[9-A]', b'_', re.I))
self.assertTrue(re.match(r'[\xc0-\xde]', '\xd7', re.I))
self.assertIsNone(re.match(r'[\xc0-\xde]', '\xf7', re.I))
self.assertTrue(re.match(r'[\xe0-\xfe]', '\xf7', re.I))
self.assertIsNone(re.match(r'[\xe0-\xfe]', '\xd7', re.I))
self.assertTrue(re.match(r'[\u0430-\u045f]', '\u0450', re.I))
self.assertTrue(re.match(r'[\u0430-\u045f]', '\u0400', re.I))
self.assertTrue(re.match(r'[\u0400-\u042f]', '\u0450', re.I))
self.assertTrue(re.match(r'[\u0400-\u042f]', '\u0400', re.I))
self.assertTrue(re.match(r'[\U00010428-\U0001044f]', '\U00010428', re.I))
self.assertTrue(re.match(r'[\U00010428-\U0001044f]', '\U00010400', re.I))
self.assertTrue(re.match(r'[\U00010400-\U00010427]', '\U00010428', re.I))
self.assertTrue(re.match(r'[\U00010400-\U00010427]', '\U00010400', re.I))
assert '\u212a'.lower() == 'k' # 'âª'
self.assertTrue(re.match(r'[J-M]', '\u212a', re.I))
self.assertTrue(re.match(r'[j-m]', '\u212a', re.I))
self.assertTrue(re.match(r'[\u2129-\u212b]', 'K', re.I))
self.assertTrue(re.match(r'[\u2129-\u212b]', 'k', re.I))
assert '\u017f'.upper() == 'S' # 'Å¿'
self.assertTrue(re.match(r'[R-T]', '\u017f', re.I))
self.assertTrue(re.match(r'[r-t]', '\u017f', re.I))
self.assertTrue(re.match(r'[\u017e-\u0180]', 'S', re.I))
self.assertTrue(re.match(r'[\u017e-\u0180]', 's', re.I))
assert '\ufb05'.upper() == '\ufb06'.upper() == 'ST' # 'ï¬
', 'ï¬'
self.assertTrue(re.match(r'[\ufb04-\ufb05]', '\ufb06', re.I))
self.assertTrue(re.match(r'[\ufb06-\ufb07]', '\ufb05', re.I))
def test_category(self):
self.assertEqual(re.match(r"(\s)", " ").group(1), " ")
def test_getlower(self):
import _sre
self.assertEqual(_sre.getlower(ord('A'), 0), ord('a'))
self.assertEqual(_sre.getlower(ord('A'), re.LOCALE), ord('a'))
self.assertEqual(_sre.getlower(ord('A'), re.UNICODE), ord('a'))
self.assertEqual(_sre.getlower(ord('A'), re.ASCII), ord('a'))
self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC")
self.assertEqual(re.match(b"abc", b"ABC", re.I).group(0), b"ABC")
self.assertEqual(re.match("abc", "ABC", re.I|re.A).group(0), "ABC")
self.assertEqual(re.match(b"abc", b"ABC", re.I|re.L).group(0), b"ABC")
def test_not_literal(self):
self.assertEqual(re.search(r"\s([^a])", " b").group(1), "b")
self.assertEqual(re.search(r"\s([^a]*)", " bb").group(1), "bb")
def test_search_coverage(self):
self.assertEqual(re.search(r"\s(b)", " b").group(1), "b")
self.assertEqual(re.search(r"a\s", "a ").group(0), "a ")
def assertMatch(self, pattern, text, match=None, span=None,
matcher=re.match):
if match is None and span is None:
# the pattern matches the whole text
match = text
span = (0, len(text))
elif match is None or span is None:
raise ValueError('If match is not None, span should be specified '
'(and vice versa).')
m = matcher(pattern, text)
self.assertTrue(m)
self.assertEqual(m.group(), match)
self.assertEqual(m.span(), span)
def test_re_escape(self):
alnum_chars = string.ascii_letters + string.digits + '_'
p = ''.join(chr(i) for i in range(256))
for c in p:
if c in alnum_chars:
self.assertEqual(re.escape(c), c)
elif c == '\x00':
self.assertEqual(re.escape(c), '\\000')
else:
self.assertEqual(re.escape(c), '\\' + c)
self.assertMatch(re.escape(c), c)
self.assertMatch(re.escape(p), p)
def test_re_escape_byte(self):
alnum_chars = (string.ascii_letters + string.digits + '_').encode('ascii')
p = bytes(range(256))
for i in p:
b = bytes([i])
if b in alnum_chars:
self.assertEqual(re.escape(b), b)
elif i == 0:
self.assertEqual(re.escape(b), b'\\000')
else:
self.assertEqual(re.escape(b), b'\\' + b)
self.assertMatch(re.escape(b), b)
self.assertMatch(re.escape(p), p)
def test_re_escape_non_ascii(self):
s = 'xxx\u2620\u2620\u2620xxx'
s_escaped = re.escape(s)
self.assertEqual(s_escaped, 'xxx\\\u2620\\\u2620\\\u2620xxx')
self.assertMatch(s_escaped, s)
self.assertMatch('.%s+.' % re.escape('\u2620'), s,
'x\u2620\u2620\u2620x', (2, 7), re.search)
def test_re_escape_non_ascii_bytes(self):
b = 'y\u2620y\u2620y'.encode('utf-8')
b_escaped = re.escape(b)
self.assertEqual(b_escaped, b'y\\\xe2\\\x98\\\xa0y\\\xe2\\\x98\\\xa0y')
self.assertMatch(b_escaped, b)
res = re.findall(re.escape('\u2620'.encode('utf-8')), b)
self.assertEqual(len(res), 2)
def test_pickling(self):
import pickle
oldpat = re.compile('a(?:b|(c|e){1,2}?|d)+?(.)', re.UNICODE)
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
pickled = pickle.dumps(oldpat, proto)
newpat = pickle.loads(pickled)
self.assertEqual(newpat, oldpat)
# current pickle expects the _compile() reconstructor in re module
from re import _compile
def test_constants(self):
self.assertEqual(re.I, re.IGNORECASE)
self.assertEqual(re.L, re.LOCALE)
self.assertEqual(re.M, re.MULTILINE)
self.assertEqual(re.S, re.DOTALL)
self.assertEqual(re.X, re.VERBOSE)
def test_flags(self):
for flag in [re.I, re.M, re.X, re.S, re.A, re.U]:
self.assertTrue(re.compile('^pattern$', flag))
for flag in [re.I, re.M, re.X, re.S, re.A, re.L]:
self.assertTrue(re.compile(b'^pattern$', flag))
def test_sre_character_literals(self):
for i in [0, 8, 16, 32, 64, 127, 128, 255, 256, 0xFFFF, 0x10000, 0x10FFFF]:
if i < 256:
self.assertTrue(re.match(r"\%03o" % i, chr(i)))
self.assertTrue(re.match(r"\%03o0" % i, chr(i)+"0"))
self.assertTrue(re.match(r"\%03o8" % i, chr(i)+"8"))
self.assertTrue(re.match(r"\x%02x" % i, chr(i)))
self.assertTrue(re.match(r"\x%02x0" % i, chr(i)+"0"))
self.assertTrue(re.match(r"\x%02xz" % i, chr(i)+"z"))
if i < 0x10000:
self.assertTrue(re.match(r"\u%04x" % i, chr(i)))
self.assertTrue(re.match(r"\u%04x0" % i, chr(i)+"0"))
self.assertTrue(re.match(r"\u%04xz" % i, chr(i)+"z"))
self.assertTrue(re.match(r"\U%08x" % i, chr(i)))
self.assertTrue(re.match(r"\U%08x0" % i, chr(i)+"0"))
self.assertTrue(re.match(r"\U%08xz" % i, chr(i)+"z"))
self.assertTrue(re.match(r"\0", "\000"))
self.assertTrue(re.match(r"\08", "\0008"))
self.assertTrue(re.match(r"\01", "\001"))
self.assertTrue(re.match(r"\018", "\0018"))
self.checkPatternError(r"\567",
r'octal escape value \567 outside of '
r'range 0-0o377', 0)
self.checkPatternError(r"\911", 'invalid group reference 91', 1)
self.checkPatternError(r"\x1", r'incomplete escape \x1', 0)
self.checkPatternError(r"\x1z", r'incomplete escape \x1', 0)
self.checkPatternError(r"\u123", r'incomplete escape \u123', 0)
self.checkPatternError(r"\u123z", r'incomplete escape \u123', 0)
self.checkPatternError(r"\U0001234", r'incomplete escape \U0001234', 0)
self.checkPatternError(r"\U0001234z", r'incomplete escape \U0001234', 0)
self.checkPatternError(r"\U00110000", r'bad escape \U00110000', 0)
def test_sre_character_class_literals(self):
for i in [0, 8, 16, 32, 64, 127, 128, 255, 256, 0xFFFF, 0x10000, 0x10FFFF]:
if i < 256:
self.assertTrue(re.match(r"[\%o]" % i, chr(i)))
self.assertTrue(re.match(r"[\%o8]" % i, chr(i)))
self.assertTrue(re.match(r"[\%03o]" % i, chr(i)))
self.assertTrue(re.match(r"[\%03o0]" % i, chr(i)))
self.assertTrue(re.match(r"[\%03o8]" % i, chr(i)))
self.assertTrue(re.match(r"[\x%02x]" % i, chr(i)))
self.assertTrue(re.match(r"[\x%02x0]" % i, chr(i)))
self.assertTrue(re.match(r"[\x%02xz]" % i, chr(i)))
if i < 0x10000:
self.assertTrue(re.match(r"[\u%04x]" % i, chr(i)))
self.assertTrue(re.match(r"[\u%04x0]" % i, chr(i)))
self.assertTrue(re.match(r"[\u%04xz]" % i, chr(i)))
self.assertTrue(re.match(r"[\U%08x]" % i, chr(i)))
self.assertTrue(re.match(r"[\U%08x0]" % i, chr(i)+"0"))
self.assertTrue(re.match(r"[\U%08xz]" % i, chr(i)+"z"))
self.checkPatternError(r"[\567]",
r'octal escape value \567 outside of '
r'range 0-0o377', 1)
self.checkPatternError(r"[\911]", r'bad escape \9', 1)
self.checkPatternError(r"[\x1z]", r'incomplete escape \x1', 1)
self.checkPatternError(r"[\u123z]", r'incomplete escape \u123', 1)
self.checkPatternError(r"[\U0001234z]", r'incomplete escape \U0001234', 1)
self.checkPatternError(r"[\U00110000]", r'bad escape \U00110000', 1)
self.assertTrue(re.match(r"[\U0001d49c-\U0001d4b5]", "\U0001d49e"))
def test_sre_byte_literals(self):
for i in [0, 8, 16, 32, 64, 127, 128, 255]:
self.assertTrue(re.match((r"\%03o" % i).encode(), bytes([i])))
self.assertTrue(re.match((r"\%03o0" % i).encode(), bytes([i])+b"0"))
self.assertTrue(re.match((r"\%03o8" % i).encode(), bytes([i])+b"8"))
self.assertTrue(re.match((r"\x%02x" % i).encode(), bytes([i])))
self.assertTrue(re.match((r"\x%02x0" % i).encode(), bytes([i])+b"0"))
self.assertTrue(re.match((r"\x%02xz" % i).encode(), bytes([i])+b"z"))
self.assertRaises(re.error, re.compile, br"\u1234")
self.assertRaises(re.error, re.compile, br"\U00012345")
self.assertTrue(re.match(br"\0", b"\000"))
self.assertTrue(re.match(br"\08", b"\0008"))
self.assertTrue(re.match(br"\01", b"\001"))
self.assertTrue(re.match(br"\018", b"\0018"))
self.checkPatternError(br"\567",
r'octal escape value \567 outside of '
r'range 0-0o377', 0)
self.checkPatternError(br"\911", 'invalid group reference 91', 1)
self.checkPatternError(br"\x1", r'incomplete escape \x1', 0)
self.checkPatternError(br"\x1z", r'incomplete escape \x1', 0)
def test_sre_byte_class_literals(self):
for i in [0, 8, 16, 32, 64, 127, 128, 255]:
self.assertTrue(re.match((r"[\%o]" % i).encode(), bytes([i])))
self.assertTrue(re.match((r"[\%o8]" % i).encode(), bytes([i])))
self.assertTrue(re.match((r"[\%03o]" % i).encode(), bytes([i])))
self.assertTrue(re.match((r"[\%03o0]" % i).encode(), bytes([i])))
self.assertTrue(re.match((r"[\%03o8]" % i).encode(), bytes([i])))
self.assertTrue(re.match((r"[\x%02x]" % i).encode(), bytes([i])))
self.assertTrue(re.match((r"[\x%02x0]" % i).encode(), bytes([i])))
self.assertTrue(re.match((r"[\x%02xz]" % i).encode(), bytes([i])))
self.assertRaises(re.error, re.compile, br"[\u1234]")
self.assertRaises(re.error, re.compile, br"[\U00012345]")
self.checkPatternError(br"[\567]",
r'octal escape value \567 outside of '
r'range 0-0o377', 1)
self.checkPatternError(br"[\911]", r'bad escape \9', 1)
self.checkPatternError(br"[\x1z]", r'incomplete escape \x1', 1)
def test_character_set_errors(self):
self.checkPatternError(r'[', 'unterminated character set', 0)
self.checkPatternError(r'[^', 'unterminated character set', 0)
self.checkPatternError(r'[a', 'unterminated character set', 0)
# bug 545855 -- This pattern failed to cause a compile error as it
# should, instead provoking a TypeError.
self.checkPatternError(r"[a-", 'unterminated character set', 0)
self.checkPatternError(r"[\w-b]", r'bad character range \w-b', 1)
self.checkPatternError(r"[a-\w]", r'bad character range a-\w', 1)
self.checkPatternError(r"[b-a]", 'bad character range b-a', 1)
def test_bug_113254(self):
self.assertEqual(re.match(r'(a)|(b)', 'b').start(1), -1)
self.assertEqual(re.match(r'(a)|(b)', 'b').end(1), -1)
self.assertEqual(re.match(r'(a)|(b)', 'b').span(1), (-1, -1))
def test_bug_527371(self):
# bug described in patches 527371/672491
self.assertIsNone(re.match(r'(a)?a','a').lastindex)
self.assertEqual(re.match(r'(a)(b)?b','ab').lastindex, 1)
self.assertEqual(re.match(r'(?P<a>a)(?P<b>b)?b','ab').lastgroup, 'a')
self.assertEqual(re.match(r"(?P<a>a(b))", "ab").lastgroup, 'a')
self.assertEqual(re.match(r"((a))", "a").lastindex, 1)
def test_bug_418626(self):
# bugs 418626 at al. -- Testing Greg Chapman's addition of op code
# SRE_OP_MIN_REPEAT_ONE for eliminating recursion on simple uses of
# pattern '*?' on a long string.
self.assertEqual(re.match('.*?c', 10000*'ab'+'cd').end(0), 20001)
self.assertEqual(re.match('.*?cd', 5000*'ab'+'c'+5000*'ab'+'cde').end(0),
20003)
self.assertEqual(re.match('.*?cd', 20000*'abc'+'de').end(0), 60001)
# non-simple '*?' still used to hit the recursion limit, before the
# non-recursive scheme was implemented.
self.assertEqual(re.search('(a|b)*?c', 10000*'ab'+'cd').end(0), 20001)
def test_bug_612074(self):
pat="["+re.escape("\u2039")+"]"
self.assertEqual(re.compile(pat) and 1, 1)
def test_stack_overflow(self):
# nasty cases that used to overflow the straightforward recursive
# implementation of repeated groups.
self.assertEqual(re.match('(x)*', 50000*'x').group(1), 'x')
self.assertEqual(re.match('(x)*y', 50000*'x'+'y').group(1), 'x')
self.assertEqual(re.match('(x)*?y', 50000*'x'+'y').group(1), 'x')
def test_nothing_to_repeat(self):
for reps in '*', '+', '?', '{1,2}':
for mod in '', '?':
self.checkPatternError('%s%s' % (reps, mod),
'nothing to repeat', 0)
self.checkPatternError('(?:%s%s)' % (reps, mod),
'nothing to repeat', 3)
def test_multiple_repeat(self):
for outer_reps in '*', '+', '{1,2}':
for outer_mod in '', '?':
outer_op = outer_reps + outer_mod
for inner_reps in '*', '+', '?', '{1,2}':
for inner_mod in '', '?':
inner_op = inner_reps + inner_mod
self.checkPatternError(r'x%s%s' % (inner_op, outer_op),
'multiple repeat', 1 + len(inner_op))
def test_unlimited_zero_width_repeat(self):
# Issue #9669
self.assertIsNone(re.match(r'(?:a?)*y', 'z'))
self.assertIsNone(re.match(r'(?:a?)+y', 'z'))
self.assertIsNone(re.match(r'(?:a?){2,}y', 'z'))
self.assertIsNone(re.match(r'(?:a?)*?y', 'z'))
self.assertIsNone(re.match(r'(?:a?)+?y', 'z'))
self.assertIsNone(re.match(r'(?:a?){2,}?y', 'z'))
def test_scanner(self):
def s_ident(scanner, token): return token
def s_operator(scanner, token): return "op%s" % token
def s_float(scanner, token): return float(token)
def s_int(scanner, token): return int(token)
scanner = Scanner([
(r"[a-zA-Z_]\w*", s_ident),
(r"\d+\.\d*", s_float),
(r"\d+", s_int),
(r"=|\+|-|\*|/", s_operator),
(r"\s+", None),
])
self.assertTrue(scanner.scanner.scanner("").pattern)
self.assertEqual(scanner.scan("sum = 3*foo + 312.50 + bar"),
(['sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5,
'op+', 'bar'], ''))
def test_bug_448951(self):
# bug 448951 (similar to 429357, but with single char match)
# (Also test greedy matches.)
for op in '','?','*':
self.assertEqual(re.match(r'((.%s):)?z'%op, 'z').groups(),
(None, None))
self.assertEqual(re.match(r'((.%s):)?z'%op, 'a:z').groups(),
('a:', 'a'))
def test_bug_725106(self):
# capturing groups in alternatives in repeats
self.assertEqual(re.match('^((a)|b)*', 'abc').groups(),
('b', 'a'))
self.assertEqual(re.match('^(([ab])|c)*', 'abc').groups(),
('c', 'b'))
self.assertEqual(re.match('^((d)|[ab])*', 'abc').groups(),
('b', None))
self.assertEqual(re.match('^((a)c|[ab])*', 'abc').groups(),
('b', None))
self.assertEqual(re.match('^((a)|b)*?c', 'abc').groups(),
('b', 'a'))
self.assertEqual(re.match('^(([ab])|c)*?d', 'abcd').groups(),
('c', 'b'))
self.assertEqual(re.match('^((d)|[ab])*?c', 'abc').groups(),
('b', None))
self.assertEqual(re.match('^((a)c|[ab])*?c', 'abc').groups(),
('b', None))
def test_bug_725149(self):
# mark_stack_base restoring before restoring marks
self.assertEqual(re.match('(a)(?:(?=(b)*)c)*', 'abb').groups(),
('a', None))
self.assertEqual(re.match('(a)((?!(b)*))*', 'abb').groups(),
('a', None, None))
def test_bug_764548(self):
# bug 764548, re.compile() barfs on str/unicode subclasses
class my_unicode(str): pass
pat = re.compile(my_unicode("abc"))
self.assertIsNone(pat.match("xyz"))
def test_finditer(self):
iter = re.finditer(r":+", "a:b::c:::d")
self.assertEqual([item.group(0) for item in iter],
[":", "::", ":::"])
pat = re.compile(r":+")
iter = pat.finditer("a:b::c:::d", 1, 10)
self.assertEqual([item.group(0) for item in iter],
[":", "::", ":::"])
pat = re.compile(r":+")
iter = pat.finditer("a:b::c:::d", pos=1, endpos=10)
self.assertEqual([item.group(0) for item in iter],
[":", "::", ":::"])
pat = re.compile(r":+")
iter = pat.finditer("a:b::c:::d", endpos=10, pos=1)
self.assertEqual([item.group(0) for item in iter],
[":", "::", ":::"])
pat = re.compile(r":+")
iter = pat.finditer("a:b::c:::d", pos=3, endpos=8)
self.assertEqual([item.group(0) for item in iter],
["::", "::"])
def test_bug_926075(self):
self.assertIsNot(re.compile('bug_926075'),
re.compile(b'bug_926075'))
def test_bug_931848(self):
pattern = "[\u002E\u3002\uFF0E\uFF61]"
self.assertEqual(re.compile(pattern).split("a.b.c"),
['a','b','c'])
def test_bug_581080(self):
iter = re.finditer(r"\s", "a b")
self.assertEqual(next(iter).span(), (1,2))
self.assertRaises(StopIteration, next, iter)
scanner = re.compile(r"\s").scanner("a b")
self.assertEqual(scanner.search().span(), (1, 2))
self.assertIsNone(scanner.search())
def test_bug_817234(self):
iter = re.finditer(r".*", "asdf")
self.assertEqual(next(iter).span(), (0, 4))
self.assertEqual(next(iter).span(), (4, 4))
self.assertRaises(StopIteration, next, iter)
def test_bug_6561(self):
# '\d' should match characters in Unicode category 'Nd'
# (Number, Decimal Digit), but not those in 'Nl' (Number,
# Letter) or 'No' (Number, Other).
decimal_digits = [
'\u0037', # '\N{DIGIT SEVEN}', category 'Nd'
'\u0e58', # '\N{THAI DIGIT SIX}', category 'Nd'
'\uff10', # '\N{FULLWIDTH DIGIT ZERO}', category 'Nd'
]
for x in decimal_digits:
self.assertEqual(re.match(r'^\d$', x).group(0), x)
not_decimal_digits = [
'\u2165', # '\N{ROMAN NUMERAL SIX}', category 'Nl'
'\u3039', # '\N{HANGZHOU NUMERAL TWENTY}', category 'Nl'
'\u2082', # '\N{SUBSCRIPT TWO}', category 'No'
'\u32b4', # '\N{CIRCLED NUMBER THIRTY NINE}', category 'No'
]
for x in not_decimal_digits:
self.assertIsNone(re.match(r'^\d$', x))
def test_empty_array(self):
# SF buf 1647541
import array
for typecode in 'bBuhHiIlLfd':
a = array.array(typecode)
self.assertIsNone(re.compile(b"bla").match(a))
self.assertEqual(re.compile(b"").match(a).groups(), ())
def test_inline_flags(self):
# Bug #1700
upper_char = '\u1ea0' # Latin Capital Letter A with Dot Below
lower_char = '\u1ea1' # Latin Small Letter A with Dot Below
p = re.compile('.' + upper_char, re.I | re.S)
q = p.match('\n' + lower_char)
self.assertTrue(q)
p = re.compile('.' + lower_char, re.I | re.S)
q = p.match('\n' + upper_char)
self.assertTrue(q)
p = re.compile('(?i).' + upper_char, re.S)
q = p.match('\n' + lower_char)
self.assertTrue(q)
p = re.compile('(?i).' + lower_char, re.S)
q = p.match('\n' + upper_char)
self.assertTrue(q)
p = re.compile('(?is).' + upper_char)
q = p.match('\n' + lower_char)
self.assertTrue(q)
p = re.compile('(?is).' + lower_char)
q = p.match('\n' + upper_char)
self.assertTrue(q)
p = re.compile('(?s)(?i).' + upper_char)
q = p.match('\n' + lower_char)
self.assertTrue(q)
p = re.compile('(?s)(?i).' + lower_char)
q = p.match('\n' + upper_char)
self.assertTrue(q)
self.assertTrue(re.match('(?ix) ' + upper_char, lower_char))
self.assertTrue(re.match('(?ix) ' + lower_char, upper_char))
self.assertTrue(re.match(' (?i) ' + upper_char, lower_char, re.X))
self.assertTrue(re.match('(?x) (?i) ' + upper_char, lower_char))
self.assertTrue(re.match(' (?x) (?i) ' + upper_char, lower_char, re.X))
# [jart] why does it care if it's a py or pyc?
# p = upper_char + '(?i)'
# with self.assertWarns(DeprecationWarning) as warns:
# self.assertTrue(re.match(p, lower_char))
# self.assertEqual(
# str(warns.warnings[0].message),
# 'Flags not at the start of the expression %r' % p
# )
# self.assertEqual(warns.warnings[0].filename, __file__)
# p = upper_char + '(?i)%s' % ('.?' * 100)
# with self.assertWarns(DeprecationWarning) as warns:
# self.assertTrue(re.match(p, lower_char))
# self.assertEqual(
# str(warns.warnings[0].message),
# 'Flags not at the start of the expression %r (truncated)' % p[:20]
# )
# self.assertEqual(warns.warnings[0].filename, __file__)
# # bpo-30605: Compiling a bytes instance regex was throwing a BytesWarning
# with warnings.catch_warnings():
# warnings.simplefilter('error', BytesWarning)
# p = b'A(?i)'
# with self.assertWarns(DeprecationWarning) as warns:
# self.assertTrue(re.match(p, b'a'))
# self.assertEqual(
# str(warns.warnings[0].message),
# 'Flags not at the start of the expression %r' % p
# )
# self.assertEqual(warns.warnings[0].filename, __file__)
# with self.assertWarns(DeprecationWarning):
# self.assertTrue(re.match('(?s).(?i)' + upper_char, '\n' + lower_char))
# with self.assertWarns(DeprecationWarning):
# self.assertTrue(re.match('(?i) ' + upper_char + ' (?x)', lower_char))
# with self.assertWarns(DeprecationWarning):
# self.assertTrue(re.match(' (?x) (?i) ' + upper_char, lower_char))
# with self.assertWarns(DeprecationWarning):
# self.assertTrue(re.match('^(?i)' + upper_char, lower_char))
# with self.assertWarns(DeprecationWarning):
# self.assertTrue(re.match('$|(?i)' + upper_char, lower_char))
# with self.assertWarns(DeprecationWarning) as warns:
# self.assertTrue(re.match('(?:(?i)' + upper_char + ')', lower_char))
# self.assertRegex(str(warns.warnings[0].message),
# 'Flags not at the start')
# self.assertEqual(warns.warnings[0].filename, __file__)
# with self.assertWarns(DeprecationWarning) as warns:
# self.assertTrue(re.fullmatch('(^)?(?(1)(?i)' + upper_char + ')',
# lower_char))
# self.assertRegex(str(warns.warnings[0].message),
# 'Flags not at the start')
# self.assertEqual(warns.warnings[0].filename, __file__)
# with self.assertWarns(DeprecationWarning) as warns:
# self.assertTrue(re.fullmatch('($)?(?(1)|(?i)' + upper_char + ')',
# lower_char))
# self.assertRegex(str(warns.warnings[0].message),
# 'Flags not at the start')
# self.assertEqual(warns.warnings[0].filename, __file__)
def test_dollar_matches_twice(self):
"$ matches the end of string, and just before the terminating \n"
pattern = re.compile('$')
self.assertEqual(pattern.sub('#', 'a\nb\n'), 'a\nb#\n#')
self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a\nb\nc#')
self.assertEqual(pattern.sub('#', '\n'), '#\n#')
pattern = re.compile('$', re.MULTILINE)
self.assertEqual(pattern.sub('#', 'a\nb\n' ), 'a#\nb#\n#' )
self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a#\nb#\nc#')
self.assertEqual(pattern.sub('#', '\n'), '#\n#')
def test_bytes_str_mixing(self):
# Mixing str and bytes is disallowed
pat = re.compile('.')
bpat = re.compile(b'.')
self.assertRaises(TypeError, pat.match, b'b')
self.assertRaises(TypeError, bpat.match, 'b')
self.assertRaises(TypeError, pat.sub, b'b', 'c')
self.assertRaises(TypeError, pat.sub, 'b', b'c')
self.assertRaises(TypeError, pat.sub, b'b', b'c')
self.assertRaises(TypeError, bpat.sub, b'b', 'c')
self.assertRaises(TypeError, bpat.sub, 'b', b'c')
self.assertRaises(TypeError, bpat.sub, 'b', 'c')
def test_ascii_and_unicode_flag(self):
# String patterns
for flags in (0, re.UNICODE):
pat = re.compile('\xc0', flags | re.IGNORECASE)
self.assertTrue(pat.match('\xe0'))
pat = re.compile(r'\w', flags)
self.assertTrue(pat.match('\xe0'))
pat = re.compile('\xc0', re.ASCII | re.IGNORECASE)
self.assertIsNone(pat.match('\xe0'))
pat = re.compile('(?a)\xc0', re.IGNORECASE)
self.assertIsNone(pat.match('\xe0'))
pat = re.compile(r'\w', re.ASCII)
self.assertIsNone(pat.match('\xe0'))
pat = re.compile(r'(?a)\w')
self.assertIsNone(pat.match('\xe0'))
# Bytes patterns
for flags in (0, re.ASCII):
pat = re.compile(b'\xc0', flags | re.IGNORECASE)
self.assertIsNone(pat.match(b'\xe0'))
pat = re.compile(br'\w', flags)
self.assertIsNone(pat.match(b'\xe0'))
# Incompatibilities
self.assertRaises(ValueError, re.compile, br'\w', re.UNICODE)
self.assertRaises(ValueError, re.compile, br'(?u)\w')
self.assertRaises(ValueError, re.compile, r'\w', re.UNICODE | re.ASCII)
self.assertRaises(ValueError, re.compile, r'(?u)\w', re.ASCII)
self.assertRaises(ValueError, re.compile, r'(?a)\w', re.UNICODE)
self.assertRaises(ValueError, re.compile, r'(?au)\w')
def test_locale_flag(self):
import locale
_, enc = locale.getlocale(locale.LC_CTYPE)
# Search non-ASCII letter
for i in range(128, 256):
try:
c = bytes([i]).decode(enc)
sletter = c.lower()
if sletter == c: continue
bletter = sletter.encode(enc)
if len(bletter) != 1: continue
if bletter.decode(enc) != sletter: continue
bpat = re.escape(bytes([i]))
break
except (UnicodeError, TypeError):
pass
else:
bletter = None
bpat = b'A'
# Bytes patterns
pat = re.compile(bpat, re.LOCALE | re.IGNORECASE)
if bletter:
self.assertTrue(pat.match(bletter))
pat = re.compile(b'(?L)' + bpat, re.IGNORECASE)
if bletter:
self.assertTrue(pat.match(bletter))
pat = re.compile(bpat, re.IGNORECASE)
if bletter:
self.assertIsNone(pat.match(bletter))
pat = re.compile(br'\w', re.LOCALE)
if bletter:
self.assertTrue(pat.match(bletter))
pat = re.compile(br'(?L)\w')
if bletter:
self.assertTrue(pat.match(bletter))
pat = re.compile(br'\w')
if bletter:
self.assertIsNone(pat.match(bletter))
# Incompatibilities
self.assertRaises(ValueError, re.compile, '', re.LOCALE)
self.assertRaises(ValueError, re.compile, '(?L)')
self.assertRaises(ValueError, re.compile, b'', re.LOCALE | re.ASCII)
self.assertRaises(ValueError, re.compile, b'(?L)', re.ASCII)
self.assertRaises(ValueError, re.compile, b'(?a)', re.LOCALE)
self.assertRaises(ValueError, re.compile, b'(?aL)')
def test_scoped_flags(self):
self.assertTrue(re.match(r'(?i:a)b', 'Ab'))
self.assertIsNone(re.match(r'(?i:a)b', 'aB'))
self.assertIsNone(re.match(r'(?-i:a)b', 'Ab', re.IGNORECASE))
self.assertTrue(re.match(r'(?-i:a)b', 'aB', re.IGNORECASE))
self.assertIsNone(re.match(r'(?i:(?-i:a)b)', 'Ab'))
self.assertTrue(re.match(r'(?i:(?-i:a)b)', 'aB'))
self.assertTrue(re.match(r'(?x: a) b', 'a b'))
self.assertIsNone(re.match(r'(?x: a) b', ' a b'))
self.assertTrue(re.match(r'(?-x: a) b', ' ab', re.VERBOSE))
self.assertIsNone(re.match(r'(?-x: a) b', 'ab', re.VERBOSE))
self.checkPatternError(r'(?a:\w)',
'bad inline flags: cannot turn on global flag', 3)
self.checkPatternError(r'(?a)(?-a:\w)',
'bad inline flags: cannot turn off global flag', 8)
self.checkPatternError(r'(?i-i:a)',
'bad inline flags: flag turned on and off', 5)
self.checkPatternError(r'(?-', 'missing flag', 3)
self.checkPatternError(r'(?-+', 'missing flag', 3)
self.checkPatternError(r'(?-z', 'unknown flag', 3)
self.checkPatternError(r'(?-i', 'missing :', 4)
self.checkPatternError(r'(?-i)', 'missing :', 4)
self.checkPatternError(r'(?-i+', 'missing :', 4)
self.checkPatternError(r'(?-iz', 'unknown flag', 4)
self.checkPatternError(r'(?i:', 'missing ), unterminated subpattern', 0)
self.checkPatternError(r'(?i', 'missing -, : or )', 3)
self.checkPatternError(r'(?i+', 'missing -, : or )', 3)
self.checkPatternError(r'(?iz', 'unknown flag', 3)
def test_bug_6509(self):
# Replacement strings of both types must parse properly.
# all strings
pat = re.compile(r'a(\w)')
self.assertEqual(pat.sub('b\\1', 'ac'), 'bc')
pat = re.compile('a(.)')
self.assertEqual(pat.sub('b\\1', 'a\u1234'), 'b\u1234')
pat = re.compile('..')
self.assertEqual(pat.sub(lambda m: 'str', 'a5'), 'str')
# all bytes
pat = re.compile(br'a(\w)')
self.assertEqual(pat.sub(b'b\\1', b'ac'), b'bc')
pat = re.compile(b'a(.)')
self.assertEqual(pat.sub(b'b\\1', b'a\xCD'), b'b\xCD')
pat = re.compile(b'..')
self.assertEqual(pat.sub(lambda m: b'bytes', b'a5'), b'bytes')
def test_dealloc(self):
# issue 3299: check for segfault in debug build
import _sre
# the overflow limit is different on wide and narrow builds and it
# depends on the definition of SRE_CODE (see sre.h).
# 2**128 should be big enough to overflow on both. For smaller values
# a RuntimeError is raised instead of OverflowError.
long_overflow = 2**128
self.assertRaises(TypeError, re.finditer, "a", {})
with self.assertRaises(OverflowError):
_sre.compile("abc", 0, [long_overflow], 0, [], [])
with self.assertRaises(TypeError):
_sre.compile({}, 0, [], 0, [], [])
def test_search_dot_unicode(self):
self.assertTrue(re.search("123.*-", '123abc-'))
self.assertTrue(re.search("123.*-", '123\xe9-'))
self.assertTrue(re.search("123.*-", '123\u20ac-'))
self.assertTrue(re.search("123.*-", '123\U0010ffff-'))
self.assertTrue(re.search("123.*-", '123\xe9\u20ac\U0010ffff-'))
def test_compile(self):
# Test return value when given string and pattern as parameter
pattern = re.compile('random pattern')
self.assertIsInstance(pattern, re._pattern_type)
same_pattern = re.compile(pattern)
self.assertIsInstance(same_pattern, re._pattern_type)
self.assertIs(same_pattern, pattern)
# Test behaviour when not given a string or pattern as parameter
self.assertRaises(TypeError, re.compile, 0)
@bigmemtest(size=_2G, memuse=1)
def test_large_search(self, size):
# Issue #10182: indices were 32-bit-truncated.
s = 'a' * size
m = re.search('$', s)
self.assertIsNotNone(m)
self.assertEqual(m.start(), size)
self.assertEqual(m.end(), size)
# The huge memuse is because of re.sub() using a list and a join()
# to create the replacement result.
@bigmemtest(size=_2G, memuse=16 + 2)
def test_large_subn(self, size):
# Issue #10182: indices were 32-bit-truncated.
s = 'a' * size
r, n = re.subn('', '', s)
self.assertEqual(r, s)
self.assertEqual(n, size + 1)
def test_bug_16688(self):
# Issue 16688: Backreferences make case-insensitive regex fail on
# non-ASCII strings.
self.assertEqual(re.findall(r"(?i)(a)\1", "aa \u0100"), ['a'])
self.assertEqual(re.match(r"(?s).{1,3}", "\u0100\u0100").span(), (0, 2))
def test_repeat_minmax_overflow(self):
# Issue #13169
string = "x" * 100000
self.assertEqual(re.match(r".{65535}", string).span(), (0, 65535))
self.assertEqual(re.match(r".{,65535}", string).span(), (0, 65535))
self.assertEqual(re.match(r".{65535,}?", string).span(), (0, 65535))
self.assertEqual(re.match(r".{65536}", string).span(), (0, 65536))
self.assertEqual(re.match(r".{,65536}", string).span(), (0, 65536))
self.assertEqual(re.match(r".{65536,}?", string).span(), (0, 65536))
# 2**128 should be big enough to overflow both SRE_CODE and Py_ssize_t.
self.assertRaises(OverflowError, re.compile, r".{%d}" % 2**128)
self.assertRaises(OverflowError, re.compile, r".{,%d}" % 2**128)
self.assertRaises(OverflowError, re.compile, r".{%d,}?" % 2**128)
self.assertRaises(OverflowError, re.compile, r".{%d,%d}" % (2**129, 2**128))
@cpython_only
def test_repeat_minmax_overflow_maxrepeat(self):
try:
from _sre import MAXREPEAT
except ImportError:
self.skipTest('requires _sre.MAXREPEAT constant')
string = "x" * 100000
self.assertIsNone(re.match(r".{%d}" % (MAXREPEAT - 1), string))
self.assertEqual(re.match(r".{,%d}" % (MAXREPEAT - 1), string).span(),
(0, 100000))
self.assertIsNone(re.match(r".{%d,}?" % (MAXREPEAT - 1), string))
self.assertRaises(OverflowError, re.compile, r".{%d}" % MAXREPEAT)
self.assertRaises(OverflowError, re.compile, r".{,%d}" % MAXREPEAT)
self.assertRaises(OverflowError, re.compile, r".{%d,}?" % MAXREPEAT)
def test_backref_group_name_in_exception(self):
# Issue 17341: Poor error message when compiling invalid regex
self.checkPatternError('(?P=<foo>)',
"bad character in group name '<foo>'", 4)
def test_group_name_in_exception(self):
# Issue 17341: Poor error message when compiling invalid regex
self.checkPatternError('(?P<?foo>)',
"bad character in group name '?foo'", 4)
def test_issue17998(self):
for reps in '*', '+', '?', '{1}':
for mod in '', '?':
pattern = '.' + reps + mod + 'yz'
self.assertEqual(re.compile(pattern, re.S).findall('xyz'),
['xyz'], msg=pattern)
pattern = pattern.encode()
self.assertEqual(re.compile(pattern, re.S).findall(b'xyz'),
[b'xyz'], msg=pattern)
def test_match_repr(self):
for string in '[abracadabra]', S('[abracadabra]'):
m = re.search(r'(.+)(.*?)\1', string)
self.assertEqual(repr(m), "<%s.%s object; "
"span=(1, 12), match='abracadabra'>" %
(type(m).__module__, type(m).__qualname__))
for string in (b'[abracadabra]', B(b'[abracadabra]'),
bytearray(b'[abracadabra]'),
memoryview(b'[abracadabra]')):
m = re.search(br'(.+)(.*?)\1', string)
self.assertEqual(repr(m), "<%s.%s object; "
"span=(1, 12), match=b'abracadabra'>" %
(type(m).__module__, type(m).__qualname__))
first, second = list(re.finditer("(aa)|(bb)", "aa bb"))
self.assertEqual(repr(first), "<%s.%s object; "
"span=(0, 2), match='aa'>" %
(type(second).__module__, type(first).__qualname__))
self.assertEqual(repr(second), "<%s.%s object; "
"span=(3, 5), match='bb'>" %
(type(second).__module__, type(second).__qualname__))
def test_bug_2537(self):
# issue 2537: empty submatches
for outer_op in ('{0,}', '*', '+', '{1,187}'):
for inner_op in ('{0,}', '*', '?'):
r = re.compile("^((x|y)%s)%s" % (inner_op, outer_op))
m = r.match("xyyzy")
self.assertEqual(m.group(0), "xyy")
self.assertEqual(m.group(1), "")
self.assertEqual(m.group(2), "y")
def test_debug_flag(self):
pat = r'(\.)(?:[ch]|py)(?(1)$|: )'
with captured_stdout() as out:
re.compile(pat, re.DEBUG)
dump = '''\
SUBPATTERN 1 0 0
LITERAL 46
SUBPATTERN None 0 0
BRANCH
IN
LITERAL 99
LITERAL 104
OR
LITERAL 112
LITERAL 121
SUBPATTERN None 0 0
GROUPREF_EXISTS 1
AT AT_END
ELSE
LITERAL 58
LITERAL 32
'''
self.assertEqual(out.getvalue(), dump)
# Debug output is output again even a second time (bypassing
# the cache -- issue #20426).
with captured_stdout() as out:
re.compile(pat, re.DEBUG)
self.assertEqual(out.getvalue(), dump)
def test_keyword_parameters(self):
# Issue #20283: Accepting the string keyword parameter.
pat = re.compile(r'(ab)')
self.assertEqual(
pat.match(string='abracadabra', pos=7, endpos=10).span(), (7, 9))
self.assertEqual(
pat.fullmatch(string='abracadabra', pos=7, endpos=9).span(), (7, 9))
self.assertEqual(
pat.search(string='abracadabra', pos=3, endpos=10).span(), (7, 9))
self.assertEqual(
pat.findall(string='abracadabra', pos=3, endpos=10), ['ab'])
self.assertEqual(
pat.split(string='abracadabra', maxsplit=1),
['', 'ab', 'racadabra'])
self.assertEqual(
pat.scanner(string='abracadabra', pos=3, endpos=10).search().span(),
(7, 9))
def test_bug_20998(self):
# Issue #20998: Fullmatch of repeated single character pattern
# with ignore case.
self.assertEqual(re.fullmatch('[a-c]+', 'ABC', re.I).span(), (0, 3))
def test_locale_caching(self):
# Issue #22410
oldlocale = locale.setlocale(locale.LC_CTYPE)
self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
for loc in 'en_US.iso88591', 'en_US.utf8':
try:
locale.setlocale(locale.LC_CTYPE, loc)
except locale.Error:
# Unsupported locale on this system
self.skipTest('test needs %s locale' % loc)
re.purge()
self.check_en_US_iso88591()
self.check_en_US_utf8()
re.purge()
self.check_en_US_utf8()
self.check_en_US_iso88591()
def check_en_US_iso88591(self):
locale.setlocale(locale.LC_CTYPE, 'en_US.iso88591')
self.assertTrue(re.match(b'\xc5\xe5', b'\xc5\xe5', re.L|re.I))
self.assertTrue(re.match(b'\xc5', b'\xe5', re.L|re.I))
self.assertTrue(re.match(b'\xe5', b'\xc5', re.L|re.I))
self.assertTrue(re.match(b'(?Li)\xc5\xe5', b'\xc5\xe5'))
self.assertTrue(re.match(b'(?Li)\xc5', b'\xe5'))
self.assertTrue(re.match(b'(?Li)\xe5', b'\xc5'))
def check_en_US_utf8(self):
locale.setlocale(locale.LC_CTYPE, 'en_US.utf8')
self.assertTrue(re.match(b'\xc5\xe5', b'\xc5\xe5', re.L|re.I))
self.assertIsNone(re.match(b'\xc5', b'\xe5', re.L|re.I))
self.assertIsNone(re.match(b'\xe5', b'\xc5', re.L|re.I))
self.assertTrue(re.match(b'(?Li)\xc5\xe5', b'\xc5\xe5'))
self.assertIsNone(re.match(b'(?Li)\xc5', b'\xe5'))
self.assertIsNone(re.match(b'(?Li)\xe5', b'\xc5'))
def test_error(self):
with self.assertRaises(re.error) as cm:
re.compile('(\u20ac))')
err = cm.exception
self.assertIsInstance(err.pattern, str)
self.assertEqual(err.pattern, '(\u20ac))')
self.assertEqual(err.pos, 3)
self.assertEqual(err.lineno, 1)
self.assertEqual(err.colno, 4)
self.assertIn(err.msg, str(err))
self.assertIn(' at position 3', str(err))
self.assertNotIn(' at position 3', err.msg)
# Bytes pattern
with self.assertRaises(re.error) as cm:
re.compile(b'(\xa4))')
err = cm.exception
self.assertIsInstance(err.pattern, bytes)
self.assertEqual(err.pattern, b'(\xa4))')
self.assertEqual(err.pos, 3)
# Multiline pattern
with self.assertRaises(re.error) as cm:
re.compile("""
(
abc
)
)
(
""", re.VERBOSE)
err = cm.exception
self.assertEqual(err.pos, 77)
self.assertEqual(err.lineno, 5)
self.assertEqual(err.colno, 17)
self.assertIn(err.msg, str(err))
self.assertIn(' at position 77', str(err))
self.assertIn('(line 5, column 17)', str(err))
def test_misc_errors(self):
self.checkPatternError(r'(', 'missing ), unterminated subpattern', 0)
self.checkPatternError(r'((a|b)', 'missing ), unterminated subpattern', 0)
self.checkPatternError(r'(a|b))', 'unbalanced parenthesis', 5)
self.checkPatternError(r'(?P', 'unexpected end of pattern', 3)
self.checkPatternError(r'(?z)', 'unknown extension ?z', 1)
self.checkPatternError(r'(?iz)', 'unknown flag', 3)
self.checkPatternError(r'(?i', 'missing -, : or )', 3)
self.checkPatternError(r'(?#abc', 'missing ), unterminated comment', 0)
self.checkPatternError(r'(?<', 'unexpected end of pattern', 3)
self.checkPatternError(r'(?<>)', 'unknown extension ?<>', 1)
self.checkPatternError(r'(?', 'unexpected end of pattern', 2)
def test_enum(self):
# Issue #28082: Check that str(flag) returns a human readable string
# instead of an integer
self.assertIn('ASCII', str(re.A))
self.assertIn('DOTALL', str(re.S))
def test_pattern_compare(self):
pattern1 = re.compile('abc', re.IGNORECASE)
# equal to itself
self.assertEqual(pattern1, pattern1)
self.assertFalse(pattern1 != pattern1)
# equal
re.purge()
pattern2 = re.compile('abc', re.IGNORECASE)
self.assertEqual(hash(pattern2), hash(pattern1))
self.assertEqual(pattern2, pattern1)
# not equal: different pattern
re.purge()
pattern3 = re.compile('XYZ', re.IGNORECASE)
# Don't test hash(pattern3) != hash(pattern1) because there is no
# warranty that hash values are different
self.assertNotEqual(pattern3, pattern1)
# not equal: different flag (flags=0)
re.purge()
pattern4 = re.compile('abc')
self.assertNotEqual(pattern4, pattern1)
# only == and != comparison operators are supported
with self.assertRaises(TypeError):
pattern1 < pattern2
def test_pattern_compare_bytes(self):
pattern1 = re.compile(b'abc')
# equal: test bytes patterns
re.purge()
pattern2 = re.compile(b'abc')
self.assertEqual(hash(pattern2), hash(pattern1))
self.assertEqual(pattern2, pattern1)
# not equal: pattern of a different types (str vs bytes),
# comparison must not raise a BytesWarning
re.purge()
pattern3 = re.compile('abc')
with warnings.catch_warnings():
warnings.simplefilter('error', BytesWarning)
self.assertNotEqual(pattern3, pattern1)
def test_bug_29444(self):
s = bytearray(b'abcdefgh')
m = re.search(b'[a-h]+', s)
m2 = re.search(b'[e-h]+', s)
self.assertEqual(m.group(), b'abcdefgh')
self.assertEqual(m2.group(), b'efgh')
s[:] = b'xyz'
self.assertEqual(m.group(), b'xyz')
self.assertEqual(m2.group(), b'')
class PatternReprTests(unittest.TestCase):
def check(self, pattern, expected):
self.assertEqual(repr(re.compile(pattern)), expected)
def check_flags(self, pattern, flags, expected):
self.assertEqual(repr(re.compile(pattern, flags)), expected)
def test_without_flags(self):
self.check('random pattern',
"re.compile('random pattern')")
def test_single_flag(self):
self.check_flags('random pattern', re.IGNORECASE,
"re.compile('random pattern', re.IGNORECASE)")
def test_multiple_flags(self):
self.check_flags('random pattern', re.I|re.S|re.X,
"re.compile('random pattern', "
"re.IGNORECASE|re.DOTALL|re.VERBOSE)")
def test_unicode_flag(self):
self.check_flags('random pattern', re.U,
"re.compile('random pattern')")
self.check_flags('random pattern', re.I|re.S|re.U,
"re.compile('random pattern', "
"re.IGNORECASE|re.DOTALL)")
def test_inline_flags(self):
self.check('(?i)pattern',
"re.compile('(?i)pattern', re.IGNORECASE)")
def test_unknown_flags(self):
self.check_flags('random pattern', 0x123000,
"re.compile('random pattern', 0x123000)")
self.check_flags('random pattern', 0x123000|re.I,
"re.compile('random pattern', re.IGNORECASE|0x123000)")
def test_bytes(self):
self.check(b'bytes pattern',
"re.compile(b'bytes pattern')")
self.check_flags(b'bytes pattern', re.A,
"re.compile(b'bytes pattern', re.ASCII)")
def test_locale(self):
self.check_flags(b'bytes pattern', re.L,
"re.compile(b'bytes pattern', re.LOCALE)")
def test_quotes(self):
self.check('random "double quoted" pattern',
'''re.compile('random "double quoted" pattern')''')
self.check("random 'single quoted' pattern",
'''re.compile("random 'single quoted' pattern")''')
self.check('''both 'single' and "double" quotes''',
'''re.compile('both \\'single\\' and "double" quotes')''')
def test_long_pattern(self):
pattern = 'Very %spattern' % ('long ' * 1000)
r = repr(re.compile(pattern))
self.assertLess(len(r), 300)
self.assertEqual(r[:30], "re.compile('Very long long lon")
r = repr(re.compile(pattern, re.I))
self.assertLess(len(r), 300)
self.assertEqual(r[:30], "re.compile('Very long long lon")
self.assertEqual(r[-16:], ", re.IGNORECASE)")
class ImplementationTest(unittest.TestCase):
"""
Test implementation details of the re module.
"""
def test_overlap_table(self):
f = sre_compile._generate_overlap_table
self.assertEqual(f(""), [])
self.assertEqual(f("a"), [0])
self.assertEqual(f("abcd"), [0, 0, 0, 0])
self.assertEqual(f("aaaa"), [0, 1, 2, 3])
self.assertEqual(f("ababba"), [0, 0, 1, 2, 0, 1])
self.assertEqual(f("abcabdac"), [0, 0, 0, 1, 2, 0, 1, 0])
class ExternalTests(unittest.TestCase):
def test_re_benchmarks(self):
're_tests benchmarks'
from test.re_tests import benchmarks
for pattern, s in benchmarks:
with self.subTest(pattern=pattern, string=s):
p = re.compile(pattern)
self.assertTrue(p.search(s))
self.assertTrue(p.match(s))
self.assertTrue(p.fullmatch(s))
s2 = ' '*10000 + s + ' '*10000
self.assertTrue(p.search(s2))
self.assertTrue(p.match(s2, 10000))
self.assertTrue(p.match(s2, 10000, 10000 + len(s)))
self.assertTrue(p.fullmatch(s2, 10000, 10000 + len(s)))
def test_re_tests(self):
're_tests test suite'
from test.re_tests import tests, SUCCEED, FAIL, SYNTAX_ERROR
for t in tests:
pattern = s = outcome = repl = expected = None
if len(t) == 5:
pattern, s, outcome, repl, expected = t
elif len(t) == 3:
pattern, s, outcome = t
else:
raise ValueError('Test tuples should have 3 or 5 fields', t)
with self.subTest(pattern=pattern, string=s):
if outcome == SYNTAX_ERROR: # Expected a syntax error
with self.assertRaises(re.error):
re.compile(pattern)
continue
obj = re.compile(pattern)
result = obj.search(s)
if outcome == FAIL:
self.assertIsNone(result, 'Succeeded incorrectly')
continue
with self.subTest():
self.assertTrue(result, 'Failed incorrectly')
# Matched, as expected, so now we compute the
# result string and compare it to our expected result.
start, end = result.span(0)
vardict = {'found': result.group(0),
'groups': result.group(),
'flags': result.re.flags}
for i in range(1, 100):
try:
gi = result.group(i)
# Special hack because else the string concat fails:
if gi is None:
gi = "None"
except IndexError:
gi = "Error"
vardict['g%d' % i] = gi
for i in result.re.groupindex.keys():
try:
gi = result.group(i)
if gi is None:
gi = "None"
except IndexError:
gi = "Error"
vardict[i] = gi
self.assertEqual(eval(repl, vardict), expected,
'grouping error')
# Try the match with both pattern and string converted to
# bytes, and check that it still succeeds.
try:
bpat = bytes(pattern, "ascii")
bs = bytes(s, "ascii")
except UnicodeEncodeError:
# skip non-ascii tests
pass
else:
with self.subTest('bytes pattern match'):
obj = re.compile(bpat)
self.assertTrue(obj.search(bs))
# Try the match with LOCALE enabled, and check that it
# still succeeds.
with self.subTest('locale-sensitive match'):
obj = re.compile(bpat, re.LOCALE)
result = obj.search(bs)
if result is None:
print('=== Fails on locale-sensitive match', t)
# Try the match with the search area limited to the extent
# of the match and see if it still succeeds. \B will
# break (because it won't match at the end or start of a
# string), so we'll ignore patterns that feature it.
if (pattern[:2] != r'\B' and pattern[-2:] != r'\B'
and result is not None):
with self.subTest('range-limited match'):
obj = re.compile(pattern)
self.assertTrue(obj.search(s, start, end + 1))
# Try the match with IGNORECASE enabled, and check that it
# still succeeds.
with self.subTest('case-insensitive match'):
obj = re.compile(pattern, re.IGNORECASE)
self.assertTrue(obj.search(s))
# Try the match with UNICODE locale enabled, and check
# that it still succeeds.
with self.subTest('unicode-sensitive match'):
obj = re.compile(pattern, re.UNICODE)
self.assertTrue(obj.search(s))
if __name__ == "__main__":
unittest.main()
| 99,028 | 2,089 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_csv.py | # Copyright (C) 2001,2002 Python Software Foundation
# csv package unit tests
import copy
import sys
import unittest
from io import StringIO
from tempfile import TemporaryFile
import csv
import gc
import pickle
from test import support
from itertools import permutations
from textwrap import dedent
from collections import OrderedDict
class Test_Csv(unittest.TestCase):
"""
Test the underlying C csv parser in ways that are not appropriate
from the high level interface. Further tests of this nature are done
in TestDialectRegistry.
"""
def _test_arg_valid(self, ctor, arg):
self.assertRaises(TypeError, ctor)
self.assertRaises(TypeError, ctor, None)
self.assertRaises(TypeError, ctor, arg, bad_attr = 0)
self.assertRaises(TypeError, ctor, arg, delimiter = 0)
self.assertRaises(TypeError, ctor, arg, delimiter = 'XX')
self.assertRaises(csv.Error, ctor, arg, 'foo')
self.assertRaises(TypeError, ctor, arg, delimiter=None)
self.assertRaises(TypeError, ctor, arg, delimiter=1)
self.assertRaises(TypeError, ctor, arg, quotechar=1)
self.assertRaises(TypeError, ctor, arg, lineterminator=None)
self.assertRaises(TypeError, ctor, arg, lineterminator=1)
self.assertRaises(TypeError, ctor, arg, quoting=None)
self.assertRaises(TypeError, ctor, arg,
quoting=csv.QUOTE_ALL, quotechar='')
self.assertRaises(TypeError, ctor, arg,
quoting=csv.QUOTE_ALL, quotechar=None)
def test_reader_arg_valid(self):
self._test_arg_valid(csv.reader, [])
def test_writer_arg_valid(self):
self._test_arg_valid(csv.writer, StringIO())
def _test_default_attrs(self, ctor, *args):
obj = ctor(*args)
# Check defaults
self.assertEqual(obj.dialect.delimiter, ',')
self.assertEqual(obj.dialect.doublequote, True)
self.assertEqual(obj.dialect.escapechar, None)
self.assertEqual(obj.dialect.lineterminator, "\r\n")
self.assertEqual(obj.dialect.quotechar, '"')
self.assertEqual(obj.dialect.quoting, csv.QUOTE_MINIMAL)
self.assertEqual(obj.dialect.skipinitialspace, False)
self.assertEqual(obj.dialect.strict, False)
# Try deleting or changing attributes (they are read-only)
self.assertRaises(AttributeError, delattr, obj.dialect, 'delimiter')
self.assertRaises(AttributeError, setattr, obj.dialect, 'delimiter', ':')
self.assertRaises(AttributeError, delattr, obj.dialect, 'quoting')
self.assertRaises(AttributeError, setattr, obj.dialect,
'quoting', None)
def test_reader_attrs(self):
self._test_default_attrs(csv.reader, [])
def test_writer_attrs(self):
self._test_default_attrs(csv.writer, StringIO())
def _test_kw_attrs(self, ctor, *args):
# Now try with alternate options
kwargs = dict(delimiter=':', doublequote=False, escapechar='\\',
lineterminator='\r', quotechar='*',
quoting=csv.QUOTE_NONE, skipinitialspace=True,
strict=True)
obj = ctor(*args, **kwargs)
self.assertEqual(obj.dialect.delimiter, ':')
self.assertEqual(obj.dialect.doublequote, False)
self.assertEqual(obj.dialect.escapechar, '\\')
self.assertEqual(obj.dialect.lineterminator, "\r")
self.assertEqual(obj.dialect.quotechar, '*')
self.assertEqual(obj.dialect.quoting, csv.QUOTE_NONE)
self.assertEqual(obj.dialect.skipinitialspace, True)
self.assertEqual(obj.dialect.strict, True)
def test_reader_kw_attrs(self):
self._test_kw_attrs(csv.reader, [])
def test_writer_kw_attrs(self):
self._test_kw_attrs(csv.writer, StringIO())
def _test_dialect_attrs(self, ctor, *args):
# Now try with dialect-derived options
class dialect:
delimiter='-'
doublequote=False
escapechar='^'
lineterminator='$'
quotechar='#'
quoting=csv.QUOTE_ALL
skipinitialspace=True
strict=False
args = args + (dialect,)
obj = ctor(*args)
self.assertEqual(obj.dialect.delimiter, '-')
self.assertEqual(obj.dialect.doublequote, False)
self.assertEqual(obj.dialect.escapechar, '^')
self.assertEqual(obj.dialect.lineterminator, "$")
self.assertEqual(obj.dialect.quotechar, '#')
self.assertEqual(obj.dialect.quoting, csv.QUOTE_ALL)
self.assertEqual(obj.dialect.skipinitialspace, True)
self.assertEqual(obj.dialect.strict, False)
def test_reader_dialect_attrs(self):
self._test_dialect_attrs(csv.reader, [])
def test_writer_dialect_attrs(self):
self._test_dialect_attrs(csv.writer, StringIO())
def _write_test(self, fields, expect, **kwargs):
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj, **kwargs)
writer.writerow(fields)
fileobj.seek(0)
self.assertEqual(fileobj.read(),
expect + writer.dialect.lineterminator)
def _write_error_test(self, exc, fields, **kwargs):
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj, **kwargs)
with self.assertRaises(exc):
writer.writerow(fields)
fileobj.seek(0)
self.assertEqual(fileobj.read(), '')
def test_write_arg_valid(self):
self._write_error_test(csv.Error, None)
self._write_test((), '')
self._write_test([None], '""')
self._write_error_test(csv.Error, [None], quoting = csv.QUOTE_NONE)
# Check that exceptions are passed up the chain
class BadList:
def __len__(self):
return 10;
def __getitem__(self, i):
if i > 2:
raise OSError
self._write_error_test(OSError, BadList())
class BadItem:
def __str__(self):
raise OSError
self._write_error_test(OSError, [BadItem()])
def test_write_bigfield(self):
# This exercises the buffer realloc functionality
bigstring = 'X' * 50000
self._write_test([bigstring,bigstring], '%s,%s' % \
(bigstring, bigstring))
def test_write_quoting(self):
self._write_test(['a',1,'p,q'], 'a,1,"p,q"')
self._write_error_test(csv.Error, ['a',1,'p,q'],
quoting = csv.QUOTE_NONE)
self._write_test(['a',1,'p,q'], 'a,1,"p,q"',
quoting = csv.QUOTE_MINIMAL)
self._write_test(['a',1,'p,q'], '"a",1,"p,q"',
quoting = csv.QUOTE_NONNUMERIC)
self._write_test(['a',1,'p,q'], '"a","1","p,q"',
quoting = csv.QUOTE_ALL)
self._write_test(['a\nb',1], '"a\nb","1"',
quoting = csv.QUOTE_ALL)
def test_write_escape(self):
self._write_test(['a',1,'p,q'], 'a,1,"p,q"',
escapechar='\\')
self._write_error_test(csv.Error, ['a',1,'p,"q"'],
escapechar=None, doublequote=False)
self._write_test(['a',1,'p,"q"'], 'a,1,"p,\\"q\\""',
escapechar='\\', doublequote = False)
self._write_test(['"'], '""""',
escapechar='\\', quoting = csv.QUOTE_MINIMAL)
self._write_test(['"'], '\\"',
escapechar='\\', quoting = csv.QUOTE_MINIMAL,
doublequote = False)
self._write_test(['"'], '\\"',
escapechar='\\', quoting = csv.QUOTE_NONE)
self._write_test(['a',1,'p,q'], 'a,1,p\\,q',
escapechar='\\', quoting = csv.QUOTE_NONE)
def test_write_iterable(self):
self._write_test(iter(['a', 1, 'p,q']), 'a,1,"p,q"')
self._write_test(iter(['a', 1, None]), 'a,1,')
self._write_test(iter([]), '')
self._write_test(iter([None]), '""')
self._write_error_test(csv.Error, iter([None]), quoting=csv.QUOTE_NONE)
self._write_test(iter([None, None]), ',')
def test_writerows(self):
class BrokenFile:
def write(self, buf):
raise OSError
writer = csv.writer(BrokenFile())
self.assertRaises(OSError, writer.writerows, [['a']])
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj)
self.assertRaises(TypeError, writer.writerows, None)
writer.writerows([['a', 'b'], ['c', 'd']])
fileobj.seek(0)
self.assertEqual(fileobj.read(), "a,b\r\nc,d\r\n")
def test_writerows_with_none(self):
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj)
writer.writerows([['a', None], [None, 'd']])
fileobj.seek(0)
self.assertEqual(fileobj.read(), "a,\r\n,d\r\n")
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj)
writer.writerows([[None], ['a']])
fileobj.seek(0)
self.assertEqual(fileobj.read(), '""\r\na\r\n')
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj)
writer.writerows([['a'], [None]])
fileobj.seek(0)
self.assertEqual(fileobj.read(), 'a\r\n""\r\n')
@support.cpython_only
def test_writerows_legacy_strings(self):
import _testcapi
c = _testcapi.unicode_legacy_string('a')
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj)
writer.writerows([[c]])
fileobj.seek(0)
self.assertEqual(fileobj.read(), "a\r\n")
def _read_test(self, input, expect, **kwargs):
reader = csv.reader(input, **kwargs)
result = list(reader)
self.assertEqual(result, expect)
def test_read_oddinputs(self):
self._read_test([], [])
self._read_test([''], [[]])
self.assertRaises(csv.Error, self._read_test,
['"ab"c'], None, strict = 1)
# cannot handle null bytes for the moment
self.assertRaises(csv.Error, self._read_test,
['ab\0c'], None, strict = 1)
self._read_test(['"ab"c'], [['abc']], doublequote = 0)
self.assertRaises(csv.Error, self._read_test,
[b'ab\0c'], None)
def test_read_eol(self):
self._read_test(['a,b'], [['a','b']])
self._read_test(['a,b\n'], [['a','b']])
self._read_test(['a,b\r\n'], [['a','b']])
self._read_test(['a,b\r'], [['a','b']])
self.assertRaises(csv.Error, self._read_test, ['a,b\rc,d'], [])
self.assertRaises(csv.Error, self._read_test, ['a,b\nc,d'], [])
self.assertRaises(csv.Error, self._read_test, ['a,b\r\nc,d'], [])
def test_read_eof(self):
self._read_test(['a,"'], [['a', '']])
self._read_test(['"a'], [['a']])
self._read_test(['^'], [['\n']], escapechar='^')
self.assertRaises(csv.Error, self._read_test, ['a,"'], [], strict=True)
self.assertRaises(csv.Error, self._read_test, ['"a'], [], strict=True)
self.assertRaises(csv.Error, self._read_test,
['^'], [], escapechar='^', strict=True)
def test_read_escape(self):
self._read_test(['a,\\b,c'], [['a', 'b', 'c']], escapechar='\\')
self._read_test(['a,b\\,c'], [['a', 'b,c']], escapechar='\\')
self._read_test(['a,"b\\,c"'], [['a', 'b,c']], escapechar='\\')
self._read_test(['a,"b,\\c"'], [['a', 'b,c']], escapechar='\\')
self._read_test(['a,"b,c\\""'], [['a', 'b,c"']], escapechar='\\')
self._read_test(['a,"b,c"\\'], [['a', 'b,c\\']], escapechar='\\')
def test_read_quoting(self):
self._read_test(['1,",3,",5'], [['1', ',3,', '5']])
self._read_test(['1,",3,",5'], [['1', '"', '3', '"', '5']],
quotechar=None, escapechar='\\')
self._read_test(['1,",3,",5'], [['1', '"', '3', '"', '5']],
quoting=csv.QUOTE_NONE, escapechar='\\')
# will this fail where locale uses comma for decimals?
self._read_test([',3,"5",7.3, 9'], [['', 3, '5', 7.3, 9]],
quoting=csv.QUOTE_NONNUMERIC)
self._read_test(['"a\nb", 7'], [['a\nb', ' 7']])
self.assertRaises(ValueError, self._read_test,
['abc,3'], [[]],
quoting=csv.QUOTE_NONNUMERIC)
def test_read_bigfield(self):
# This exercises the buffer realloc functionality and field size
# limits.
limit = csv.field_size_limit()
try:
size = 50000
bigstring = 'X' * size
bigline = '%s,%s' % (bigstring, bigstring)
self._read_test([bigline], [[bigstring, bigstring]])
csv.field_size_limit(size)
self._read_test([bigline], [[bigstring, bigstring]])
self.assertEqual(csv.field_size_limit(), size)
csv.field_size_limit(size-1)
self.assertRaises(csv.Error, self._read_test, [bigline], [])
self.assertRaises(TypeError, csv.field_size_limit, None)
self.assertRaises(TypeError, csv.field_size_limit, 1, None)
finally:
csv.field_size_limit(limit)
def test_read_linenum(self):
r = csv.reader(['line,1', 'line,2', 'line,3'])
self.assertEqual(r.line_num, 0)
next(r)
self.assertEqual(r.line_num, 1)
next(r)
self.assertEqual(r.line_num, 2)
next(r)
self.assertEqual(r.line_num, 3)
self.assertRaises(StopIteration, next, r)
self.assertEqual(r.line_num, 3)
def test_roundtrip_quoteed_newlines(self):
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj)
self.assertRaises(TypeError, writer.writerows, None)
rows = [['a\nb','b'],['c','x\r\nd']]
writer.writerows(rows)
fileobj.seek(0)
for i, row in enumerate(csv.reader(fileobj)):
self.assertEqual(row, rows[i])
def test_roundtrip_escaped_unquoted_newlines(self):
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj,quoting=csv.QUOTE_NONE,escapechar="\\")
rows = [['a\nb','b'],['c','x\r\nd']]
writer.writerows(rows)
fileobj.seek(0)
for i, row in enumerate(csv.reader(fileobj,quoting=csv.QUOTE_NONE,escapechar="\\")):
self.assertEqual(row,rows[i])
class TestDialectRegistry(unittest.TestCase):
def test_registry_badargs(self):
self.assertRaises(TypeError, csv.list_dialects, None)
self.assertRaises(TypeError, csv.get_dialect)
self.assertRaises(csv.Error, csv.get_dialect, None)
self.assertRaises(csv.Error, csv.get_dialect, "nonesuch")
self.assertRaises(TypeError, csv.unregister_dialect)
self.assertRaises(csv.Error, csv.unregister_dialect, None)
self.assertRaises(csv.Error, csv.unregister_dialect, "nonesuch")
self.assertRaises(TypeError, csv.register_dialect, None)
self.assertRaises(TypeError, csv.register_dialect, None, None)
self.assertRaises(TypeError, csv.register_dialect, "nonesuch", 0, 0)
self.assertRaises(TypeError, csv.register_dialect, "nonesuch",
badargument=None)
self.assertRaises(TypeError, csv.register_dialect, "nonesuch",
quoting=None)
self.assertRaises(TypeError, csv.register_dialect, [])
def test_registry(self):
class myexceltsv(csv.excel):
delimiter = "\t"
name = "myexceltsv"
expected_dialects = csv.list_dialects() + [name]
expected_dialects.sort()
csv.register_dialect(name, myexceltsv)
self.addCleanup(csv.unregister_dialect, name)
self.assertEqual(csv.get_dialect(name).delimiter, '\t')
got_dialects = sorted(csv.list_dialects())
self.assertEqual(expected_dialects, got_dialects)
def test_register_kwargs(self):
name = 'fedcba'
csv.register_dialect(name, delimiter=';')
self.addCleanup(csv.unregister_dialect, name)
self.assertEqual(csv.get_dialect(name).delimiter, ';')
self.assertEqual([['X', 'Y', 'Z']], list(csv.reader(['X;Y;Z'], name)))
def test_incomplete_dialect(self):
class myexceltsv(csv.Dialect):
delimiter = "\t"
self.assertRaises(csv.Error, myexceltsv)
def test_space_dialect(self):
class space(csv.excel):
delimiter = " "
quoting = csv.QUOTE_NONE
escapechar = "\\"
with TemporaryFile("w+") as fileobj:
fileobj.write("abc def\nc1ccccc1 benzene\n")
fileobj.seek(0)
reader = csv.reader(fileobj, dialect=space())
self.assertEqual(next(reader), ["abc", "def"])
self.assertEqual(next(reader), ["c1ccccc1", "benzene"])
def compare_dialect_123(self, expected, *writeargs, **kwwriteargs):
with TemporaryFile("w+", newline='', encoding="utf-8") as fileobj:
writer = csv.writer(fileobj, *writeargs, **kwwriteargs)
writer.writerow([1,2,3])
fileobj.seek(0)
self.assertEqual(fileobj.read(), expected)
def test_dialect_apply(self):
class testA(csv.excel):
delimiter = "\t"
class testB(csv.excel):
delimiter = ":"
class testC(csv.excel):
delimiter = "|"
class testUni(csv.excel):
delimiter = "\u039B"
csv.register_dialect('testC', testC)
try:
self.compare_dialect_123("1,2,3\r\n")
self.compare_dialect_123("1\t2\t3\r\n", testA)
self.compare_dialect_123("1:2:3\r\n", dialect=testB())
self.compare_dialect_123("1|2|3\r\n", dialect='testC')
self.compare_dialect_123("1;2;3\r\n", dialect=testA,
delimiter=';')
self.compare_dialect_123("1\u039B2\u039B3\r\n",
dialect=testUni)
finally:
csv.unregister_dialect('testC')
def test_bad_dialect(self):
# Unknown parameter
self.assertRaises(TypeError, csv.reader, [], bad_attr = 0)
# Bad values
self.assertRaises(TypeError, csv.reader, [], delimiter = None)
self.assertRaises(TypeError, csv.reader, [], quoting = -1)
self.assertRaises(TypeError, csv.reader, [], quoting = 100)
def test_copy(self):
for name in csv.list_dialects():
dialect = csv.get_dialect(name)
self.assertRaises(TypeError, copy.copy, dialect)
def test_pickle(self):
for name in csv.list_dialects():
dialect = csv.get_dialect(name)
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
self.assertRaises(TypeError, pickle.dumps, dialect, proto)
class TestCsvBase(unittest.TestCase):
def readerAssertEqual(self, input, expected_result):
with TemporaryFile("w+", newline='') as fileobj:
fileobj.write(input)
fileobj.seek(0)
reader = csv.reader(fileobj, dialect = self.dialect)
fields = list(reader)
self.assertEqual(fields, expected_result)
def writerAssertEqual(self, input, expected_result):
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj, dialect = self.dialect)
writer.writerows(input)
fileobj.seek(0)
self.assertEqual(fileobj.read(), expected_result)
class TestDialectExcel(TestCsvBase):
dialect = 'excel'
def test_single(self):
self.readerAssertEqual('abc', [['abc']])
def test_simple(self):
self.readerAssertEqual('1,2,3,4,5', [['1','2','3','4','5']])
def test_blankline(self):
self.readerAssertEqual('', [])
def test_empty_fields(self):
self.readerAssertEqual(',', [['', '']])
def test_singlequoted(self):
self.readerAssertEqual('""', [['']])
def test_singlequoted_left_empty(self):
self.readerAssertEqual('"",', [['','']])
def test_singlequoted_right_empty(self):
self.readerAssertEqual(',""', [['','']])
def test_single_quoted_quote(self):
self.readerAssertEqual('""""', [['"']])
def test_quoted_quotes(self):
self.readerAssertEqual('""""""', [['""']])
def test_inline_quote(self):
self.readerAssertEqual('a""b', [['a""b']])
def test_inline_quotes(self):
self.readerAssertEqual('a"b"c', [['a"b"c']])
def test_quotes_and_more(self):
# Excel would never write a field containing '"a"b', but when
# reading one, it will return 'ab'.
self.readerAssertEqual('"a"b', [['ab']])
def test_lone_quote(self):
self.readerAssertEqual('a"b', [['a"b']])
def test_quote_and_quote(self):
# Excel would never write a field containing '"a" "b"', but when
# reading one, it will return 'a "b"'.
self.readerAssertEqual('"a" "b"', [['a "b"']])
def test_space_and_quote(self):
self.readerAssertEqual(' "a"', [[' "a"']])
def test_quoted(self):
self.readerAssertEqual('1,2,3,"I think, therefore I am",5,6',
[['1', '2', '3',
'I think, therefore I am',
'5', '6']])
def test_quoted_quote(self):
self.readerAssertEqual('1,2,3,"""I see,"" said the blind man","as he picked up his hammer and saw"',
[['1', '2', '3',
'"I see," said the blind man',
'as he picked up his hammer and saw']])
def test_quoted_nl(self):
input = '''\
1,2,3,"""I see,""
said the blind man","as he picked up his
hammer and saw"
9,8,7,6'''
self.readerAssertEqual(input,
[['1', '2', '3',
'"I see,"\nsaid the blind man',
'as he picked up his\nhammer and saw'],
['9','8','7','6']])
def test_dubious_quote(self):
self.readerAssertEqual('12,12,1",', [['12', '12', '1"', '']])
def test_null(self):
self.writerAssertEqual([], '')
def test_single_writer(self):
self.writerAssertEqual([['abc']], 'abc\r\n')
def test_simple_writer(self):
self.writerAssertEqual([[1, 2, 'abc', 3, 4]], '1,2,abc,3,4\r\n')
def test_quotes(self):
self.writerAssertEqual([[1, 2, 'a"bc"', 3, 4]], '1,2,"a""bc""",3,4\r\n')
def test_quote_fieldsep(self):
self.writerAssertEqual([['abc,def']], '"abc,def"\r\n')
def test_newlines(self):
self.writerAssertEqual([[1, 2, 'a\nbc', 3, 4]], '1,2,"a\nbc",3,4\r\n')
class EscapedExcel(csv.excel):
quoting = csv.QUOTE_NONE
escapechar = '\\'
class TestEscapedExcel(TestCsvBase):
dialect = EscapedExcel()
def test_escape_fieldsep(self):
self.writerAssertEqual([['abc,def']], 'abc\\,def\r\n')
def test_read_escape_fieldsep(self):
self.readerAssertEqual('abc\\,def\r\n', [['abc,def']])
class TestDialectUnix(TestCsvBase):
dialect = 'unix'
def test_simple_writer(self):
self.writerAssertEqual([[1, 'abc def', 'abc']], '"1","abc def","abc"\n')
def test_simple_reader(self):
self.readerAssertEqual('"1","abc def","abc"\n', [['1', 'abc def', 'abc']])
class QuotedEscapedExcel(csv.excel):
quoting = csv.QUOTE_NONNUMERIC
escapechar = '\\'
class TestQuotedEscapedExcel(TestCsvBase):
dialect = QuotedEscapedExcel()
def test_write_escape_fieldsep(self):
self.writerAssertEqual([['abc,def']], '"abc,def"\r\n')
def test_read_escape_fieldsep(self):
self.readerAssertEqual('"abc\\,def"\r\n', [['abc,def']])
class TestDictFields(unittest.TestCase):
### "long" means the row is longer than the number of fieldnames
### "short" means there are fewer elements in the row than fieldnames
def test_write_simple_dict(self):
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.DictWriter(fileobj, fieldnames = ["f1", "f2", "f3"])
writer.writeheader()
fileobj.seek(0)
self.assertEqual(fileobj.readline(), "f1,f2,f3\r\n")
writer.writerow({"f1": 10, "f3": "abc"})
fileobj.seek(0)
fileobj.readline() # header
self.assertEqual(fileobj.read(), "10,,abc\r\n")
def test_write_multiple_dict_rows(self):
fileobj = StringIO()
writer = csv.DictWriter(fileobj, fieldnames=["f1", "f2", "f3"])
writer.writeheader()
self.assertEqual(fileobj.getvalue(), "f1,f2,f3\r\n")
writer.writerows([{"f1": 1, "f2": "abc", "f3": "f"},
{"f1": 2, "f2": 5, "f3": "xyz"}])
self.assertEqual(fileobj.getvalue(),
"f1,f2,f3\r\n1,abc,f\r\n2,5,xyz\r\n")
def test_write_no_fields(self):
fileobj = StringIO()
self.assertRaises(TypeError, csv.DictWriter, fileobj)
def test_write_fields_not_in_fieldnames(self):
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.DictWriter(fileobj, fieldnames = ["f1", "f2", "f3"])
# Of special note is the non-string key (issue 19449)
with self.assertRaises(ValueError) as cx:
writer.writerow({"f4": 10, "f2": "spam", 1: "abc"})
exception = str(cx.exception)
self.assertIn("fieldnames", exception)
self.assertIn("'f4'", exception)
self.assertNotIn("'f2'", exception)
self.assertIn("1", exception)
def test_typo_in_extrasaction_raises_error(self):
fileobj = StringIO()
self.assertRaises(ValueError, csv.DictWriter, fileobj, ['f1', 'f2'],
extrasaction="raised")
def test_write_field_not_in_field_names_raise(self):
fileobj = StringIO()
writer = csv.DictWriter(fileobj, ['f1', 'f2'], extrasaction="raise")
dictrow = {'f0': 0, 'f1': 1, 'f2': 2, 'f3': 3}
self.assertRaises(ValueError, csv.DictWriter.writerow, writer, dictrow)
def test_write_field_not_in_field_names_ignore(self):
fileobj = StringIO()
writer = csv.DictWriter(fileobj, ['f1', 'f2'], extrasaction="ignore")
dictrow = {'f0': 0, 'f1': 1, 'f2': 2, 'f3': 3}
csv.DictWriter.writerow(writer, dictrow)
self.assertEqual(fileobj.getvalue(), "1,2\r\n")
def test_read_dict_fields(self):
with TemporaryFile("w+") as fileobj:
fileobj.write("1,2,abc\r\n")
fileobj.seek(0)
reader = csv.DictReader(fileobj,
fieldnames=["f1", "f2", "f3"])
self.assertEqual(next(reader), {"f1": '1', "f2": '2', "f3": 'abc'})
def test_read_dict_no_fieldnames(self):
with TemporaryFile("w+") as fileobj:
fileobj.write("f1,f2,f3\r\n1,2,abc\r\n")
fileobj.seek(0)
reader = csv.DictReader(fileobj)
self.assertEqual(next(reader), {"f1": '1', "f2": '2', "f3": 'abc'})
self.assertEqual(reader.fieldnames, ["f1", "f2", "f3"])
# Two test cases to make sure existing ways of implicitly setting
# fieldnames continue to work. Both arise from discussion in issue3436.
def test_read_dict_fieldnames_from_file(self):
with TemporaryFile("w+") as fileobj:
fileobj.write("f1,f2,f3\r\n1,2,abc\r\n")
fileobj.seek(0)
reader = csv.DictReader(fileobj,
fieldnames=next(csv.reader(fileobj)))
self.assertEqual(reader.fieldnames, ["f1", "f2", "f3"])
self.assertEqual(next(reader), {"f1": '1', "f2": '2', "f3": 'abc'})
def test_read_dict_fieldnames_chain(self):
import itertools
with TemporaryFile("w+") as fileobj:
fileobj.write("f1,f2,f3\r\n1,2,abc\r\n")
fileobj.seek(0)
reader = csv.DictReader(fileobj)
first = next(reader)
for row in itertools.chain([first], reader):
self.assertEqual(reader.fieldnames, ["f1", "f2", "f3"])
self.assertEqual(row, {"f1": '1', "f2": '2', "f3": 'abc'})
def test_read_long(self):
with TemporaryFile("w+") as fileobj:
fileobj.write("1,2,abc,4,5,6\r\n")
fileobj.seek(0)
reader = csv.DictReader(fileobj,
fieldnames=["f1", "f2"])
self.assertEqual(next(reader), {"f1": '1', "f2": '2',
None: ["abc", "4", "5", "6"]})
def test_read_long_with_rest(self):
with TemporaryFile("w+") as fileobj:
fileobj.write("1,2,abc,4,5,6\r\n")
fileobj.seek(0)
reader = csv.DictReader(fileobj,
fieldnames=["f1", "f2"], restkey="_rest")
self.assertEqual(next(reader), {"f1": '1', "f2": '2',
"_rest": ["abc", "4", "5", "6"]})
def test_read_long_with_rest_no_fieldnames(self):
with TemporaryFile("w+") as fileobj:
fileobj.write("f1,f2\r\n1,2,abc,4,5,6\r\n")
fileobj.seek(0)
reader = csv.DictReader(fileobj, restkey="_rest")
self.assertEqual(reader.fieldnames, ["f1", "f2"])
self.assertEqual(next(reader), {"f1": '1', "f2": '2',
"_rest": ["abc", "4", "5", "6"]})
def test_read_short(self):
with TemporaryFile("w+") as fileobj:
fileobj.write("1,2,abc,4,5,6\r\n1,2,abc\r\n")
fileobj.seek(0)
reader = csv.DictReader(fileobj,
fieldnames="1 2 3 4 5 6".split(),
restval="DEFAULT")
self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc',
"4": '4', "5": '5', "6": '6'})
self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc',
"4": 'DEFAULT', "5": 'DEFAULT',
"6": 'DEFAULT'})
def test_read_multi(self):
sample = [
'2147483648,43.0e12,17,abc,def\r\n',
'147483648,43.0e2,17,abc,def\r\n',
'47483648,43.0,170,abc,def\r\n'
]
reader = csv.DictReader(sample,
fieldnames="i1 float i2 s1 s2".split())
self.assertEqual(next(reader), {"i1": '2147483648',
"float": '43.0e12',
"i2": '17',
"s1": 'abc',
"s2": 'def'})
def test_read_with_blanks(self):
reader = csv.DictReader(["1,2,abc,4,5,6\r\n","\r\n",
"1,2,abc,4,5,6\r\n"],
fieldnames="1 2 3 4 5 6".split())
self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc',
"4": '4', "5": '5', "6": '6'})
self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc',
"4": '4', "5": '5', "6": '6'})
def test_read_semi_sep(self):
reader = csv.DictReader(["1;2;abc;4;5;6\r\n"],
fieldnames="1 2 3 4 5 6".split(),
delimiter=';')
self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc',
"4": '4', "5": '5', "6": '6'})
class TestArrayWrites(unittest.TestCase):
def test_int_write(self):
import array
contents = [(20-i) for i in range(20)]
a = array.array('i', contents)
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj, dialect="excel")
writer.writerow(a)
expected = ",".join([str(i) for i in a])+"\r\n"
fileobj.seek(0)
self.assertEqual(fileobj.read(), expected)
def test_double_write(self):
import array
contents = [(20-i)*0.1 for i in range(20)]
a = array.array('d', contents)
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj, dialect="excel")
writer.writerow(a)
expected = ",".join([str(i) for i in a])+"\r\n"
fileobj.seek(0)
self.assertEqual(fileobj.read(), expected)
def test_float_write(self):
import array
contents = [(20-i)*0.1 for i in range(20)]
a = array.array('f', contents)
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj, dialect="excel")
writer.writerow(a)
expected = ",".join([str(i) for i in a])+"\r\n"
fileobj.seek(0)
self.assertEqual(fileobj.read(), expected)
def test_char_write(self):
import array, string
a = array.array('u', string.ascii_letters)
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj, dialect="excel")
writer.writerow(a)
expected = ",".join(a)+"\r\n"
fileobj.seek(0)
self.assertEqual(fileobj.read(), expected)
class TestDialectValidity(unittest.TestCase):
def test_quoting(self):
class mydialect(csv.Dialect):
delimiter = ";"
escapechar = '\\'
doublequote = False
skipinitialspace = True
lineterminator = '\r\n'
quoting = csv.QUOTE_NONE
d = mydialect()
self.assertEqual(d.quoting, csv.QUOTE_NONE)
mydialect.quoting = None
self.assertRaises(csv.Error, mydialect)
mydialect.doublequote = True
mydialect.quoting = csv.QUOTE_ALL
mydialect.quotechar = '"'
d = mydialect()
self.assertEqual(d.quoting, csv.QUOTE_ALL)
self.assertEqual(d.quotechar, '"')
self.assertTrue(d.doublequote)
mydialect.quotechar = "''"
with self.assertRaises(csv.Error) as cm:
mydialect()
self.assertEqual(str(cm.exception),
'"quotechar" must be a 1-character string')
mydialect.quotechar = 4
with self.assertRaises(csv.Error) as cm:
mydialect()
self.assertEqual(str(cm.exception),
'"quotechar" must be string, not int')
def test_delimiter(self):
class mydialect(csv.Dialect):
delimiter = ";"
escapechar = '\\'
doublequote = False
skipinitialspace = True
lineterminator = '\r\n'
quoting = csv.QUOTE_NONE
d = mydialect()
self.assertEqual(d.delimiter, ";")
mydialect.delimiter = ":::"
with self.assertRaises(csv.Error) as cm:
mydialect()
self.assertEqual(str(cm.exception),
'"delimiter" must be a 1-character string')
mydialect.delimiter = ""
with self.assertRaises(csv.Error) as cm:
mydialect()
self.assertEqual(str(cm.exception),
'"delimiter" must be a 1-character string')
mydialect.delimiter = b","
with self.assertRaises(csv.Error) as cm:
mydialect()
self.assertEqual(str(cm.exception),
'"delimiter" must be string, not bytes')
mydialect.delimiter = 4
with self.assertRaises(csv.Error) as cm:
mydialect()
self.assertEqual(str(cm.exception),
'"delimiter" must be string, not int')
def test_lineterminator(self):
class mydialect(csv.Dialect):
delimiter = ";"
escapechar = '\\'
doublequote = False
skipinitialspace = True
lineterminator = '\r\n'
quoting = csv.QUOTE_NONE
d = mydialect()
self.assertEqual(d.lineterminator, '\r\n')
mydialect.lineterminator = ":::"
d = mydialect()
self.assertEqual(d.lineterminator, ":::")
mydialect.lineterminator = 4
with self.assertRaises(csv.Error) as cm:
mydialect()
self.assertEqual(str(cm.exception),
'"lineterminator" must be a string')
def test_invalid_chars(self):
def create_invalid(field_name, value):
class mydialect(csv.Dialect):
pass
setattr(mydialect, field_name, value)
d = mydialect()
for field_name in ("delimiter", "escapechar", "quotechar"):
with self.subTest(field_name=field_name):
self.assertRaises(csv.Error, create_invalid, field_name, "")
self.assertRaises(csv.Error, create_invalid, field_name, "abc")
self.assertRaises(csv.Error, create_invalid, field_name, b'x')
self.assertRaises(csv.Error, create_invalid, field_name, 5)
class TestSniffer(unittest.TestCase):
sample1 = """\
Harry's, Arlington Heights, IL, 2/1/03, Kimi Hayes
Shark City, Glendale Heights, IL, 12/28/02, Prezence
Tommy's Place, Blue Island, IL, 12/28/02, Blue Sunday/White Crow
Stonecutters Seafood and Chop House, Lemont, IL, 12/19/02, Week Back
"""
sample2 = """\
'Harry''s':'Arlington Heights':'IL':'2/1/03':'Kimi Hayes'
'Shark City':'Glendale Heights':'IL':'12/28/02':'Prezence'
'Tommy''s Place':'Blue Island':'IL':'12/28/02':'Blue Sunday/White Crow'
'Stonecutters ''Seafood'' and Chop House':'Lemont':'IL':'12/19/02':'Week Back'
"""
header1 = '''\
"venue","city","state","date","performers"
'''
sample3 = '''\
05/05/03?05/05/03?05/05/03?05/05/03?05/05/03?05/05/03
05/05/03?05/05/03?05/05/03?05/05/03?05/05/03?05/05/03
05/05/03?05/05/03?05/05/03?05/05/03?05/05/03?05/05/03
'''
sample4 = '''\
2147483648;43.0e12;17;abc;def
147483648;43.0e2;17;abc;def
47483648;43.0;170;abc;def
'''
sample5 = "aaa\tbbb\r\nAAA\t\r\nBBB\t\r\n"
sample6 = "a|b|c\r\nd|e|f\r\n"
sample7 = "'a'|'b'|'c'\r\n'd'|e|f\r\n"
# Issue 18155: Use a delimiter that is a special char to regex:
header2 = '''\
"venue"+"city"+"state"+"date"+"performers"
'''
sample8 = """\
Harry's+ Arlington Heights+ IL+ 2/1/03+ Kimi Hayes
Shark City+ Glendale Heights+ IL+ 12/28/02+ Prezence
Tommy's Place+ Blue Island+ IL+ 12/28/02+ Blue Sunday/White Crow
Stonecutters Seafood and Chop House+ Lemont+ IL+ 12/19/02+ Week Back
"""
sample9 = """\
'Harry''s'+ Arlington Heights'+ 'IL'+ '2/1/03'+ 'Kimi Hayes'
'Shark City'+ Glendale Heights'+' IL'+ '12/28/02'+ 'Prezence'
'Tommy''s Place'+ Blue Island'+ 'IL'+ '12/28/02'+ 'Blue Sunday/White Crow'
'Stonecutters ''Seafood'' and Chop House'+ 'Lemont'+ 'IL'+ '12/19/02'+ 'Week Back'
"""
def test_has_header(self):
sniffer = csv.Sniffer()
self.assertEqual(sniffer.has_header(self.sample1), False)
self.assertEqual(sniffer.has_header(self.header1 + self.sample1),
True)
def test_has_header_regex_special_delimiter(self):
sniffer = csv.Sniffer()
self.assertEqual(sniffer.has_header(self.sample8), False)
self.assertEqual(sniffer.has_header(self.header2 + self.sample8),
True)
def test_guess_quote_and_delimiter(self):
sniffer = csv.Sniffer()
for header in (";'123;4';", "'123;4';", ";'123;4'", "'123;4'"):
with self.subTest(header):
dialect = sniffer.sniff(header, ",;")
self.assertEqual(dialect.delimiter, ';')
self.assertEqual(dialect.quotechar, "'")
self.assertIs(dialect.doublequote, False)
self.assertIs(dialect.skipinitialspace, False)
def test_sniff(self):
sniffer = csv.Sniffer()
dialect = sniffer.sniff(self.sample1)
self.assertEqual(dialect.delimiter, ",")
self.assertEqual(dialect.quotechar, '"')
self.assertEqual(dialect.skipinitialspace, True)
dialect = sniffer.sniff(self.sample2)
self.assertEqual(dialect.delimiter, ":")
self.assertEqual(dialect.quotechar, "'")
self.assertEqual(dialect.skipinitialspace, False)
def test_delimiters(self):
sniffer = csv.Sniffer()
dialect = sniffer.sniff(self.sample3)
# given that all three lines in sample3 are equal,
# I think that any character could have been 'guessed' as the
# delimiter, depending on dictionary order
self.assertIn(dialect.delimiter, self.sample3)
dialect = sniffer.sniff(self.sample3, delimiters="?,")
self.assertEqual(dialect.delimiter, "?")
dialect = sniffer.sniff(self.sample3, delimiters="/,")
self.assertEqual(dialect.delimiter, "/")
dialect = sniffer.sniff(self.sample4)
self.assertEqual(dialect.delimiter, ";")
dialect = sniffer.sniff(self.sample5)
self.assertEqual(dialect.delimiter, "\t")
dialect = sniffer.sniff(self.sample6)
self.assertEqual(dialect.delimiter, "|")
dialect = sniffer.sniff(self.sample7)
self.assertEqual(dialect.delimiter, "|")
self.assertEqual(dialect.quotechar, "'")
dialect = sniffer.sniff(self.sample8)
self.assertEqual(dialect.delimiter, '+')
dialect = sniffer.sniff(self.sample9)
self.assertEqual(dialect.delimiter, '+')
self.assertEqual(dialect.quotechar, "'")
def test_doublequote(self):
sniffer = csv.Sniffer()
dialect = sniffer.sniff(self.header1)
self.assertFalse(dialect.doublequote)
dialect = sniffer.sniff(self.header2)
self.assertFalse(dialect.doublequote)
dialect = sniffer.sniff(self.sample2)
self.assertTrue(dialect.doublequote)
dialect = sniffer.sniff(self.sample8)
self.assertFalse(dialect.doublequote)
dialect = sniffer.sniff(self.sample9)
self.assertTrue(dialect.doublequote)
class NUL:
def write(s, *args):
pass
writelines = write
@unittest.skipUnless(hasattr(sys, "gettotalrefcount"),
'requires sys.gettotalrefcount()')
class TestLeaks(unittest.TestCase):
def test_create_read(self):
delta = 0
lastrc = sys.gettotalrefcount()
for i in range(20):
gc.collect()
self.assertEqual(gc.garbage, [])
rc = sys.gettotalrefcount()
csv.reader(["a,b,c\r\n"])
csv.reader(["a,b,c\r\n"])
csv.reader(["a,b,c\r\n"])
delta = rc-lastrc
lastrc = rc
# if csv.reader() leaks, last delta should be 3 or more
self.assertEqual(delta < 3, True)
def test_create_write(self):
delta = 0
lastrc = sys.gettotalrefcount()
s = NUL()
for i in range(20):
gc.collect()
self.assertEqual(gc.garbage, [])
rc = sys.gettotalrefcount()
csv.writer(s)
csv.writer(s)
csv.writer(s)
delta = rc-lastrc
lastrc = rc
# if csv.writer() leaks, last delta should be 3 or more
self.assertEqual(delta < 3, True)
def test_read(self):
delta = 0
rows = ["a,b,c\r\n"]*5
lastrc = sys.gettotalrefcount()
for i in range(20):
gc.collect()
self.assertEqual(gc.garbage, [])
rc = sys.gettotalrefcount()
rdr = csv.reader(rows)
for row in rdr:
pass
delta = rc-lastrc
lastrc = rc
# if reader leaks during read, delta should be 5 or more
self.assertEqual(delta < 5, True)
def test_write(self):
delta = 0
rows = [[1,2,3]]*5
s = NUL()
lastrc = sys.gettotalrefcount()
for i in range(20):
gc.collect()
self.assertEqual(gc.garbage, [])
rc = sys.gettotalrefcount()
writer = csv.writer(s)
for row in rows:
writer.writerow(row)
delta = rc-lastrc
lastrc = rc
# if writer leaks during write, last delta should be 5 or more
self.assertEqual(delta < 5, True)
class TestUnicode(unittest.TestCase):
names = ["Martin von Löwis",
"Marc André Lemburg",
"Guido van Rossum",
"François Pinard"]
def test_unicode_read(self):
with TemporaryFile("w+", newline='', encoding="utf-8") as fileobj:
fileobj.write(",".join(self.names) + "\r\n")
fileobj.seek(0)
reader = csv.reader(fileobj)
self.assertEqual(list(reader), [self.names])
def test_unicode_write(self):
with TemporaryFile("w+", newline='', encoding="utf-8") as fileobj:
writer = csv.writer(fileobj)
writer.writerow(self.names)
expected = ",".join(self.names)+"\r\n"
fileobj.seek(0)
self.assertEqual(fileobj.read(), expected)
class KeyOrderingTest(unittest.TestCase):
def test_ordering_for_the_dict_reader_and_writer(self):
resultset = set()
for keys in permutations("abcde"):
with TemporaryFile('w+', newline='', encoding="utf-8") as fileobject:
dw = csv.DictWriter(fileobject, keys)
dw.writeheader()
fileobject.seek(0)
dr = csv.DictReader(fileobject)
kt = tuple(dr.fieldnames)
self.assertEqual(keys, kt)
resultset.add(kt)
# Final sanity check: were all permutations unique?
self.assertEqual(len(resultset), 120, "Key ordering: some key permutations not collected (expected 120)")
def test_ordered_dict_reader(self):
data = dedent('''\
FirstName,LastName
Eric,Idle
Graham,Chapman,Over1,Over2
Under1
John,Cleese
''').splitlines()
self.assertEqual(list(csv.DictReader(data)),
[OrderedDict([('FirstName', 'Eric'), ('LastName', 'Idle')]),
OrderedDict([('FirstName', 'Graham'), ('LastName', 'Chapman'),
(None, ['Over1', 'Over2'])]),
OrderedDict([('FirstName', 'Under1'), ('LastName', None)]),
OrderedDict([('FirstName', 'John'), ('LastName', 'Cleese')]),
])
self.assertEqual(list(csv.DictReader(data, restkey='OtherInfo')),
[OrderedDict([('FirstName', 'Eric'), ('LastName', 'Idle')]),
OrderedDict([('FirstName', 'Graham'), ('LastName', 'Chapman'),
('OtherInfo', ['Over1', 'Over2'])]),
OrderedDict([('FirstName', 'Under1'), ('LastName', None)]),
OrderedDict([('FirstName', 'John'), ('LastName', 'Cleese')]),
])
del data[0] # Remove the header row
self.assertEqual(list(csv.DictReader(data, fieldnames=['fname', 'lname'])),
[OrderedDict([('fname', 'Eric'), ('lname', 'Idle')]),
OrderedDict([('fname', 'Graham'), ('lname', 'Chapman'),
(None, ['Over1', 'Over2'])]),
OrderedDict([('fname', 'Under1'), ('lname', None)]),
OrderedDict([('fname', 'John'), ('lname', 'Cleese')]),
])
class MiscTestCase(unittest.TestCase):
def test__all__(self):
extra = {'__doc__', '__version__'}
support.check__all__(self, csv, ('csv', '_csv'), extra=extra)
if __name__ == '__main__':
unittest.main()
| 48,189 | 1,205 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/pythoninfo.py | """
Collect various information about Python to help debugging test failures.
"""
from __future__ import print_function
import errno
import re
import sys
import traceback
if __name__ == 'PYOBJ.COM':
import resource
def normalize_text(text):
if text is None:
return None
text = str(text)
text = re.sub(r'\s+', ' ', text)
return text.strip()
class PythonInfo:
def __init__(self):
self.info = {}
def add(self, key, value):
if key in self.info:
raise ValueError("duplicate key: %r" % key)
if value is None:
return
if not isinstance(value, int):
if not isinstance(value, str):
# convert other objects like sys.flags to string
value = str(value)
value = value.strip()
if not value:
return
self.info[key] = value
def get_infos(self):
"""
Get information as a key:value dictionary where values are strings.
"""
return {key: str(value) for key, value in self.info.items()}
def copy_attributes(info_add, obj, name_fmt, attributes, *, formatter=None):
for attr in attributes:
value = getattr(obj, attr, None)
if value is None:
continue
name = name_fmt % attr
if formatter is not None:
value = formatter(attr, value)
info_add(name, value)
def copy_attr(info_add, name, mod, attr_name):
try:
value = getattr(mod, attr_name)
except AttributeError:
return
info_add(name, value)
def call_func(info_add, name, mod, func_name, *, formatter=None):
try:
func = getattr(mod, func_name)
except AttributeError:
return
value = func()
if formatter is not None:
value = formatter(value)
info_add(name, value)
def collect_sys(info_add):
attributes = (
'_framework',
'abiflags',
'api_version',
'builtin_module_names',
'byteorder',
'dont_write_bytecode',
'executable',
'flags',
'float_info',
'float_repr_style',
'hash_info',
'hexversion',
'implementation',
'int_info',
'maxsize',
'maxunicode',
'path',
'platform',
'prefix',
'thread_info',
'version',
'version_info',
'winver',
)
copy_attributes(info_add, sys, 'sys.%s', attributes)
call_func(info_add, 'sys.androidapilevel', sys, 'getandroidapilevel')
call_func(info_add, 'sys.windowsversion', sys, 'getwindowsversion')
encoding = sys.getfilesystemencoding()
if hasattr(sys, 'getfilesystemencodeerrors'):
encoding = '%s/%s' % (encoding, sys.getfilesystemencodeerrors())
info_add('sys.filesystem_encoding', encoding)
for name in ('stdin', 'stdout', 'stderr'):
stream = getattr(sys, name)
if stream is None:
continue
encoding = getattr(stream, 'encoding', None)
if not encoding:
continue
errors = getattr(stream, 'errors', None)
if errors:
encoding = '%s/%s' % (encoding, errors)
info_add('sys.%s.encoding' % name, encoding)
# Were we compiled --with-pydebug or with #define Py_DEBUG?
Py_DEBUG = hasattr(sys, 'gettotalrefcount')
if Py_DEBUG:
text = 'Yes (sys.gettotalrefcount() present)'
else:
text = 'No (sys.gettotalrefcount() missing)'
info_add('Py_DEBUG', text)
def collect_platform(info_add):
import platform
arch = platform.architecture()
arch = ' '.join(filter(bool, arch))
info_add('platform.architecture', arch)
info_add('platform.python_implementation',
platform.python_implementation())
info_add('platform.platform',
platform.platform(aliased=True, terse=True))
def collect_locale(info_add):
import locale
info_add('locale.encoding', locale.getpreferredencoding(False))
def collect_builtins(info_add):
info_add('builtins.float.float_format', float.__getformat__("float"))
info_add('builtins.float.double_format', float.__getformat__("double"))
def collect_os(info_add):
import os
def format_attr(attr, value):
if attr in ('supports_follow_symlinks', 'supports_fd',
'supports_effective_ids'):
return str(sorted(func.__name__ for func in value))
else:
return value
attributes = (
'name',
'supports_bytes_environ',
'supports_effective_ids',
'supports_fd',
'supports_follow_symlinks',
)
copy_attributes(info_add, os, 'os.%s', attributes, formatter=format_attr)
call_func(info_add, 'os.cwd', os, 'getcwd')
call_func(info_add, 'os.uid', os, 'getuid')
call_func(info_add, 'os.gid', os, 'getgid')
call_func(info_add, 'os.uname', os, 'uname')
def format_groups(groups):
return ', '.join(map(str, groups))
call_func(info_add, 'os.groups', os, 'getgroups', formatter=format_groups)
if hasattr(os, 'getlogin'):
try:
login = os.getlogin()
except OSError:
# getlogin() fails with "OSError: [Errno 25] Inappropriate ioctl
# for device" on Travis CI
pass
else:
info_add("os.login", login)
call_func(info_add, 'os.cpu_count', os, 'cpu_count')
call_func(info_add, 'os.loadavg', os, 'getloadavg')
# Environment variables used by the stdlib and tests. Don't log the full
# environment: filter to list to not leak sensitive information.
#
# HTTP_PROXY is not logged because it can contain a password.
ENV_VARS = frozenset((
"APPDATA",
"AR",
"ARCHFLAGS",
"ARFLAGS",
"AUDIODEV",
"CC",
"CFLAGS",
"COLUMNS",
"COMPUTERNAME",
"COMSPEC",
"CPP",
"CPPFLAGS",
"DISPLAY",
"DISTUTILS_DEBUG",
"DISTUTILS_USE_SDK",
"DYLD_LIBRARY_PATH",
"ENSUREPIP_OPTIONS",
"HISTORY_FILE",
"HOME",
"HOMEDRIVE",
"HOMEPATH",
"IDLESTARTUP",
"LANG",
"LDFLAGS",
"LDSHARED",
"LD_LIBRARY_PATH",
"LINES",
"MACOSX_DEPLOYMENT_TARGET",
"MAILCAPS",
"MAKEFLAGS",
"MIXERDEV",
"MSSDK",
"PATH",
"PATHEXT",
"PIP_CONFIG_FILE",
"PLAT",
"POSIXLY_CORRECT",
"PY_SAX_PARSER",
"ProgramFiles",
"ProgramFiles(x86)",
"RUNNING_ON_VALGRIND",
"SDK_TOOLS_BIN",
"SERVER_SOFTWARE",
"SHELL",
"SOURCE_DATE_EPOCH",
"SYSTEMROOT",
"TEMP",
"TERM",
"TILE_LIBRARY",
"TIX_LIBRARY",
"TMP",
"TMPDIR",
"TRAVIS",
"TZ",
"USERPROFILE",
"VIRTUAL_ENV",
"WAYLAND_DISPLAY",
"WINDIR",
"_PYTHON_HOST_PLATFORM",
"_PYTHON_PROJECT_BASE",
"_PYTHON_SYSCONFIGDATA_NAME",
"__PYVENV_LAUNCHER__",
))
for name, value in os.environ.items():
uname = name.upper()
if (uname in ENV_VARS
# Copy PYTHON* and LC_* variables
or uname.startswith(("PYTHON", "LC_"))
# Visual Studio: VS140COMNTOOLS
or (uname.startswith("VS") and uname.endswith("COMNTOOLS"))):
info_add('os.environ[%s]' % name, value)
if hasattr(os, 'umask'):
mask = os.umask(0)
os.umask(mask)
info_add("os.umask", '%03o' % mask)
if hasattr(os, 'getrandom'):
# PEP 524: Check if system urandom is initialized
try:
try:
os.getrandom(1, os.GRND_NONBLOCK)
state = 'ready (initialized)'
except BlockingIOError as exc:
state = 'not seeded yet (%s)' % exc
info_add('os.getrandom', state)
except OSError as exc:
# Python was compiled on a more recent Linux version
# than the current Linux kernel: ignore OSError(ENOSYS)
if exc.errno != errno.ENOSYS:
raise
def collect_readline(info_add):
try:
import readline
except ImportError:
return
def format_attr(attr, value):
if isinstance(value, int):
return "%#x" % value
else:
return value
attributes = (
"_READLINE_VERSION",
"_READLINE_RUNTIME_VERSION",
"_READLINE_LIBRARY_VERSION",
)
copy_attributes(info_add, readline, 'readline.%s', attributes,
formatter=format_attr)
if not hasattr(readline, "_READLINE_LIBRARY_VERSION"):
# _READLINE_LIBRARY_VERSION has been added to CPython 3.7
doc = getattr(readline, '__doc__', '')
if 'libedit readline' in doc:
info_add('readline.library', 'libedit readline')
elif 'GNU readline' in doc:
info_add('readline.library', 'GNU readline')
def collect_gdb(info_add):
import subprocess
try:
proc = subprocess.Popen(["gdb", "-nx", "--version"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
version = proc.communicate()[0]
except OSError:
return
# Only keep the first line
version = version.splitlines()[0]
info_add('gdb_version', version)
def collect_tkinter(info_add):
try:
import _tkinter
except ImportError:
pass
else:
attributes = ('TK_VERSION', 'TCL_VERSION')
copy_attributes(info_add, _tkinter, 'tkinter.%s', attributes)
try:
import tkinter
except ImportError:
pass
else:
tcl = tkinter.Tcl()
patchlevel = tcl.call('info', 'patchlevel')
info_add('tkinter.info_patchlevel', patchlevel)
def collect_time(info_add):
import time
info_add('time.time', time.time())
attributes = (
'altzone',
'daylight',
'timezone',
'tzname',
)
copy_attributes(info_add, time, 'time.%s', attributes)
if hasattr(time, 'get_clock_info'):
for clock in ('time', 'perf_counter'):
tinfo = time.get_clock_info(clock)
info_add('time.get_clock_info(%s)' % clock, tinfo)
def collect_datetime(info_add):
try:
import datetime
except ImportError:
return
info_add('datetime.datetime.now', datetime.datetime.now())
def collect_sysconfig(info_add):
import sysconfig
for name in (
'ABIFLAGS',
'ANDROID_API_LEVEL',
'CC',
'CCSHARED',
'CFLAGS',
'CFLAGSFORSHARED',
'CONFIG_ARGS',
'HOST_GNU_TYPE',
'MACHDEP',
'MULTIARCH',
'OPT',
'PY_CFLAGS',
'PY_CFLAGS_NODIST',
'PY_CORE_LDFLAGS',
'PY_LDFLAGS',
'PY_LDFLAGS_NODIST',
'Py_DEBUG',
'Py_ENABLE_SHARED',
'SHELL',
'SOABI',
'prefix',
):
value = sysconfig.get_config_var(name)
if name == 'ANDROID_API_LEVEL' and not value:
# skip ANDROID_API_LEVEL=0
continue
value = normalize_text(value)
info_add('sysconfig[%s]' % name, value)
def collect_ssl(info_add):
try:
import ssl
except ImportError:
return
def format_attr(attr, value):
if attr.startswith('OP_'):
return '%#8x' % value
else:
return value
attributes = (
'OPENSSL_VERSION',
'OPENSSL_VERSION_INFO',
'HAS_SNI',
'OP_ALL',
'OP_NO_TLSv1_1',
)
copy_attributes(info_add, ssl, 'ssl.%s', attributes, formatter=format_attr)
def collect_socket(info_add):
import socket
hostname = socket.gethostname()
info_add('socket.hostname', hostname)
def collect_sqlite(info_add):
try:
import sqlite3
except ImportError:
return
attributes = ('version', 'sqlite_version')
copy_attributes(info_add, sqlite3, 'sqlite3.%s', attributes)
def collect_zlib(info_add):
try:
import zlib
except ImportError:
return
attributes = ('ZLIB_VERSION', 'ZLIB_RUNTIME_VERSION')
copy_attributes(info_add, zlib, 'zlib.%s', attributes)
def collect_expat(info_add):
try:
from xml.parsers import expat
except ImportError:
return
attributes = ('EXPAT_VERSION',)
copy_attributes(info_add, expat, 'expat.%s', attributes)
def collect_decimal(info_add):
try:
import _decimal
except ImportError:
return
attributes = ('__libmpdec_version__',)
copy_attributes(info_add, _decimal, '_decimal.%s', attributes)
def collect_testcapi(info_add):
try:
import _testcapi
except ImportError:
return
call_func(info_add, 'pymem.allocator', _testcapi, 'pymem_getallocatorsname')
copy_attr(info_add, 'pymem.with_pymalloc', _testcapi, 'WITH_PYMALLOC')
def collect_resource(info_add):
try:
import resource
except ImportError:
return
limits = [attr for attr in dir(resource) if attr.startswith('RLIMIT_')]
for name in limits:
key = getattr(resource, name)
value = resource.getrlimit(key)
info_add('resource.%s' % name, value)
def collect_test_socket(info_add):
try:
from test import test_socket
except ImportError:
return
# all check attributes like HAVE_SOCKET_CAN
attributes = [name for name in dir(test_socket)
if name.startswith('HAVE_')]
copy_attributes(info_add, test_socket, 'test_socket.%s', attributes)
def collect_test_support(info_add):
try:
from test import support
except ImportError:
return
attributes = ('IPV6_ENABLED',)
copy_attributes(info_add, support, 'test_support.%s', attributes)
call_func(info_add, 'test_support._is_gui_available', support, '_is_gui_available')
call_func(info_add, 'test_support.python_is_optimized', support, 'python_is_optimized')
def collect_cc(info_add):
import subprocess
import sysconfig
CC = sysconfig.get_config_var('CC')
if not CC:
return
try:
import shlex
args = shlex.split(CC)
except ImportError:
args = CC.split()
args.append('--version')
proc = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True)
stdout = proc.communicate()[0]
if proc.returncode:
# CC --version failed: ignore error
return
text = stdout.splitlines()[0]
text = normalize_text(text)
info_add('CC.version', text)
def collect_info(info):
error = False
info_add = info.add
for collect_func in (
# collect_os() should be the first, to check the getrandom() status
collect_os,
collect_builtins,
collect_gdb,
collect_locale,
collect_platform,
collect_readline,
collect_socket,
collect_sqlite,
collect_ssl,
collect_sys,
collect_sysconfig,
collect_time,
collect_datetime,
collect_tkinter,
collect_zlib,
collect_expat,
collect_decimal,
collect_testcapi,
collect_resource,
collect_cc,
# Collecting from tests should be last as they have side effects.
collect_test_socket,
collect_test_support,
):
try:
collect_func(info_add)
except Exception as exc:
error = True
print("ERROR: %s() failed" % (collect_func.__name__),
file=sys.stderr)
traceback.print_exc(file=sys.stderr)
print(file=sys.stderr)
sys.stderr.flush()
return error
def dump_info(info, file=None):
title = "Python debug information"
print(title)
print("=" * len(title))
print()
infos = info.get_infos()
infos = sorted(infos.items())
for key, value in infos:
value = value.replace("\n", " ")
print("%s: %s" % (key, value))
print()
def main():
info = PythonInfo()
error = collect_info(info)
dump_info(info)
if error:
print("Collection failed: exit with error", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
| 16,532 | 646 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_fractions.py | """Tests for Lib/fractions.py."""
from decimal import Decimal
from test.support import requires_IEEE_754
import math
import numbers
import operator
import fractions
import sys
import unittest
import warnings
from copy import copy, deepcopy
from pickle import dumps, loads
F = fractions.Fraction
gcd = fractions.gcd
class DummyFloat(object):
"""Dummy float class for testing comparisons with Fractions"""
def __init__(self, value):
if not isinstance(value, float):
raise TypeError("DummyFloat can only be initialized from float")
self.value = value
def _richcmp(self, other, op):
if isinstance(other, numbers.Rational):
return op(F.from_float(self.value), other)
elif isinstance(other, DummyFloat):
return op(self.value, other.value)
else:
return NotImplemented
def __eq__(self, other): return self._richcmp(other, operator.eq)
def __le__(self, other): return self._richcmp(other, operator.le)
def __lt__(self, other): return self._richcmp(other, operator.lt)
def __ge__(self, other): return self._richcmp(other, operator.ge)
def __gt__(self, other): return self._richcmp(other, operator.gt)
# shouldn't be calling __float__ at all when doing comparisons
def __float__(self):
assert False, "__float__ should not be invoked for comparisons"
# same goes for subtraction
def __sub__(self, other):
assert False, "__sub__ should not be invoked for comparisons"
__rsub__ = __sub__
class DummyRational(object):
"""Test comparison of Fraction with a naive rational implementation."""
def __init__(self, num, den):
g = math.gcd(num, den)
self.num = num // g
self.den = den // g
def __eq__(self, other):
if isinstance(other, fractions.Fraction):
return (self.num == other._numerator and
self.den == other._denominator)
else:
return NotImplemented
def __lt__(self, other):
return(self.num * other._denominator < self.den * other._numerator)
def __gt__(self, other):
return(self.num * other._denominator > self.den * other._numerator)
def __le__(self, other):
return(self.num * other._denominator <= self.den * other._numerator)
def __ge__(self, other):
return(self.num * other._denominator >= self.den * other._numerator)
# this class is for testing comparisons; conversion to float
# should never be used for a comparison, since it loses accuracy
def __float__(self):
assert False, "__float__ should not be invoked"
class DummyFraction(fractions.Fraction):
"""Dummy Fraction subclass for copy and deepcopy testing."""
class GcdTest(unittest.TestCase):
def testMisc(self):
# fractions.gcd() is deprecated
with self.assertWarnsRegex(DeprecationWarning, r'fractions\.gcd'):
gcd(1, 1)
with warnings.catch_warnings():
warnings.filterwarnings('ignore', r'fractions\.gcd',
DeprecationWarning)
self.assertEqual(0, gcd(0, 0))
self.assertEqual(1, gcd(1, 0))
self.assertEqual(-1, gcd(-1, 0))
self.assertEqual(1, gcd(0, 1))
self.assertEqual(-1, gcd(0, -1))
self.assertEqual(1, gcd(7, 1))
self.assertEqual(-1, gcd(7, -1))
self.assertEqual(1, gcd(-23, 15))
self.assertEqual(12, gcd(120, 84))
self.assertEqual(-12, gcd(84, -120))
self.assertEqual(gcd(120.0, 84), 12.0)
self.assertEqual(gcd(120, 84.0), 12.0)
self.assertEqual(gcd(F(120), F(84)), F(12))
self.assertEqual(gcd(F(120, 77), F(84, 55)), F(12, 385))
def _components(r):
return (r.numerator, r.denominator)
class FractionTest(unittest.TestCase):
def assertTypedEquals(self, expected, actual):
"""Asserts that both the types and values are the same."""
self.assertEqual(type(expected), type(actual))
self.assertEqual(expected, actual)
def assertRaisesMessage(self, exc_type, message,
callable, *args, **kwargs):
"""Asserts that callable(*args, **kwargs) raises exc_type(message)."""
try:
callable(*args, **kwargs)
except exc_type as e:
self.assertEqual(message, str(e))
else:
self.fail("%s not raised" % exc_type.__name__)
def testInit(self):
self.assertEqual((0, 1), _components(F()))
self.assertEqual((7, 1), _components(F(7)))
self.assertEqual((7, 3), _components(F(F(7, 3))))
self.assertEqual((-1, 1), _components(F(-1, 1)))
self.assertEqual((-1, 1), _components(F(1, -1)))
self.assertEqual((1, 1), _components(F(-2, -2)))
self.assertEqual((1, 2), _components(F(5, 10)))
self.assertEqual((7, 15), _components(F(7, 15)))
self.assertEqual((10**23, 1), _components(F(10**23)))
self.assertEqual((3, 77), _components(F(F(3, 7), 11)))
self.assertEqual((-9, 5), _components(F(2, F(-10, 9))))
self.assertEqual((2486, 2485), _components(F(F(22, 7), F(355, 113))))
self.assertRaisesMessage(ZeroDivisionError, "Fraction(12, 0)",
F, 12, 0)
self.assertRaises(TypeError, F, 1.5 + 3j)
self.assertRaises(TypeError, F, "3/2", 3)
self.assertRaises(TypeError, F, 3, 0j)
self.assertRaises(TypeError, F, 3, 1j)
self.assertRaises(TypeError, F, 1, 2, 3)
@requires_IEEE_754
def testInitFromFloat(self):
self.assertEqual((5, 2), _components(F(2.5)))
self.assertEqual((0, 1), _components(F(-0.0)))
self.assertEqual((3602879701896397, 36028797018963968),
_components(F(0.1)))
# bug 16469: error types should be consistent with float -> int
self.assertRaises(ValueError, F, float('nan'))
self.assertRaises(OverflowError, F, float('inf'))
self.assertRaises(OverflowError, F, float('-inf'))
def testInitFromDecimal(self):
self.assertEqual((11, 10),
_components(F(Decimal('1.1'))))
self.assertEqual((7, 200),
_components(F(Decimal('3.5e-2'))))
self.assertEqual((0, 1),
_components(F(Decimal('.000e20'))))
# bug 16469: error types should be consistent with decimal -> int
self.assertRaises(ValueError, F, Decimal('nan'))
self.assertRaises(ValueError, F, Decimal('snan'))
self.assertRaises(OverflowError, F, Decimal('inf'))
self.assertRaises(OverflowError, F, Decimal('-inf'))
def testFromString(self):
self.assertEqual((5, 1), _components(F("5")))
self.assertEqual((3, 2), _components(F("3/2")))
self.assertEqual((3, 2), _components(F(" \n +3/2")))
self.assertEqual((-3, 2), _components(F("-3/2 ")))
self.assertEqual((13, 2), _components(F(" 013/02 \n ")))
self.assertEqual((16, 5), _components(F(" 3.2 ")))
self.assertEqual((-16, 5), _components(F(" -3.2 ")))
self.assertEqual((-3, 1), _components(F(" -3. ")))
self.assertEqual((3, 5), _components(F(" .6 ")))
self.assertEqual((1, 3125), _components(F("32.e-5")))
self.assertEqual((1000000, 1), _components(F("1E+06")))
self.assertEqual((-12300, 1), _components(F("-1.23e4")))
self.assertEqual((0, 1), _components(F(" .0e+0\t")))
self.assertEqual((0, 1), _components(F("-0.000e0")))
self.assertRaisesMessage(
ZeroDivisionError, "Fraction(3, 0)",
F, "3/0")
self.assertRaisesMessage(
ValueError, "Invalid literal for Fraction: '3/'",
F, "3/")
self.assertRaisesMessage(
ValueError, "Invalid literal for Fraction: '/2'",
F, "/2")
self.assertRaisesMessage(
ValueError, "Invalid literal for Fraction: '3 /2'",
F, "3 /2")
self.assertRaisesMessage(
# Denominators don't need a sign.
ValueError, "Invalid literal for Fraction: '3/+2'",
F, "3/+2")
self.assertRaisesMessage(
# Imitate float's parsing.
ValueError, "Invalid literal for Fraction: '+ 3/2'",
F, "+ 3/2")
self.assertRaisesMessage(
# Avoid treating '.' as a regex special character.
ValueError, "Invalid literal for Fraction: '3a2'",
F, "3a2")
self.assertRaisesMessage(
# Don't accept combinations of decimals and rationals.
ValueError, "Invalid literal for Fraction: '3/7.2'",
F, "3/7.2")
self.assertRaisesMessage(
# Don't accept combinations of decimals and rationals.
ValueError, "Invalid literal for Fraction: '3.2/7'",
F, "3.2/7")
self.assertRaisesMessage(
# Allow 3. and .3, but not .
ValueError, "Invalid literal for Fraction: '.'",
F, ".")
def testImmutable(self):
r = F(7, 3)
r.__init__(2, 15)
self.assertEqual((7, 3), _components(r))
self.assertRaises(AttributeError, setattr, r, 'numerator', 12)
self.assertRaises(AttributeError, setattr, r, 'denominator', 6)
self.assertEqual((7, 3), _components(r))
# But if you _really_ need to:
r._numerator = 4
r._denominator = 2
self.assertEqual((4, 2), _components(r))
# Which breaks some important operations:
self.assertNotEqual(F(4, 2), r)
def testFromFloat(self):
self.assertRaises(TypeError, F.from_float, 3+4j)
self.assertEqual((10, 1), _components(F.from_float(10)))
bigint = 1234567890123456789
self.assertEqual((bigint, 1), _components(F.from_float(bigint)))
self.assertEqual((0, 1), _components(F.from_float(-0.0)))
self.assertEqual((10, 1), _components(F.from_float(10.0)))
self.assertEqual((-5, 2), _components(F.from_float(-2.5)))
self.assertEqual((99999999999999991611392, 1),
_components(F.from_float(1e23)))
self.assertEqual(float(10**23), float(F.from_float(1e23)))
self.assertEqual((3602879701896397, 1125899906842624),
_components(F.from_float(3.2)))
self.assertEqual(3.2, float(F.from_float(3.2)))
inf = 1e1000
nan = inf - inf
# bug 16469: error types should be consistent with float -> int
self.assertRaisesMessage(
OverflowError, "cannot convert Infinity to integer ratio",
F.from_float, inf)
self.assertRaisesMessage(
OverflowError, "cannot convert Infinity to integer ratio",
F.from_float, -inf)
self.assertRaisesMessage(
ValueError, "cannot convert NaN to integer ratio",
F.from_float, nan)
def testFromDecimal(self):
self.assertRaises(TypeError, F.from_decimal, 3+4j)
self.assertEqual(F(10, 1), F.from_decimal(10))
self.assertEqual(F(0), F.from_decimal(Decimal("-0")))
self.assertEqual(F(5, 10), F.from_decimal(Decimal("0.5")))
self.assertEqual(F(5, 1000), F.from_decimal(Decimal("5e-3")))
self.assertEqual(F(5000), F.from_decimal(Decimal("5e3")))
self.assertEqual(1 - F(1, 10**30),
F.from_decimal(Decimal("0." + "9" * 30)))
# bug 16469: error types should be consistent with decimal -> int
self.assertRaisesMessage(
OverflowError, "cannot convert Infinity to integer ratio",
F.from_decimal, Decimal("inf"))
self.assertRaisesMessage(
OverflowError, "cannot convert Infinity to integer ratio",
F.from_decimal, Decimal("-inf"))
self.assertRaisesMessage(
ValueError, "cannot convert NaN to integer ratio",
F.from_decimal, Decimal("nan"))
self.assertRaisesMessage(
ValueError, "cannot convert NaN to integer ratio",
F.from_decimal, Decimal("snan"))
def testLimitDenominator(self):
rpi = F('3.1415926535897932')
self.assertEqual(rpi.limit_denominator(10000), F(355, 113))
self.assertEqual(-rpi.limit_denominator(10000), F(-355, 113))
self.assertEqual(rpi.limit_denominator(113), F(355, 113))
self.assertEqual(rpi.limit_denominator(112), F(333, 106))
self.assertEqual(F(201, 200).limit_denominator(100), F(1))
self.assertEqual(F(201, 200).limit_denominator(101), F(102, 101))
self.assertEqual(F(0).limit_denominator(10000), F(0))
for i in (0, -1):
self.assertRaisesMessage(
ValueError, "max_denominator should be at least 1",
F(1).limit_denominator, i)
def testConversions(self):
self.assertTypedEquals(-1, math.trunc(F(-11, 10)))
self.assertTypedEquals(1, math.trunc(F(11, 10)))
self.assertTypedEquals(-2, math.floor(F(-11, 10)))
self.assertTypedEquals(-1, math.ceil(F(-11, 10)))
self.assertTypedEquals(-1, math.ceil(F(-10, 10)))
self.assertTypedEquals(-1, int(F(-11, 10)))
self.assertTypedEquals(0, round(F(-1, 10)))
self.assertTypedEquals(0, round(F(-5, 10)))
self.assertTypedEquals(-2, round(F(-15, 10)))
self.assertTypedEquals(-1, round(F(-7, 10)))
self.assertEqual(False, bool(F(0, 1)))
self.assertEqual(True, bool(F(3, 2)))
self.assertTypedEquals(0.1, float(F(1, 10)))
# Check that __float__ isn't implemented by converting the
# numerator and denominator to float before dividing.
self.assertRaises(OverflowError, float, int('2'*400+'7'))
self.assertAlmostEqual(2.0/3,
float(F(int('2'*400+'7'), int('3'*400+'1'))))
self.assertTypedEquals(0.1+0j, complex(F(1,10)))
def testRound(self):
self.assertTypedEquals(F(-200), round(F(-150), -2))
self.assertTypedEquals(F(-200), round(F(-250), -2))
self.assertTypedEquals(F(30), round(F(26), -1))
self.assertTypedEquals(F(-2, 10), round(F(-15, 100), 1))
self.assertTypedEquals(F(-2, 10), round(F(-25, 100), 1))
def testArithmetic(self):
self.assertEqual(F(1, 2), F(1, 10) + F(2, 5))
self.assertEqual(F(-3, 10), F(1, 10) - F(2, 5))
self.assertEqual(F(1, 25), F(1, 10) * F(2, 5))
self.assertEqual(F(1, 4), F(1, 10) / F(2, 5))
self.assertTypedEquals(2, F(9, 10) // F(2, 5))
self.assertTypedEquals(10**23, F(10**23, 1) // F(1))
self.assertEqual(F(2, 3), F(-7, 3) % F(3, 2))
self.assertEqual(F(8, 27), F(2, 3) ** F(3))
self.assertEqual(F(27, 8), F(2, 3) ** F(-3))
self.assertTypedEquals(2.0, F(4) ** F(1, 2))
self.assertEqual(F(1, 1), +F(1, 1))
z = pow(F(-1), F(1, 2))
self.assertAlmostEqual(z.real, 0)
self.assertEqual(z.imag, 1)
# Regression test for #27539.
p = F(-1, 2) ** 0
self.assertEqual(p, F(1, 1))
self.assertEqual(p.numerator, 1)
self.assertEqual(p.denominator, 1)
p = F(-1, 2) ** -1
self.assertEqual(p, F(-2, 1))
self.assertEqual(p.numerator, -2)
self.assertEqual(p.denominator, 1)
p = F(-1, 2) ** -2
self.assertEqual(p, F(4, 1))
self.assertEqual(p.numerator, 4)
self.assertEqual(p.denominator, 1)
def testMixedArithmetic(self):
self.assertTypedEquals(F(11, 10), F(1, 10) + 1)
self.assertTypedEquals(1.1, F(1, 10) + 1.0)
self.assertTypedEquals(1.1 + 0j, F(1, 10) + (1.0 + 0j))
self.assertTypedEquals(F(11, 10), 1 + F(1, 10))
self.assertTypedEquals(1.1, 1.0 + F(1, 10))
self.assertTypedEquals(1.1 + 0j, (1.0 + 0j) + F(1, 10))
self.assertTypedEquals(F(-9, 10), F(1, 10) - 1)
self.assertTypedEquals(-0.9, F(1, 10) - 1.0)
self.assertTypedEquals(-0.9 + 0j, F(1, 10) - (1.0 + 0j))
self.assertTypedEquals(F(9, 10), 1 - F(1, 10))
self.assertTypedEquals(0.9, 1.0 - F(1, 10))
self.assertTypedEquals(0.9 + 0j, (1.0 + 0j) - F(1, 10))
self.assertTypedEquals(F(1, 10), F(1, 10) * 1)
self.assertTypedEquals(0.1, F(1, 10) * 1.0)
self.assertTypedEquals(0.1 + 0j, F(1, 10) * (1.0 + 0j))
self.assertTypedEquals(F(1, 10), 1 * F(1, 10))
self.assertTypedEquals(0.1, 1.0 * F(1, 10))
self.assertTypedEquals(0.1 + 0j, (1.0 + 0j) * F(1, 10))
self.assertTypedEquals(F(1, 10), F(1, 10) / 1)
self.assertTypedEquals(0.1, F(1, 10) / 1.0)
self.assertTypedEquals(0.1 + 0j, F(1, 10) / (1.0 + 0j))
self.assertTypedEquals(F(10, 1), 1 / F(1, 10))
self.assertTypedEquals(10.0, 1.0 / F(1, 10))
self.assertTypedEquals(10.0 + 0j, (1.0 + 0j) / F(1, 10))
self.assertTypedEquals(0, F(1, 10) // 1)
self.assertTypedEquals(0, F(1, 10) // 1.0)
self.assertTypedEquals(10, 1 // F(1, 10))
self.assertTypedEquals(10**23, 10**22 // F(1, 10))
self.assertTypedEquals(10, 1.0 // F(1, 10))
self.assertTypedEquals(F(1, 10), F(1, 10) % 1)
self.assertTypedEquals(0.1, F(1, 10) % 1.0)
self.assertTypedEquals(F(0, 1), 1 % F(1, 10))
self.assertTypedEquals(0.0, 1.0 % F(1, 10))
# No need for divmod since we don't override it.
# ** has more interesting conversion rules.
self.assertTypedEquals(F(100, 1), F(1, 10) ** -2)
self.assertTypedEquals(F(100, 1), F(10, 1) ** 2)
self.assertTypedEquals(0.1, F(1, 10) ** 1.0)
self.assertTypedEquals(0.1 + 0j, F(1, 10) ** (1.0 + 0j))
self.assertTypedEquals(4 , 2 ** F(2, 1))
z = pow(-1, F(1, 2))
self.assertAlmostEqual(0, z.real)
self.assertEqual(1, z.imag)
self.assertTypedEquals(F(1, 4) , 2 ** F(-2, 1))
self.assertTypedEquals(2.0 , 4 ** F(1, 2))
self.assertTypedEquals(0.25, 2.0 ** F(-2, 1))
self.assertTypedEquals(1.0 + 0j, (1.0 + 0j) ** F(1, 10))
self.assertRaises(ZeroDivisionError, operator.pow,
F(0, 1), -2)
def testMixingWithDecimal(self):
# Decimal refuses mixed arithmetic (but not mixed comparisons)
self.assertRaises(TypeError, operator.add,
F(3,11), Decimal('3.1415926'))
self.assertRaises(TypeError, operator.add,
Decimal('3.1415926'), F(3,11))
def testComparisons(self):
self.assertTrue(F(1, 2) < F(2, 3))
self.assertFalse(F(1, 2) < F(1, 2))
self.assertTrue(F(1, 2) <= F(2, 3))
self.assertTrue(F(1, 2) <= F(1, 2))
self.assertFalse(F(2, 3) <= F(1, 2))
self.assertTrue(F(1, 2) == F(1, 2))
self.assertFalse(F(1, 2) == F(1, 3))
self.assertFalse(F(1, 2) != F(1, 2))
self.assertTrue(F(1, 2) != F(1, 3))
def testComparisonsDummyRational(self):
self.assertTrue(F(1, 2) == DummyRational(1, 2))
self.assertTrue(DummyRational(1, 2) == F(1, 2))
self.assertFalse(F(1, 2) == DummyRational(3, 4))
self.assertFalse(DummyRational(3, 4) == F(1, 2))
self.assertTrue(F(1, 2) < DummyRational(3, 4))
self.assertFalse(F(1, 2) < DummyRational(1, 2))
self.assertFalse(F(1, 2) < DummyRational(1, 7))
self.assertFalse(F(1, 2) > DummyRational(3, 4))
self.assertFalse(F(1, 2) > DummyRational(1, 2))
self.assertTrue(F(1, 2) > DummyRational(1, 7))
self.assertTrue(F(1, 2) <= DummyRational(3, 4))
self.assertTrue(F(1, 2) <= DummyRational(1, 2))
self.assertFalse(F(1, 2) <= DummyRational(1, 7))
self.assertFalse(F(1, 2) >= DummyRational(3, 4))
self.assertTrue(F(1, 2) >= DummyRational(1, 2))
self.assertTrue(F(1, 2) >= DummyRational(1, 7))
self.assertTrue(DummyRational(1, 2) < F(3, 4))
self.assertFalse(DummyRational(1, 2) < F(1, 2))
self.assertFalse(DummyRational(1, 2) < F(1, 7))
self.assertFalse(DummyRational(1, 2) > F(3, 4))
self.assertFalse(DummyRational(1, 2) > F(1, 2))
self.assertTrue(DummyRational(1, 2) > F(1, 7))
self.assertTrue(DummyRational(1, 2) <= F(3, 4))
self.assertTrue(DummyRational(1, 2) <= F(1, 2))
self.assertFalse(DummyRational(1, 2) <= F(1, 7))
self.assertFalse(DummyRational(1, 2) >= F(3, 4))
self.assertTrue(DummyRational(1, 2) >= F(1, 2))
self.assertTrue(DummyRational(1, 2) >= F(1, 7))
def testComparisonsDummyFloat(self):
x = DummyFloat(1./3.)
y = F(1, 3)
self.assertTrue(x != y)
self.assertTrue(x < y or x > y)
self.assertFalse(x == y)
self.assertFalse(x <= y and x >= y)
self.assertTrue(y != x)
self.assertTrue(y < x or y > x)
self.assertFalse(y == x)
self.assertFalse(y <= x and y >= x)
def testMixedLess(self):
self.assertTrue(2 < F(5, 2))
self.assertFalse(2 < F(4, 2))
self.assertTrue(F(5, 2) < 3)
self.assertFalse(F(4, 2) < 2)
self.assertTrue(F(1, 2) < 0.6)
self.assertFalse(F(1, 2) < 0.4)
self.assertTrue(0.4 < F(1, 2))
self.assertFalse(0.5 < F(1, 2))
self.assertFalse(float('inf') < F(1, 2))
self.assertTrue(float('-inf') < F(0, 10))
self.assertFalse(float('nan') < F(-3, 7))
self.assertTrue(F(1, 2) < float('inf'))
self.assertFalse(F(17, 12) < float('-inf'))
self.assertFalse(F(144, -89) < float('nan'))
def testMixedLessEqual(self):
self.assertTrue(0.5 <= F(1, 2))
self.assertFalse(0.6 <= F(1, 2))
self.assertTrue(F(1, 2) <= 0.5)
self.assertFalse(F(1, 2) <= 0.4)
self.assertTrue(2 <= F(4, 2))
self.assertFalse(2 <= F(3, 2))
self.assertTrue(F(4, 2) <= 2)
self.assertFalse(F(5, 2) <= 2)
self.assertFalse(float('inf') <= F(1, 2))
self.assertTrue(float('-inf') <= F(0, 10))
self.assertFalse(float('nan') <= F(-3, 7))
self.assertTrue(F(1, 2) <= float('inf'))
self.assertFalse(F(17, 12) <= float('-inf'))
self.assertFalse(F(144, -89) <= float('nan'))
def testBigFloatComparisons(self):
# Because 10**23 can't be represented exactly as a float:
self.assertFalse(F(10**23) == float(10**23))
# The first test demonstrates why these are important.
self.assertFalse(1e23 < float(F(math.trunc(1e23) + 1)))
self.assertTrue(1e23 < F(math.trunc(1e23) + 1))
self.assertFalse(1e23 <= F(math.trunc(1e23) - 1))
self.assertTrue(1e23 > F(math.trunc(1e23) - 1))
self.assertFalse(1e23 >= F(math.trunc(1e23) + 1))
def testBigComplexComparisons(self):
self.assertFalse(F(10**23) == complex(10**23))
self.assertRaises(TypeError, operator.gt, F(10**23), complex(10**23))
self.assertRaises(TypeError, operator.le, F(10**23), complex(10**23))
x = F(3, 8)
z = complex(0.375, 0.0)
w = complex(0.375, 0.2)
self.assertTrue(x == z)
self.assertFalse(x != z)
self.assertFalse(x == w)
self.assertTrue(x != w)
for op in operator.lt, operator.le, operator.gt, operator.ge:
self.assertRaises(TypeError, op, x, z)
self.assertRaises(TypeError, op, z, x)
self.assertRaises(TypeError, op, x, w)
self.assertRaises(TypeError, op, w, x)
def testMixedEqual(self):
self.assertTrue(0.5 == F(1, 2))
self.assertFalse(0.6 == F(1, 2))
self.assertTrue(F(1, 2) == 0.5)
self.assertFalse(F(1, 2) == 0.4)
self.assertTrue(2 == F(4, 2))
self.assertFalse(2 == F(3, 2))
self.assertTrue(F(4, 2) == 2)
self.assertFalse(F(5, 2) == 2)
self.assertFalse(F(5, 2) == float('nan'))
self.assertFalse(float('nan') == F(3, 7))
self.assertFalse(F(5, 2) == float('inf'))
self.assertFalse(float('-inf') == F(2, 5))
def testStringification(self):
self.assertEqual("Fraction(7, 3)", repr(F(7, 3)))
self.assertEqual("Fraction(6283185307, 2000000000)",
repr(F('3.1415926535')))
self.assertEqual("Fraction(-1, 100000000000000000000)",
repr(F(1, -10**20)))
self.assertEqual("7/3", str(F(7, 3)))
self.assertEqual("7", str(F(7, 1)))
def testHash(self):
hmod = sys.hash_info.modulus
hinf = sys.hash_info.inf
self.assertEqual(hash(2.5), hash(F(5, 2)))
self.assertEqual(hash(10**50), hash(F(10**50)))
self.assertNotEqual(hash(float(10**23)), hash(F(10**23)))
self.assertEqual(hinf, hash(F(1, hmod)))
# Check that __hash__ produces the same value as hash(), for
# consistency with int and Decimal. (See issue #10356.)
self.assertEqual(hash(F(-1)), F(-1).__hash__())
def testApproximatePi(self):
# Algorithm borrowed from
# http://docs.python.org/lib/decimal-recipes.html
three = F(3)
lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
while abs(s - lasts) > F(1, 10**9):
lasts = s
n, na = n+na, na+8
d, da = d+da, da+32
t = (t * n) / d
s += t
self.assertAlmostEqual(math.pi, s)
def testApproximateCos1(self):
# Algorithm borrowed from
# http://docs.python.org/lib/decimal-recipes.html
x = F(1)
i, lasts, s, fact, num, sign = 0, 0, F(1), 1, 1, 1
while abs(s - lasts) > F(1, 10**9):
lasts = s
i += 2
fact *= i * (i-1)
num *= x * x
sign *= -1
s += num / fact * sign
self.assertAlmostEqual(math.cos(1), s)
def test_copy_deepcopy_pickle(self):
r = F(13, 7)
dr = DummyFraction(13, 7)
self.assertEqual(r, loads(dumps(r)))
self.assertEqual(id(r), id(copy(r)))
self.assertEqual(id(r), id(deepcopy(r)))
self.assertNotEqual(id(dr), id(copy(dr)))
self.assertNotEqual(id(dr), id(deepcopy(dr)))
self.assertTypedEquals(dr, copy(dr))
self.assertTypedEquals(dr, deepcopy(dr))
def test_slots(self):
# Issue 4998
r = F(13, 7)
self.assertRaises(AttributeError, setattr, r, 'a', 10)
if __name__ == '__main__':
unittest.main()
| 26,545 | 636 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/CP932.TXT | #
# Name: cp932 to Unicode table
# Unicode version: 2.0
# Table version: 2.01
# Table format: Format A
# Date: 04/15/98
#
# Contact: [email protected]
#
# General notes: none
#
# Format: Three tab-separated columns
# Column #1 is the cp932 code (in hex)
# Column #2 is the Unicode (in hex as 0xXXXX)
# Column #3 is the Unicode name (follows a comment sign, '#')
#
# The entries are in cp932 order
#
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
80
81
82
83
84
85
86
87
88
89
8A
8B
8C
8D
8E
8F
90
91
92
93
94
95
96
97
98
99
9A
9B
9C
9D
9E
9F
A0
A1 FF61
A2 FF62
A3 FF63
A4 FF64
A5 FF65
A6 FF66
A7 FF67
A8 FF68
A9 FF69
AA FF6A
AB FF6B
AC FF6C
AD FF6D
AE FF6E
AF FF6F
B0 FF70
B1 FF71
B2 FF72
B3 FF73
B4 FF74
B5 FF75
B6 FF76
B7 FF77
B8 FF78
B9 FF79
BA FF7A
BB FF7B
BC FF7C
BD FF7D
BE FF7E
BF FF7F
C0 FF80
C1 FF81
C2 FF82
C3 FF83
C4 FF84
C5 FF85
C6 FF86
C7 FF87
C8 FF88
C9 FF89
CA FF8A
CB FF8B
CC FF8C
CD FF8D
CE FF8E
CF FF8F
D0 FF90
D1 FF91
D2 FF92
D3 FF93
D4 FF94
D5 FF95
D6 FF96
D7 FF97
D8 FF98
D9 FF99
DA FF9A
DB FF9B
DC FF9C
DD FF9D
DE FF9E
DF FF9F
E0
E1
E2
E3
E4
E5
E6
E7
E8
E9
EA
EB
EC
ED
EE
EF
F0
F1
F2
F3
F4
F5
F6
F7
F8
F9
FA
FB
FC
FD
FE
FF
8140 3000
8141 3001
8142 3002
8143 FF0C
8144 FF0E
8145 30FB
8146 FF1A
8147 FF1B
8148 FF1F
8149 FF01
814A 309B
814B 309C
814C 00B4
814D FF40
814E 00A8
814F FF3E
8150 FFE3
8151 FF3F
8152 30FD
8153 30FE
8154 309D
8155 309E
8156 3003
8157 4EDD
8158 3005
8159 3006
815A 3007
815B 30FC
815C 2015
815D 2010
815E FF0F
815F FF3C
8160 FF5E
8161 2225
8162 FF5C
8163 2026
8164 2025
8165 2018
8166 2019
8167 201C
8168 201D
8169 FF08
816A FF09
816B 3014
816C 3015
816D FF3B
816E FF3D
816F FF5B
8170 FF5D
8171 3008
8172 3009
8173 300A
8174 300B
8175 300C
8176 300D
8177 300E
8178 300F
8179 3010
817A 3011
817B FF0B
817C FF0D
817D 00B1
817E 00D7
8180 00F7
8181 FF1D
8182 2260
8183 FF1C
8184 FF1E
8185 2266
8186 2267
8187 221E
8188 2234
8189 2642
818A 2640
818B 00B0
818C 2032
818D 2033
818E 2103
818F FFE5
8190 FF04
8191 FFE0
8192 FFE1
8193 FF05
8194 FF03
8195 FF06
8196 FF0A
8197 FF20
8198 00A7
8199 2606
819A 2605
819B 25CB
819C 25CF
819D 25CE
819E 25C7
819F 25C6
81A0 25A1
81A1 25A0
81A2 25B3
81A3 25B2
81A4 25BD
81A5 25BC
81A6 203B
81A7 3012
81A8 2192
81A9 2190
81AA 2191
81AB 2193
81AC 3013
81B8 2208
81B9 220B
81BA 2286
81BB 2287
81BC 2282
81BD 2283
81BE 222A
81BF 2229
81C8 2227
81C9 2228
81CA FFE2
81CB 21D2
81CC 21D4
81CD 2200
81CE 2203
81DA 2220
81DB 22A5
81DC 2312
81DD 2202
81DE 2207
81DF 2261
81E0 2252
81E1 226A
81E2 226B
81E3 221A
81E4 223D
81E5 221D
81E6 2235
81E7 222B
81E8 222C
81F0 212B
81F1 2030
81F2 266F
81F3 266D
81F4 266A
81F5 2020
81F6 2021
81F7 00B6
81FC 25EF
824F FF10
8250 FF11
8251 FF12
8252 FF13
8253 FF14
8254 FF15
8255 FF16
8256 FF17
8257 FF18
8258 FF19
8260 FF21
8261 FF22
8262 FF23
8263 FF24
8264 FF25
8265 FF26
8266 FF27
8267 FF28
8268 FF29
8269 FF2A
826A FF2B
826B FF2C
826C FF2D
826D FF2E
826E FF2F
826F FF30
8270 FF31
8271 FF32
8272 FF33
8273 FF34
8274 FF35
8275 FF36
8276 FF37
8277 FF38
8278 FF39
8279 FF3A
8281 FF41
8282 FF42
8283 FF43
8284 FF44
8285 FF45
8286 FF46
8287 FF47
8288 FF48
8289 FF49
828A FF4A
828B FF4B
828C FF4C
828D FF4D
828E FF4E
828F FF4F
8290 FF50
8291 FF51
8292 FF52
8293 FF53
8294 FF54
8295 FF55
8296 FF56
8297 FF57
8298 FF58
8299 FF59
829A FF5A
829F 3041
82A0 3042
82A1 3043
82A2 3044
82A3 3045
82A4 3046
82A5 3047
82A6 3048
82A7 3049
82A8 304A
82A9 304B
82AA 304C
82AB 304D
82AC 304E
82AD 304F
82AE 3050
82AF 3051
82B0 3052
82B1 3053
82B2 3054
82B3 3055
82B4 3056
82B5 3057
82B6 3058
82B7 3059
82B8 305A
82B9 305B
82BA 305C
82BB 305D
82BC 305E
82BD 305F
82BE 3060
82BF 3061
82C0 3062
82C1 3063
82C2 3064
82C3 3065
82C4 3066
82C5 3067
82C6 3068
82C7 3069
82C8 306A
82C9 306B
82CA 306C
82CB 306D
82CC 306E
82CD 306F
82CE 3070
82CF 3071
82D0 3072
82D1 3073
82D2 3074
82D3 3075
82D4 3076
82D5 3077
82D6 3078
82D7 3079
82D8 307A
82D9 307B
82DA 307C
82DB 307D
82DC 307E
82DD 307F
82DE 3080
82DF 3081
82E0 3082
82E1 3083
82E2 3084
82E3 3085
82E4 3086
82E5 3087
82E6 3088
82E7 3089
82E8 308A
82E9 308B
82EA 308C
82EB 308D
82EC 308E
82ED 308F
82EE 3090
82EF 3091
82F0 3092
82F1 3093
8340 30A1
8341 30A2
8342 30A3
8343 30A4
8344 30A5
8345 30A6
8346 30A7
8347 30A8
8348 30A9
8349 30AA
834A 30AB
834B 30AC
834C 30AD
834D 30AE
834E 30AF
834F 30B0
8350 30B1
8351 30B2
8352 30B3
8353 30B4
8354 30B5
8355 30B6
8356 30B7
8357 30B8
8358 30B9
8359 30BA
835A 30BB
835B 30BC
835C 30BD
835D 30BE
835E 30BF
835F 30C0
8360 30C1
8361 30C2
8362 30C3
8363 30C4
8364 30C5
8365 30C6
8366 30C7
8367 30C8
8368 30C9
8369 30CA
836A 30CB
836B 30CC
836C 30CD
836D 30CE
836E 30CF
836F 30D0
8370 30D1
8371 30D2
8372 30D3
8373 30D4
8374 30D5
8375 30D6
8376 30D7
8377 30D8
8378 30D9
8379 30DA
837A 30DB
837B 30DC
837C 30DD
837D 30DE
837E 30DF
8380 30E0
8381 30E1
8382 30E2
8383 30E3
8384 30E4
8385 30E5
8386 30E6
8387 30E7
8388 30E8
8389 30E9
838A 30EA
838B 30EB
838C 30EC
838D 30ED
838E 30EE
838F 30EF
8390 30F0
8391 30F1
8392 30F2
8393 30F3
8394 30F4
8395 30F5
8396 30F6
839F 0391
83A0 0392
83A1 0393
83A2 0394
83A3 0395
83A4 0396
83A5 0397
83A6 0398
83A7 0399
83A8 039A
83A9 039B
83AA 039C
83AB 039D
83AC 039E
83AD 039F
83AE 03A0
83AF 03A1
83B0 03A3
83B1 03A4
83B2 03A5
83B3 03A6
83B4 03A7
83B5 03A8
83B6 03A9
83BF 03B1
83C0 03B2
83C1 03B3
83C2 03B4
83C3 03B5
83C4 03B6
83C5 03B7
83C6 03B8
83C7 03B9
83C8 03BA
83C9 03BB
83CA 03BC
83CB 03BD
83CC 03BE
83CD 03BF
83CE 03C0
83CF 03C1
83D0 03C3
83D1 03C4
83D2 03C5
83D3 03C6
83D4 03C7
83D5 03C8
83D6 03C9
8440 0410
8441 0411
8442 0412
8443 0413
8444 0414
8445 0415
8446 0401
8447 0416
8448 0417
8449 0418
844A 0419
844B 041A
844C 041B
844D 041C
844E 041D
844F 041E
8450 041F
8451 0420
8452 0421
8453 0422
8454 0423
8455 0424
8456 0425
8457 0426
8458 0427
8459 0428
845A 0429
845B 042A
845C 042B
845D 042C
845E 042D
845F 042E
8460 042F
8470 0430
8471 0431
8472 0432
8473 0433
8474 0434
8475 0435
8476 0451
8477 0436
8478 0437
8479 0438
847A 0439
847B 043A
847C 043B
847D 043C
847E 043D
8480 043E
8481 043F
8482 0440
8483 0441
8484 0442
8485 0443
8486 0444
8487 0445
8488 0446
8489 0447
848A 0448
848B 0449
848C 044A
848D 044B
848E 044C
848F 044D
8490 044E
8491 044F
849F 2500
84A0 2502
84A1 250C
84A2 2510
84A3 2518
84A4 2514
84A5 251C
84A6 252C
84A7 2524
84A8 2534
84A9 253C
84AA 2501
84AB 2503
84AC 250F
84AD 2513
84AE 251B
84AF 2517
84B0 2523
84B1 2533
84B2 252B
84B3 253B
84B4 254B
84B5 2520
84B6 252F
84B7 2528
84B8 2537
84B9 253F
84BA 251D
84BB 2530
84BC 2525
84BD 2538
84BE 2542
8740 2460
8741 2461
8742 2462
8743 2463
8744 2464
8745 2465
8746 2466
8747 2467
8748 2468
8749 2469
874A 246A
874B 246B
874C 246C
874D 246D
874E 246E
874F 246F
8750 2470
8751 2471
8752 2472
8753 2473
8754 2160
8755 2161
8756 2162
8757 2163
8758 2164
8759 2165
875A 2166
875B 2167
875C 2168
875D 2169
875F 3349
8760 3314
8761 3322
8762 334D
8763 3318
8764 3327
8765 3303
8766 3336
8767 3351
8768 3357
8769 330D
876A 3326
876B 3323
876C 332B
876D 334A
876E 333B
876F 339C
8770 339D
8771 339E
8772 338E
8773 338F
8774 33C4
8775 33A1
877E 337B
8780 301D
8781 301F
8782 2116
8783 33CD
8784 2121
8785 32A4
8786 32A5
8787 32A6
8788 32A7
8789 32A8
878A 3231
878B 3232
878C 3239
878D 337E
878E 337D
878F 337C
8790 2252
8791 2261
8792 222B
8793 222E
8794 2211
8795 221A
8796 22A5
8797 2220
8798 221F
8799 22BF
879A 2235
879B 2229
879C 222A
889F 4E9C
88A0 5516
88A1 5A03
88A2 963F
88A3 54C0
88A4 611B
88A5 6328
88A6 59F6
88A7 9022
88A8 8475
88A9 831C
88AA 7A50
88AB 60AA
88AC 63E1
88AD 6E25
88AE 65ED
88AF 8466
88B0 82A6
88B1 9BF5
88B2 6893
88B3 5727
88B4 65A1
88B5 6271
88B6 5B9B
88B7 59D0
88B8 867B
88B9 98F4
88BA 7D62
88BB 7DBE
88BC 9B8E
88BD 6216
88BE 7C9F
88BF 88B7
88C0 5B89
88C1 5EB5
88C2 6309
88C3 6697
88C4 6848
88C5 95C7
88C6 978D
88C7 674F
88C8 4EE5
88C9 4F0A
88CA 4F4D
88CB 4F9D
88CC 5049
88CD 56F2
88CE 5937
88CF 59D4
88D0 5A01
88D1 5C09
88D2 60DF
88D3 610F
88D4 6170
88D5 6613
88D6 6905
88D7 70BA
88D8 754F
88D9 7570
88DA 79FB
88DB 7DAD
88DC 7DEF
88DD 80C3
88DE 840E
88DF 8863
88E0 8B02
88E1 9055
88E2 907A
88E3 533B
88E4 4E95
88E5 4EA5
88E6 57DF
88E7 80B2
88E8 90C1
88E9 78EF
88EA 4E00
88EB 58F1
88EC 6EA2
88ED 9038
88EE 7A32
88EF 8328
88F0 828B
88F1 9C2F
88F2 5141
88F3 5370
88F4 54BD
88F5 54E1
88F6 56E0
88F7 59FB
88F8 5F15
88F9 98F2
88FA 6DEB
88FB 80E4
88FC 852D
8940 9662
8941 9670
8942 96A0
8943 97FB
8944 540B
8945 53F3
8946 5B87
8947 70CF
8948 7FBD
8949 8FC2
894A 96E8
894B 536F
894C 9D5C
894D 7ABA
894E 4E11
894F 7893
8950 81FC
8951 6E26
8952 5618
8953 5504
8954 6B1D
8955 851A
8956 9C3B
8957 59E5
8958 53A9
8959 6D66
895A 74DC
895B 958F
895C 5642
895D 4E91
895E 904B
895F 96F2
8960 834F
8961 990C
8962 53E1
8963 55B6
8964 5B30
8965 5F71
8966 6620
8967 66F3
8968 6804
8969 6C38
896A 6CF3
896B 6D29
896C 745B
896D 76C8
896E 7A4E
896F 9834
8970 82F1
8971 885B
8972 8A60
8973 92ED
8974 6DB2
8975 75AB
8976 76CA
8977 99C5
8978 60A6
8979 8B01
897A 8D8A
897B 95B2
897C 698E
897D 53AD
897E 5186
8980 5712
8981 5830
8982 5944
8983 5BB4
8984 5EF6
8985 6028
8986 63A9
8987 63F4
8988 6CBF
8989 6F14
898A 708E
898B 7114
898C 7159
898D 71D5
898E 733F
898F 7E01
8990 8276
8991 82D1
8992 8597
8993 9060
8994 925B
8995 9D1B
8996 5869
8997 65BC
8998 6C5A
8999 7525
899A 51F9
899B 592E
899C 5965
899D 5F80
899E 5FDC
899F 62BC
89A0 65FA
89A1 6A2A
89A2 6B27
89A3 6BB4
89A4 738B
89A5 7FC1
89A6 8956
89A7 9D2C
89A8 9D0E
89A9 9EC4
89AA 5CA1
89AB 6C96
89AC 837B
89AD 5104
89AE 5C4B
89AF 61B6
89B0 81C6
89B1 6876
89B2 7261
89B3 4E59
89B4 4FFA
89B5 5378
89B6 6069
89B7 6E29
89B8 7A4F
89B9 97F3
89BA 4E0B
89BB 5316
89BC 4EEE
89BD 4F55
89BE 4F3D
89BF 4FA1
89C0 4F73
89C1 52A0
89C2 53EF
89C3 5609
89C4 590F
89C5 5AC1
89C6 5BB6
89C7 5BE1
89C8 79D1
89C9 6687
89CA 679C
89CB 67B6
89CC 6B4C
89CD 6CB3
89CE 706B
89CF 73C2
89D0 798D
89D1 79BE
89D2 7A3C
89D3 7B87
89D4 82B1
89D5 82DB
89D6 8304
89D7 8377
89D8 83EF
89D9 83D3
89DA 8766
89DB 8AB2
89DC 5629
89DD 8CA8
89DE 8FE6
89DF 904E
89E0 971E
89E1 868A
89E2 4FC4
89E3 5CE8
89E4 6211
89E5 7259
89E6 753B
89E7 81E5
89E8 82BD
89E9 86FE
89EA 8CC0
89EB 96C5
89EC 9913
89ED 99D5
89EE 4ECB
89EF 4F1A
89F0 89E3
89F1 56DE
89F2 584A
89F3 58CA
89F4 5EFB
89F5 5FEB
89F6 602A
89F7 6094
89F8 6062
89F9 61D0
89FA 6212
89FB 62D0
89FC 6539
8A40 9B41
8A41 6666
8A42 68B0
8A43 6D77
8A44 7070
8A45 754C
8A46 7686
8A47 7D75
8A48 82A5
8A49 87F9
8A4A 958B
8A4B 968E
8A4C 8C9D
8A4D 51F1
8A4E 52BE
8A4F 5916
8A50 54B3
8A51 5BB3
8A52 5D16
8A53 6168
8A54 6982
8A55 6DAF
8A56 788D
8A57 84CB
8A58 8857
8A59 8A72
8A5A 93A7
8A5B 9AB8
8A5C 6D6C
8A5D 99A8
8A5E 86D9
8A5F 57A3
8A60 67FF
8A61 86CE
8A62 920E
8A63 5283
8A64 5687
8A65 5404
8A66 5ED3
8A67 62E1
8A68 64B9
8A69 683C
8A6A 6838
8A6B 6BBB
8A6C 7372
8A6D 78BA
8A6E 7A6B
8A6F 899A
8A70 89D2
8A71 8D6B
8A72 8F03
8A73 90ED
8A74 95A3
8A75 9694
8A76 9769
8A77 5B66
8A78 5CB3
8A79 697D
8A7A 984D
8A7B 984E
8A7C 639B
8A7D 7B20
8A7E 6A2B
8A80 6A7F
8A81 68B6
8A82 9C0D
8A83 6F5F
8A84 5272
8A85 559D
8A86 6070
8A87 62EC
8A88 6D3B
8A89 6E07
8A8A 6ED1
8A8B 845B
8A8C 8910
8A8D 8F44
8A8E 4E14
8A8F 9C39
8A90 53F6
8A91 691B
8A92 6A3A
8A93 9784
8A94 682A
8A95 515C
8A96 7AC3
8A97 84B2
8A98 91DC
8A99 938C
8A9A 565B
8A9B 9D28
8A9C 6822
8A9D 8305
8A9E 8431
8A9F 7CA5
8AA0 5208
8AA1 82C5
8AA2 74E6
8AA3 4E7E
8AA4 4F83
8AA5 51A0
8AA6 5BD2
8AA7 520A
8AA8 52D8
8AA9 52E7
8AAA 5DFB
8AAB 559A
8AAC 582A
8AAD 59E6
8AAE 5B8C
8AAF 5B98
8AB0 5BDB
8AB1 5E72
8AB2 5E79
8AB3 60A3
8AB4 611F
8AB5 6163
8AB6 61BE
8AB7 63DB
8AB8 6562
8AB9 67D1
8ABA 6853
8ABB 68FA
8ABC 6B3E
8ABD 6B53
8ABE 6C57
8ABF 6F22
8AC0 6F97
8AC1 6F45
8AC2 74B0
8AC3 7518
8AC4 76E3
8AC5 770B
8AC6 7AFF
8AC7 7BA1
8AC8 7C21
8AC9 7DE9
8ACA 7F36
8ACB 7FF0
8ACC 809D
8ACD 8266
8ACE 839E
8ACF 89B3
8AD0 8ACC
8AD1 8CAB
8AD2 9084
8AD3 9451
8AD4 9593
8AD5 9591
8AD6 95A2
8AD7 9665
8AD8 97D3
8AD9 9928
8ADA 8218
8ADB 4E38
8ADC 542B
8ADD 5CB8
8ADE 5DCC
8ADF 73A9
8AE0 764C
8AE1 773C
8AE2 5CA9
8AE3 7FEB
8AE4 8D0B
8AE5 96C1
8AE6 9811
8AE7 9854
8AE8 9858
8AE9 4F01
8AEA 4F0E
8AEB 5371
8AEC 559C
8AED 5668
8AEE 57FA
8AEF 5947
8AF0 5B09
8AF1 5BC4
8AF2 5C90
8AF3 5E0C
8AF4 5E7E
8AF5 5FCC
8AF6 63EE
8AF7 673A
8AF8 65D7
8AF9 65E2
8AFA 671F
8AFB 68CB
8AFC 68C4
8B40 6A5F
8B41 5E30
8B42 6BC5
8B43 6C17
8B44 6C7D
8B45 757F
8B46 7948
8B47 5B63
8B48 7A00
8B49 7D00
8B4A 5FBD
8B4B 898F
8B4C 8A18
8B4D 8CB4
8B4E 8D77
8B4F 8ECC
8B50 8F1D
8B51 98E2
8B52 9A0E
8B53 9B3C
8B54 4E80
8B55 507D
8B56 5100
8B57 5993
8B58 5B9C
8B59 622F
8B5A 6280
8B5B 64EC
8B5C 6B3A
8B5D 72A0
8B5E 7591
8B5F 7947
8B60 7FA9
8B61 87FB
8B62 8ABC
8B63 8B70
8B64 63AC
8B65 83CA
8B66 97A0
8B67 5409
8B68 5403
8B69 55AB
8B6A 6854
8B6B 6A58
8B6C 8A70
8B6D 7827
8B6E 6775
8B6F 9ECD
8B70 5374
8B71 5BA2
8B72 811A
8B73 8650
8B74 9006
8B75 4E18
8B76 4E45
8B77 4EC7
8B78 4F11
8B79 53CA
8B7A 5438
8B7B 5BAE
8B7C 5F13
8B7D 6025
8B7E 6551
8B80 673D
8B81 6C42
8B82 6C72
8B83 6CE3
8B84 7078
8B85 7403
8B86 7A76
8B87 7AAE
8B88 7B08
8B89 7D1A
8B8A 7CFE
8B8B 7D66
8B8C 65E7
8B8D 725B
8B8E 53BB
8B8F 5C45
8B90 5DE8
8B91 62D2
8B92 62E0
8B93 6319
8B94 6E20
8B95 865A
8B96 8A31
8B97 8DDD
8B98 92F8
8B99 6F01
8B9A 79A6
8B9B 9B5A
8B9C 4EA8
8B9D 4EAB
8B9E 4EAC
8B9F 4F9B
8BA0 4FA0
8BA1 50D1
8BA2 5147
8BA3 7AF6
8BA4 5171
8BA5 51F6
8BA6 5354
8BA7 5321
8BA8 537F
8BA9 53EB
8BAA 55AC
8BAB 5883
8BAC 5CE1
8BAD 5F37
8BAE 5F4A
8BAF 602F
8BB0 6050
8BB1 606D
8BB2 631F
8BB3 6559
8BB4 6A4B
8BB5 6CC1
8BB6 72C2
8BB7 72ED
8BB8 77EF
8BB9 80F8
8BBA 8105
8BBB 8208
8BBC 854E
8BBD 90F7
8BBE 93E1
8BBF 97FF
8BC0 9957
8BC1 9A5A
8BC2 4EF0
8BC3 51DD
8BC4 5C2D
8BC5 6681
8BC6 696D
8BC7 5C40
8BC8 66F2
8BC9 6975
8BCA 7389
8BCB 6850
8BCC 7C81
8BCD 50C5
8BCE 52E4
8BCF 5747
8BD0 5DFE
8BD1 9326
8BD2 65A4
8BD3 6B23
8BD4 6B3D
8BD5 7434
8BD6 7981
8BD7 79BD
8BD8 7B4B
8BD9 7DCA
8BDA 82B9
8BDB 83CC
8BDC 887F
8BDD 895F
8BDE 8B39
8BDF 8FD1
8BE0 91D1
8BE1 541F
8BE2 9280
8BE3 4E5D
8BE4 5036
8BE5 53E5
8BE6 533A
8BE7 72D7
8BE8 7396
8BE9 77E9
8BEA 82E6
8BEB 8EAF
8BEC 99C6
8BED 99C8
8BEE 99D2
8BEF 5177
8BF0 611A
8BF1 865E
8BF2 55B0
8BF3 7A7A
8BF4 5076
8BF5 5BD3
8BF6 9047
8BF7 9685
8BF8 4E32
8BF9 6ADB
8BFA 91E7
8BFB 5C51
8BFC 5C48
8C40 6398
8C41 7A9F
8C42 6C93
8C43 9774
8C44 8F61
8C45 7AAA
8C46 718A
8C47 9688
8C48 7C82
8C49 6817
8C4A 7E70
8C4B 6851
8C4C 936C
8C4D 52F2
8C4E 541B
8C4F 85AB
8C50 8A13
8C51 7FA4
8C52 8ECD
8C53 90E1
8C54 5366
8C55 8888
8C56 7941
8C57 4FC2
8C58 50BE
8C59 5211
8C5A 5144
8C5B 5553
8C5C 572D
8C5D 73EA
8C5E 578B
8C5F 5951
8C60 5F62
8C61 5F84
8C62 6075
8C63 6176
8C64 6167
8C65 61A9
8C66 63B2
8C67 643A
8C68 656C
8C69 666F
8C6A 6842
8C6B 6E13
8C6C 7566
8C6D 7A3D
8C6E 7CFB
8C6F 7D4C
8C70 7D99
8C71 7E4B
8C72 7F6B
8C73 830E
8C74 834A
8C75 86CD
8C76 8A08
8C77 8A63
8C78 8B66
8C79 8EFD
8C7A 981A
8C7B 9D8F
8C7C 82B8
8C7D 8FCE
8C7E 9BE8
8C80 5287
8C81 621F
8C82 6483
8C83 6FC0
8C84 9699
8C85 6841
8C86 5091
8C87 6B20
8C88 6C7A
8C89 6F54
8C8A 7A74
8C8B 7D50
8C8C 8840
8C8D 8A23
8C8E 6708
8C8F 4EF6
8C90 5039
8C91 5026
8C92 5065
8C93 517C
8C94 5238
8C95 5263
8C96 55A7
8C97 570F
8C98 5805
8C99 5ACC
8C9A 5EFA
8C9B 61B2
8C9C 61F8
8C9D 62F3
8C9E 6372
8C9F 691C
8CA0 6A29
8CA1 727D
8CA2 72AC
8CA3 732E
8CA4 7814
8CA5 786F
8CA6 7D79
8CA7 770C
8CA8 80A9
8CA9 898B
8CAA 8B19
8CAB 8CE2
8CAC 8ED2
8CAD 9063
8CAE 9375
8CAF 967A
8CB0 9855
8CB1 9A13
8CB2 9E78
8CB3 5143
8CB4 539F
8CB5 53B3
8CB6 5E7B
8CB7 5F26
8CB8 6E1B
8CB9 6E90
8CBA 7384
8CBB 73FE
8CBC 7D43
8CBD 8237
8CBE 8A00
8CBF 8AFA
8CC0 9650
8CC1 4E4E
8CC2 500B
8CC3 53E4
8CC4 547C
8CC5 56FA
8CC6 59D1
8CC7 5B64
8CC8 5DF1
8CC9 5EAB
8CCA 5F27
8CCB 6238
8CCC 6545
8CCD 67AF
8CCE 6E56
8CCF 72D0
8CD0 7CCA
8CD1 88B4
8CD2 80A1
8CD3 80E1
8CD4 83F0
8CD5 864E
8CD6 8A87
8CD7 8DE8
8CD8 9237
8CD9 96C7
8CDA 9867
8CDB 9F13
8CDC 4E94
8CDD 4E92
8CDE 4F0D
8CDF 5348
8CE0 5449
8CE1 543E
8CE2 5A2F
8CE3 5F8C
8CE4 5FA1
8CE5 609F
8CE6 68A7
8CE7 6A8E
8CE8 745A
8CE9 7881
8CEA 8A9E
8CEB 8AA4
8CEC 8B77
8CED 9190
8CEE 4E5E
8CEF 9BC9
8CF0 4EA4
8CF1 4F7C
8CF2 4FAF
8CF3 5019
8CF4 5016
8CF5 5149
8CF6 516C
8CF7 529F
8CF8 52B9
8CF9 52FE
8CFA 539A
8CFB 53E3
8CFC 5411
8D40 540E
8D41 5589
8D42 5751
8D43 57A2
8D44 597D
8D45 5B54
8D46 5B5D
8D47 5B8F
8D48 5DE5
8D49 5DE7
8D4A 5DF7
8D4B 5E78
8D4C 5E83
8D4D 5E9A
8D4E 5EB7
8D4F 5F18
8D50 6052
8D51 614C
8D52 6297
8D53 62D8
8D54 63A7
8D55 653B
8D56 6602
8D57 6643
8D58 66F4
8D59 676D
8D5A 6821
8D5B 6897
8D5C 69CB
8D5D 6C5F
8D5E 6D2A
8D5F 6D69
8D60 6E2F
8D61 6E9D
8D62 7532
8D63 7687
8D64 786C
8D65 7A3F
8D66 7CE0
8D67 7D05
8D68 7D18
8D69 7D5E
8D6A 7DB1
8D6B 8015
8D6C 8003
8D6D 80AF
8D6E 80B1
8D6F 8154
8D70 818F
8D71 822A
8D72 8352
8D73 884C
8D74 8861
8D75 8B1B
8D76 8CA2
8D77 8CFC
8D78 90CA
8D79 9175
8D7A 9271
8D7B 783F
8D7C 92FC
8D7D 95A4
8D7E 964D
8D80 9805
8D81 9999
8D82 9AD8
8D83 9D3B
8D84 525B
8D85 52AB
8D86 53F7
8D87 5408
8D88 58D5
8D89 62F7
8D8A 6FE0
8D8B 8C6A
8D8C 8F5F
8D8D 9EB9
8D8E 514B
8D8F 523B
8D90 544A
8D91 56FD
8D92 7A40
8D93 9177
8D94 9D60
8D95 9ED2
8D96 7344
8D97 6F09
8D98 8170
8D99 7511
8D9A 5FFD
8D9B 60DA
8D9C 9AA8
8D9D 72DB
8D9E 8FBC
8D9F 6B64
8DA0 9803
8DA1 4ECA
8DA2 56F0
8DA3 5764
8DA4 58BE
8DA5 5A5A
8DA6 6068
8DA7 61C7
8DA8 660F
8DA9 6606
8DAA 6839
8DAB 68B1
8DAC 6DF7
8DAD 75D5
8DAE 7D3A
8DAF 826E
8DB0 9B42
8DB1 4E9B
8DB2 4F50
8DB3 53C9
8DB4 5506
8DB5 5D6F
8DB6 5DE6
8DB7 5DEE
8DB8 67FB
8DB9 6C99
8DBA 7473
8DBB 7802
8DBC 8A50
8DBD 9396
8DBE 88DF
8DBF 5750
8DC0 5EA7
8DC1 632B
8DC2 50B5
8DC3 50AC
8DC4 518D
8DC5 6700
8DC6 54C9
8DC7 585E
8DC8 59BB
8DC9 5BB0
8DCA 5F69
8DCB 624D
8DCC 63A1
8DCD 683D
8DCE 6B73
8DCF 6E08
8DD0 707D
8DD1 91C7
8DD2 7280
8DD3 7815
8DD4 7826
8DD5 796D
8DD6 658E
8DD7 7D30
8DD8 83DC
8DD9 88C1
8DDA 8F09
8DDB 969B
8DDC 5264
8DDD 5728
8DDE 6750
8DDF 7F6A
8DE0 8CA1
8DE1 51B4
8DE2 5742
8DE3 962A
8DE4 583A
8DE5 698A
8DE6 80B4
8DE7 54B2
8DE8 5D0E
8DE9 57FC
8DEA 7895
8DEB 9DFA
8DEC 4F5C
8DED 524A
8DEE 548B
8DEF 643E
8DF0 6628
8DF1 6714
8DF2 67F5
8DF3 7A84
8DF4 7B56
8DF5 7D22
8DF6 932F
8DF7 685C
8DF8 9BAD
8DF9 7B39
8DFA 5319
8DFB 518A
8DFC 5237
8E40 5BDF
8E41 62F6
8E42 64AE
8E43 64E6
8E44 672D
8E45 6BBA
8E46 85A9
8E47 96D1
8E48 7690
8E49 9BD6
8E4A 634C
8E4B 9306
8E4C 9BAB
8E4D 76BF
8E4E 6652
8E4F 4E09
8E50 5098
8E51 53C2
8E52 5C71
8E53 60E8
8E54 6492
8E55 6563
8E56 685F
8E57 71E6
8E58 73CA
8E59 7523
8E5A 7B97
8E5B 7E82
8E5C 8695
8E5D 8B83
8E5E 8CDB
8E5F 9178
8E60 9910
8E61 65AC
8E62 66AB
8E63 6B8B
8E64 4ED5
8E65 4ED4
8E66 4F3A
8E67 4F7F
8E68 523A
8E69 53F8
8E6A 53F2
8E6B 55E3
8E6C 56DB
8E6D 58EB
8E6E 59CB
8E6F 59C9
8E70 59FF
8E71 5B50
8E72 5C4D
8E73 5E02
8E74 5E2B
8E75 5FD7
8E76 601D
8E77 6307
8E78 652F
8E79 5B5C
8E7A 65AF
8E7B 65BD
8E7C 65E8
8E7D 679D
8E7E 6B62
8E80 6B7B
8E81 6C0F
8E82 7345
8E83 7949
8E84 79C1
8E85 7CF8
8E86 7D19
8E87 7D2B
8E88 80A2
8E89 8102
8E8A 81F3
8E8B 8996
8E8C 8A5E
8E8D 8A69
8E8E 8A66
8E8F 8A8C
8E90 8AEE
8E91 8CC7
8E92 8CDC
8E93 96CC
8E94 98FC
8E95 6B6F
8E96 4E8B
8E97 4F3C
8E98 4F8D
8E99 5150
8E9A 5B57
8E9B 5BFA
8E9C 6148
8E9D 6301
8E9E 6642
8E9F 6B21
8EA0 6ECB
8EA1 6CBB
8EA2 723E
8EA3 74BD
8EA4 75D4
8EA5 78C1
8EA6 793A
8EA7 800C
8EA8 8033
8EA9 81EA
8EAA 8494
8EAB 8F9E
8EAC 6C50
8EAD 9E7F
8EAE 5F0F
8EAF 8B58
8EB0 9D2B
8EB1 7AFA
8EB2 8EF8
8EB3 5B8D
8EB4 96EB
8EB5 4E03
8EB6 53F1
8EB7 57F7
8EB8 5931
8EB9 5AC9
8EBA 5BA4
8EBB 6089
8EBC 6E7F
8EBD 6F06
8EBE 75BE
8EBF 8CEA
8EC0 5B9F
8EC1 8500
8EC2 7BE0
8EC3 5072
8EC4 67F4
8EC5 829D
8EC6 5C61
8EC7 854A
8EC8 7E1E
8EC9 820E
8ECA 5199
8ECB 5C04
8ECC 6368
8ECD 8D66
8ECE 659C
8ECF 716E
8ED0 793E
8ED1 7D17
8ED2 8005
8ED3 8B1D
8ED4 8ECA
8ED5 906E
8ED6 86C7
8ED7 90AA
8ED8 501F
8ED9 52FA
8EDA 5C3A
8EDB 6753
8EDC 707C
8EDD 7235
8EDE 914C
8EDF 91C8
8EE0 932B
8EE1 82E5
8EE2 5BC2
8EE3 5F31
8EE4 60F9
8EE5 4E3B
8EE6 53D6
8EE7 5B88
8EE8 624B
8EE9 6731
8EEA 6B8A
8EEB 72E9
8EEC 73E0
8EED 7A2E
8EEE 816B
8EEF 8DA3
8EF0 9152
8EF1 9996
8EF2 5112
8EF3 53D7
8EF4 546A
8EF5 5BFF
8EF6 6388
8EF7 6A39
8EF8 7DAC
8EF9 9700
8EFA 56DA
8EFB 53CE
8EFC 5468
8F40 5B97
8F41 5C31
8F42 5DDE
8F43 4FEE
8F44 6101
8F45 62FE
8F46 6D32
8F47 79C0
8F48 79CB
8F49 7D42
8F4A 7E4D
8F4B 7FD2
8F4C 81ED
8F4D 821F
8F4E 8490
8F4F 8846
8F50 8972
8F51 8B90
8F52 8E74
8F53 8F2F
8F54 9031
8F55 914B
8F56 916C
8F57 96C6
8F58 919C
8F59 4EC0
8F5A 4F4F
8F5B 5145
8F5C 5341
8F5D 5F93
8F5E 620E
8F5F 67D4
8F60 6C41
8F61 6E0B
8F62 7363
8F63 7E26
8F64 91CD
8F65 9283
8F66 53D4
8F67 5919
8F68 5BBF
8F69 6DD1
8F6A 795D
8F6B 7E2E
8F6C 7C9B
8F6D 587E
8F6E 719F
8F6F 51FA
8F70 8853
8F71 8FF0
8F72 4FCA
8F73 5CFB
8F74 6625
8F75 77AC
8F76 7AE3
8F77 821C
8F78 99FF
8F79 51C6
8F7A 5FAA
8F7B 65EC
8F7C 696F
8F7D 6B89
8F7E 6DF3
8F80 6E96
8F81 6F64
8F82 76FE
8F83 7D14
8F84 5DE1
8F85 9075
8F86 9187
8F87 9806
8F88 51E6
8F89 521D
8F8A 6240
8F8B 6691
8F8C 66D9
8F8D 6E1A
8F8E 5EB6
8F8F 7DD2
8F90 7F72
8F91 66F8
8F92 85AF
8F93 85F7
8F94 8AF8
8F95 52A9
8F96 53D9
8F97 5973
8F98 5E8F
8F99 5F90
8F9A 6055
8F9B 92E4
8F9C 9664
8F9D 50B7
8F9E 511F
8F9F 52DD
8FA0 5320
8FA1 5347
8FA2 53EC
8FA3 54E8
8FA4 5546
8FA5 5531
8FA6 5617
8FA7 5968
8FA8 59BE
8FA9 5A3C
8FAA 5BB5
8FAB 5C06
8FAC 5C0F
8FAD 5C11
8FAE 5C1A
8FAF 5E84
8FB0 5E8A
8FB1 5EE0
8FB2 5F70
8FB3 627F
8FB4 6284
8FB5 62DB
8FB6 638C
8FB7 6377
8FB8 6607
8FB9 660C
8FBA 662D
8FBB 6676
8FBC 677E
8FBD 68A2
8FBE 6A1F
8FBF 6A35
8FC0 6CBC
8FC1 6D88
8FC2 6E09
8FC3 6E58
8FC4 713C
8FC5 7126
8FC6 7167
8FC7 75C7
8FC8 7701
8FC9 785D
8FCA 7901
8FCB 7965
8FCC 79F0
8FCD 7AE0
8FCE 7B11
8FCF 7CA7
8FD0 7D39
8FD1 8096
8FD2 83D6
8FD3 848B
8FD4 8549
8FD5 885D
8FD6 88F3
8FD7 8A1F
8FD8 8A3C
8FD9 8A54
8FDA 8A73
8FDB 8C61
8FDC 8CDE
8FDD 91A4
8FDE 9266
8FDF 937E
8FE0 9418
8FE1 969C
8FE2 9798
8FE3 4E0A
8FE4 4E08
8FE5 4E1E
8FE6 4E57
8FE7 5197
8FE8 5270
8FE9 57CE
8FEA 5834
8FEB 58CC
8FEC 5B22
8FED 5E38
8FEE 60C5
8FEF 64FE
8FF0 6761
8FF1 6756
8FF2 6D44
8FF3 72B6
8FF4 7573
8FF5 7A63
8FF6 84B8
8FF7 8B72
8FF8 91B8
8FF9 9320
8FFA 5631
8FFB 57F4
8FFC 98FE
9040 62ED
9041 690D
9042 6B96
9043 71ED
9044 7E54
9045 8077
9046 8272
9047 89E6
9048 98DF
9049 8755
904A 8FB1
904B 5C3B
904C 4F38
904D 4FE1
904E 4FB5
904F 5507
9050 5A20
9051 5BDD
9052 5BE9
9053 5FC3
9054 614E
9055 632F
9056 65B0
9057 664B
9058 68EE
9059 699B
905A 6D78
905B 6DF1
905C 7533
905D 75B9
905E 771F
905F 795E
9060 79E6
9061 7D33
9062 81E3
9063 82AF
9064 85AA
9065 89AA
9066 8A3A
9067 8EAB
9068 8F9B
9069 9032
906A 91DD
906B 9707
906C 4EBA
906D 4EC1
906E 5203
906F 5875
9070 58EC
9071 5C0B
9072 751A
9073 5C3D
9074 814E
9075 8A0A
9076 8FC5
9077 9663
9078 976D
9079 7B25
907A 8ACF
907B 9808
907C 9162
907D 56F3
907E 53A8
9080 9017
9081 5439
9082 5782
9083 5E25
9084 63A8
9085 6C34
9086 708A
9087 7761
9088 7C8B
9089 7FE0
908A 8870
908B 9042
908C 9154
908D 9310
908E 9318
908F 968F
9090 745E
9091 9AC4
9092 5D07
9093 5D69
9094 6570
9095 67A2
9096 8DA8
9097 96DB
9098 636E
9099 6749
909A 6919
909B 83C5
909C 9817
909D 96C0
909E 88FE
909F 6F84
90A0 647A
90A1 5BF8
90A2 4E16
90A3 702C
90A4 755D
90A5 662F
90A6 51C4
90A7 5236
90A8 52E2
90A9 59D3
90AA 5F81
90AB 6027
90AC 6210
90AD 653F
90AE 6574
90AF 661F
90B0 6674
90B1 68F2
90B2 6816
90B3 6B63
90B4 6E05
90B5 7272
90B6 751F
90B7 76DB
90B8 7CBE
90B9 8056
90BA 58F0
90BB 88FD
90BC 897F
90BD 8AA0
90BE 8A93
90BF 8ACB
90C0 901D
90C1 9192
90C2 9752
90C3 9759
90C4 6589
90C5 7A0E
90C6 8106
90C7 96BB
90C8 5E2D
90C9 60DC
90CA 621A
90CB 65A5
90CC 6614
90CD 6790
90CE 77F3
90CF 7A4D
90D0 7C4D
90D1 7E3E
90D2 810A
90D3 8CAC
90D4 8D64
90D5 8DE1
90D6 8E5F
90D7 78A9
90D8 5207
90D9 62D9
90DA 63A5
90DB 6442
90DC 6298
90DD 8A2D
90DE 7A83
90DF 7BC0
90E0 8AAC
90E1 96EA
90E2 7D76
90E3 820C
90E4 8749
90E5 4ED9
90E6 5148
90E7 5343
90E8 5360
90E9 5BA3
90EA 5C02
90EB 5C16
90EC 5DDD
90ED 6226
90EE 6247
90EF 64B0
90F0 6813
90F1 6834
90F2 6CC9
90F3 6D45
90F4 6D17
90F5 67D3
90F6 6F5C
90F7 714E
90F8 717D
90F9 65CB
90FA 7A7F
90FB 7BAD
90FC 7DDA
9140 7E4A
9141 7FA8
9142 817A
9143 821B
9144 8239
9145 85A6
9146 8A6E
9147 8CCE
9148 8DF5
9149 9078
914A 9077
914B 92AD
914C 9291
914D 9583
914E 9BAE
914F 524D
9150 5584
9151 6F38
9152 7136
9153 5168
9154 7985
9155 7E55
9156 81B3
9157 7CCE
9158 564C
9159 5851
915A 5CA8
915B 63AA
915C 66FE
915D 66FD
915E 695A
915F 72D9
9160 758F
9161 758E
9162 790E
9163 7956
9164 79DF
9165 7C97
9166 7D20
9167 7D44
9168 8607
9169 8A34
916A 963B
916B 9061
916C 9F20
916D 50E7
916E 5275
916F 53CC
9170 53E2
9171 5009
9172 55AA
9173 58EE
9174 594F
9175 723D
9176 5B8B
9177 5C64
9178 531D
9179 60E3
917A 60F3
917B 635C
917C 6383
917D 633F
917E 63BB
9180 64CD
9181 65E9
9182 66F9
9183 5DE3
9184 69CD
9185 69FD
9186 6F15
9187 71E5
9188 4E89
9189 75E9
918A 76F8
918B 7A93
918C 7CDF
918D 7DCF
918E 7D9C
918F 8061
9190 8349
9191 8358
9192 846C
9193 84BC
9194 85FB
9195 88C5
9196 8D70
9197 9001
9198 906D
9199 9397
919A 971C
919B 9A12
919C 50CF
919D 5897
919E 618E
919F 81D3
91A0 8535
91A1 8D08
91A2 9020
91A3 4FC3
91A4 5074
91A5 5247
91A6 5373
91A7 606F
91A8 6349
91A9 675F
91AA 6E2C
91AB 8DB3
91AC 901F
91AD 4FD7
91AE 5C5E
91AF 8CCA
91B0 65CF
91B1 7D9A
91B2 5352
91B3 8896
91B4 5176
91B5 63C3
91B6 5B58
91B7 5B6B
91B8 5C0A
91B9 640D
91BA 6751
91BB 905C
91BC 4ED6
91BD 591A
91BE 592A
91BF 6C70
91C0 8A51
91C1 553E
91C2 5815
91C3 59A5
91C4 60F0
91C5 6253
91C6 67C1
91C7 8235
91C8 6955
91C9 9640
91CA 99C4
91CB 9A28
91CC 4F53
91CD 5806
91CE 5BFE
91CF 8010
91D0 5CB1
91D1 5E2F
91D2 5F85
91D3 6020
91D4 614B
91D5 6234
91D6 66FF
91D7 6CF0
91D8 6EDE
91D9 80CE
91DA 817F
91DB 82D4
91DC 888B
91DD 8CB8
91DE 9000
91DF 902E
91E0 968A
91E1 9EDB
91E2 9BDB
91E3 4EE3
91E4 53F0
91E5 5927
91E6 7B2C
91E7 918D
91E8 984C
91E9 9DF9
91EA 6EDD
91EB 7027
91EC 5353
91ED 5544
91EE 5B85
91EF 6258
91F0 629E
91F1 62D3
91F2 6CA2
91F3 6FEF
91F4 7422
91F5 8A17
91F6 9438
91F7 6FC1
91F8 8AFE
91F9 8338
91FA 51E7
91FB 86F8
91FC 53EA
9240 53E9
9241 4F46
9242 9054
9243 8FB0
9244 596A
9245 8131
9246 5DFD
9247 7AEA
9248 8FBF
9249 68DA
924A 8C37
924B 72F8
924C 9C48
924D 6A3D
924E 8AB0
924F 4E39
9250 5358
9251 5606
9252 5766
9253 62C5
9254 63A2
9255 65E6
9256 6B4E
9257 6DE1
9258 6E5B
9259 70AD
925A 77ED
925B 7AEF
925C 7BAA
925D 7DBB
925E 803D
925F 80C6
9260 86CB
9261 8A95
9262 935B
9263 56E3
9264 58C7
9265 5F3E
9266 65AD
9267 6696
9268 6A80
9269 6BB5
926A 7537
926B 8AC7
926C 5024
926D 77E5
926E 5730
926F 5F1B
9270 6065
9271 667A
9272 6C60
9273 75F4
9274 7A1A
9275 7F6E
9276 81F4
9277 8718
9278 9045
9279 99B3
927A 7BC9
927B 755C
927C 7AF9
927D 7B51
927E 84C4
9280 9010
9281 79E9
9282 7A92
9283 8336
9284 5AE1
9285 7740
9286 4E2D
9287 4EF2
9288 5B99
9289 5FE0
928A 62BD
928B 663C
928C 67F1
928D 6CE8
928E 866B
928F 8877
9290 8A3B
9291 914E
9292 92F3
9293 99D0
9294 6A17
9295 7026
9296 732A
9297 82E7
9298 8457
9299 8CAF
929A 4E01
929B 5146
929C 51CB
929D 558B
929E 5BF5
929F 5E16
92A0 5E33
92A1 5E81
92A2 5F14
92A3 5F35
92A4 5F6B
92A5 5FB4
92A6 61F2
92A7 6311
92A8 66A2
92A9 671D
92AA 6F6E
92AB 7252
92AC 753A
92AD 773A
92AE 8074
92AF 8139
92B0 8178
92B1 8776
92B2 8ABF
92B3 8ADC
92B4 8D85
92B5 8DF3
92B6 929A
92B7 9577
92B8 9802
92B9 9CE5
92BA 52C5
92BB 6357
92BC 76F4
92BD 6715
92BE 6C88
92BF 73CD
92C0 8CC3
92C1 93AE
92C2 9673
92C3 6D25
92C4 589C
92C5 690E
92C6 69CC
92C7 8FFD
92C8 939A
92C9 75DB
92CA 901A
92CB 585A
92CC 6802
92CD 63B4
92CE 69FB
92CF 4F43
92D0 6F2C
92D1 67D8
92D2 8FBB
92D3 8526
92D4 7DB4
92D5 9354
92D6 693F
92D7 6F70
92D8 576A
92D9 58F7
92DA 5B2C
92DB 7D2C
92DC 722A
92DD 540A
92DE 91E3
92DF 9DB4
92E0 4EAD
92E1 4F4E
92E2 505C
92E3 5075
92E4 5243
92E5 8C9E
92E6 5448
92E7 5824
92E8 5B9A
92E9 5E1D
92EA 5E95
92EB 5EAD
92EC 5EF7
92ED 5F1F
92EE 608C
92EF 62B5
92F0 633A
92F1 63D0
92F2 68AF
92F3 6C40
92F4 7887
92F5 798E
92F6 7A0B
92F7 7DE0
92F8 8247
92F9 8A02
92FA 8AE6
92FB 8E44
92FC 9013
9340 90B8
9341 912D
9342 91D8
9343 9F0E
9344 6CE5
9345 6458
9346 64E2
9347 6575
9348 6EF4
9349 7684
934A 7B1B
934B 9069
934C 93D1
934D 6EBA
934E 54F2
934F 5FB9
9350 64A4
9351 8F4D
9352 8FED
9353 9244
9354 5178
9355 586B
9356 5929
9357 5C55
9358 5E97
9359 6DFB
935A 7E8F
935B 751C
935C 8CBC
935D 8EE2
935E 985B
935F 70B9
9360 4F1D
9361 6BBF
9362 6FB1
9363 7530
9364 96FB
9365 514E
9366 5410
9367 5835
9368 5857
9369 59AC
936A 5C60
936B 5F92
936C 6597
936D 675C
936E 6E21
936F 767B
9370 83DF
9371 8CED
9372 9014
9373 90FD
9374 934D
9375 7825
9376 783A
9377 52AA
9378 5EA6
9379 571F
937A 5974
937B 6012
937C 5012
937D 515A
937E 51AC
9380 51CD
9381 5200
9382 5510
9383 5854
9384 5858
9385 5957
9386 5B95
9387 5CF6
9388 5D8B
9389 60BC
938A 6295
938B 642D
938C 6771
938D 6843
938E 68BC
938F 68DF
9390 76D7
9391 6DD8
9392 6E6F
9393 6D9B
9394 706F
9395 71C8
9396 5F53
9397 75D8
9398 7977
9399 7B49
939A 7B54
939B 7B52
939C 7CD6
939D 7D71
939E 5230
939F 8463
93A0 8569
93A1 85E4
93A2 8A0E
93A3 8B04
93A4 8C46
93A5 8E0F
93A6 9003
93A7 900F
93A8 9419
93A9 9676
93AA 982D
93AB 9A30
93AC 95D8
93AD 50CD
93AE 52D5
93AF 540C
93B0 5802
93B1 5C0E
93B2 61A7
93B3 649E
93B4 6D1E
93B5 77B3
93B6 7AE5
93B7 80F4
93B8 8404
93B9 9053
93BA 9285
93BB 5CE0
93BC 9D07
93BD 533F
93BE 5F97
93BF 5FB3
93C0 6D9C
93C1 7279
93C2 7763
93C3 79BF
93C4 7BE4
93C5 6BD2
93C6 72EC
93C7 8AAD
93C8 6803
93C9 6A61
93CA 51F8
93CB 7A81
93CC 6934
93CD 5C4A
93CE 9CF6
93CF 82EB
93D0 5BC5
93D1 9149
93D2 701E
93D3 5678
93D4 5C6F
93D5 60C7
93D6 6566
93D7 6C8C
93D8 8C5A
93D9 9041
93DA 9813
93DB 5451
93DC 66C7
93DD 920D
93DE 5948
93DF 90A3
93E0 5185
93E1 4E4D
93E2 51EA
93E3 8599
93E4 8B0E
93E5 7058
93E6 637A
93E7 934B
93E8 6962
93E9 99B4
93EA 7E04
93EB 7577
93EC 5357
93ED 6960
93EE 8EDF
93EF 96E3
93F0 6C5D
93F1 4E8C
93F2 5C3C
93F3 5F10
93F4 8FE9
93F5 5302
93F6 8CD1
93F7 8089
93F8 8679
93F9 5EFF
93FA 65E5
93FB 4E73
93FC 5165
9440 5982
9441 5C3F
9442 97EE
9443 4EFB
9444 598A
9445 5FCD
9446 8A8D
9447 6FE1
9448 79B0
9449 7962
944A 5BE7
944B 8471
944C 732B
944D 71B1
944E 5E74
944F 5FF5
9450 637B
9451 649A
9452 71C3
9453 7C98
9454 4E43
9455 5EFC
9456 4E4B
9457 57DC
9458 56A2
9459 60A9
945A 6FC3
945B 7D0D
945C 80FD
945D 8133
945E 81BF
945F 8FB2
9460 8997
9461 86A4
9462 5DF4
9463 628A
9464 64AD
9465 8987
9466 6777
9467 6CE2
9468 6D3E
9469 7436
946A 7834
946B 5A46
946C 7F75
946D 82AD
946E 99AC
946F 4FF3
9470 5EC3
9471 62DD
9472 6392
9473 6557
9474 676F
9475 76C3
9476 724C
9477 80CC
9478 80BA
9479 8F29
947A 914D
947B 500D
947C 57F9
947D 5A92
947E 6885
9480 6973
9481 7164
9482 72FD
9483 8CB7
9484 58F2
9485 8CE0
9486 966A
9487 9019
9488 877F
9489 79E4
948A 77E7
948B 8429
948C 4F2F
948D 5265
948E 535A
948F 62CD
9490 67CF
9491 6CCA
9492 767D
9493 7B94
9494 7C95
9495 8236
9496 8584
9497 8FEB
9498 66DD
9499 6F20
949A 7206
949B 7E1B
949C 83AB
949D 99C1
949E 9EA6
949F 51FD
94A0 7BB1
94A1 7872
94A2 7BB8
94A3 8087
94A4 7B48
94A5 6AE8
94A6 5E61
94A7 808C
94A8 7551
94A9 7560
94AA 516B
94AB 9262
94AC 6E8C
94AD 767A
94AE 9197
94AF 9AEA
94B0 4F10
94B1 7F70
94B2 629C
94B3 7B4F
94B4 95A5
94B5 9CE9
94B6 567A
94B7 5859
94B8 86E4
94B9 96BC
94BA 4F34
94BB 5224
94BC 534A
94BD 53CD
94BE 53DB
94BF 5E06
94C0 642C
94C1 6591
94C2 677F
94C3 6C3E
94C4 6C4E
94C5 7248
94C6 72AF
94C7 73ED
94C8 7554
94C9 7E41
94CA 822C
94CB 85E9
94CC 8CA9
94CD 7BC4
94CE 91C6
94CF 7169
94D0 9812
94D1 98EF
94D2 633D
94D3 6669
94D4 756A
94D5 76E4
94D6 78D0
94D7 8543
94D8 86EE
94D9 532A
94DA 5351
94DB 5426
94DC 5983
94DD 5E87
94DE 5F7C
94DF 60B2
94E0 6249
94E1 6279
94E2 62AB
94E3 6590
94E4 6BD4
94E5 6CCC
94E6 75B2
94E7 76AE
94E8 7891
94E9 79D8
94EA 7DCB
94EB 7F77
94EC 80A5
94ED 88AB
94EE 8AB9
94EF 8CBB
94F0 907F
94F1 975E
94F2 98DB
94F3 6A0B
94F4 7C38
94F5 5099
94F6 5C3E
94F7 5FAE
94F8 6787
94F9 6BD8
94FA 7435
94FB 7709
94FC 7F8E
9540 9F3B
9541 67CA
9542 7A17
9543 5339
9544 758B
9545 9AED
9546 5F66
9547 819D
9548 83F1
9549 8098
954A 5F3C
954B 5FC5
954C 7562
954D 7B46
954E 903C
954F 6867
9550 59EB
9551 5A9B
9552 7D10
9553 767E
9554 8B2C
9555 4FF5
9556 5F6A
9557 6A19
9558 6C37
9559 6F02
955A 74E2
955B 7968
955C 8868
955D 8A55
955E 8C79
955F 5EDF
9560 63CF
9561 75C5
9562 79D2
9563 82D7
9564 9328
9565 92F2
9566 849C
9567 86ED
9568 9C2D
9569 54C1
956A 5F6C
956B 658C
956C 6D5C
956D 7015
956E 8CA7
956F 8CD3
9570 983B
9571 654F
9572 74F6
9573 4E0D
9574 4ED8
9575 57E0
9576 592B
9577 5A66
9578 5BCC
9579 51A8
957A 5E03
957B 5E9C
957C 6016
957D 6276
957E 6577
9580 65A7
9581 666E
9582 6D6E
9583 7236
9584 7B26
9585 8150
9586 819A
9587 8299
9588 8B5C
9589 8CA0
958A 8CE6
958B 8D74
958C 961C
958D 9644
958E 4FAE
958F 64AB
9590 6B66
9591 821E
9592 8461
9593 856A
9594 90E8
9595 5C01
9596 6953
9597 98A8
9598 847A
9599 8557
959A 4F0F
959B 526F
959C 5FA9
959D 5E45
959E 670D
959F 798F
95A0 8179
95A1 8907
95A2 8986
95A3 6DF5
95A4 5F17
95A5 6255
95A6 6CB8
95A7 4ECF
95A8 7269
95A9 9B92
95AA 5206
95AB 543B
95AC 5674
95AD 58B3
95AE 61A4
95AF 626E
95B0 711A
95B1 596E
95B2 7C89
95B3 7CDE
95B4 7D1B
95B5 96F0
95B6 6587
95B7 805E
95B8 4E19
95B9 4F75
95BA 5175
95BB 5840
95BC 5E63
95BD 5E73
95BE 5F0A
95BF 67C4
95C0 4E26
95C1 853D
95C2 9589
95C3 965B
95C4 7C73
95C5 9801
95C6 50FB
95C7 58C1
95C8 7656
95C9 78A7
95CA 5225
95CB 77A5
95CC 8511
95CD 7B86
95CE 504F
95CF 5909
95D0 7247
95D1 7BC7
95D2 7DE8
95D3 8FBA
95D4 8FD4
95D5 904D
95D6 4FBF
95D7 52C9
95D8 5A29
95D9 5F01
95DA 97AD
95DB 4FDD
95DC 8217
95DD 92EA
95DE 5703
95DF 6355
95E0 6B69
95E1 752B
95E2 88DC
95E3 8F14
95E4 7A42
95E5 52DF
95E6 5893
95E7 6155
95E8 620A
95E9 66AE
95EA 6BCD
95EB 7C3F
95EC 83E9
95ED 5023
95EE 4FF8
95EF 5305
95F0 5446
95F1 5831
95F2 5949
95F3 5B9D
95F4 5CF0
95F5 5CEF
95F6 5D29
95F7 5E96
95F8 62B1
95F9 6367
95FA 653E
95FB 65B9
95FC 670B
9640 6CD5
9641 6CE1
9642 70F9
9643 7832
9644 7E2B
9645 80DE
9646 82B3
9647 840C
9648 84EC
9649 8702
964A 8912
964B 8A2A
964C 8C4A
964D 90A6
964E 92D2
964F 98FD
9650 9CF3
9651 9D6C
9652 4E4F
9653 4EA1
9654 508D
9655 5256
9656 574A
9657 59A8
9658 5E3D
9659 5FD8
965A 5FD9
965B 623F
965C 66B4
965D 671B
965E 67D0
965F 68D2
9660 5192
9661 7D21
9662 80AA
9663 81A8
9664 8B00
9665 8C8C
9666 8CBF
9667 927E
9668 9632
9669 5420
966A 982C
966B 5317
966C 50D5
966D 535C
966E 58A8
966F 64B2
9670 6734
9671 7267
9672 7766
9673 7A46
9674 91E6
9675 52C3
9676 6CA1
9677 6B86
9678 5800
9679 5E4C
967A 5954
967B 672C
967C 7FFB
967D 51E1
967E 76C6
9680 6469
9681 78E8
9682 9B54
9683 9EBB
9684 57CB
9685 59B9
9686 6627
9687 679A
9688 6BCE
9689 54E9
968A 69D9
968B 5E55
968C 819C
968D 6795
968E 9BAA
968F 67FE
9690 9C52
9691 685D
9692 4EA6
9693 4FE3
9694 53C8
9695 62B9
9696 672B
9697 6CAB
9698 8FC4
9699 4FAD
969A 7E6D
969B 9EBF
969C 4E07
969D 6162
969E 6E80
969F 6F2B
96A0 8513
96A1 5473
96A2 672A
96A3 9B45
96A4 5DF3
96A5 7B95
96A6 5CAC
96A7 5BC6
96A8 871C
96A9 6E4A
96AA 84D1
96AB 7A14
96AC 8108
96AD 5999
96AE 7C8D
96AF 6C11
96B0 7720
96B1 52D9
96B2 5922
96B3 7121
96B4 725F
96B5 77DB
96B6 9727
96B7 9D61
96B8 690B
96B9 5A7F
96BA 5A18
96BB 51A5
96BC 540D
96BD 547D
96BE 660E
96BF 76DF
96C0 8FF7
96C1 9298
96C2 9CF4
96C3 59EA
96C4 725D
96C5 6EC5
96C6 514D
96C7 68C9
96C8 7DBF
96C9 7DEC
96CA 9762
96CB 9EBA
96CC 6478
96CD 6A21
96CE 8302
96CF 5984
96D0 5B5F
96D1 6BDB
96D2 731B
96D3 76F2
96D4 7DB2
96D5 8017
96D6 8499
96D7 5132
96D8 6728
96D9 9ED9
96DA 76EE
96DB 6762
96DC 52FF
96DD 9905
96DE 5C24
96DF 623B
96E0 7C7E
96E1 8CB0
96E2 554F
96E3 60B6
96E4 7D0B
96E5 9580
96E6 5301
96E7 4E5F
96E8 51B6
96E9 591C
96EA 723A
96EB 8036
96EC 91CE
96ED 5F25
96EE 77E2
96EF 5384
96F0 5F79
96F1 7D04
96F2 85AC
96F3 8A33
96F4 8E8D
96F5 9756
96F6 67F3
96F7 85AE
96F8 9453
96F9 6109
96FA 6108
96FB 6CB9
96FC 7652
9740 8AED
9741 8F38
9742 552F
9743 4F51
9744 512A
9745 52C7
9746 53CB
9747 5BA5
9748 5E7D
9749 60A0
974A 6182
974B 63D6
974C 6709
974D 67DA
974E 6E67
974F 6D8C
9750 7336
9751 7337
9752 7531
9753 7950
9754 88D5
9755 8A98
9756 904A
9757 9091
9758 90F5
9759 96C4
975A 878D
975B 5915
975C 4E88
975D 4F59
975E 4E0E
975F 8A89
9760 8F3F
9761 9810
9762 50AD
9763 5E7C
9764 5996
9765 5BB9
9766 5EB8
9767 63DA
9768 63FA
9769 64C1
976A 66DC
976B 694A
976C 69D8
976D 6D0B
976E 6EB6
976F 7194
9770 7528
9771 7AAF
9772 7F8A
9773 8000
9774 8449
9775 84C9
9776 8981
9777 8B21
9778 8E0A
9779 9065
977A 967D
977B 990A
977C 617E
977D 6291
977E 6B32
9780 6C83
9781 6D74
9782 7FCC
9783 7FFC
9784 6DC0
9785 7F85
9786 87BA
9787 88F8
9788 6765
9789 83B1
978A 983C
978B 96F7
978C 6D1B
978D 7D61
978E 843D
978F 916A
9790 4E71
9791 5375
9792 5D50
9793 6B04
9794 6FEB
9795 85CD
9796 862D
9797 89A7
9798 5229
9799 540F
979A 5C65
979B 674E
979C 68A8
979D 7406
979E 7483
979F 75E2
97A0 88CF
97A1 88E1
97A2 91CC
97A3 96E2
97A4 9678
97A5 5F8B
97A6 7387
97A7 7ACB
97A8 844E
97A9 63A0
97AA 7565
97AB 5289
97AC 6D41
97AD 6E9C
97AE 7409
97AF 7559
97B0 786B
97B1 7C92
97B2 9686
97B3 7ADC
97B4 9F8D
97B5 4FB6
97B6 616E
97B7 65C5
97B8 865C
97B9 4E86
97BA 4EAE
97BB 50DA
97BC 4E21
97BD 51CC
97BE 5BEE
97BF 6599
97C0 6881
97C1 6DBC
97C2 731F
97C3 7642
97C4 77AD
97C5 7A1C
97C6 7CE7
97C7 826F
97C8 8AD2
97C9 907C
97CA 91CF
97CB 9675
97CC 9818
97CD 529B
97CE 7DD1
97CF 502B
97D0 5398
97D1 6797
97D2 6DCB
97D3 71D0
97D4 7433
97D5 81E8
97D6 8F2A
97D7 96A3
97D8 9C57
97D9 9E9F
97DA 7460
97DB 5841
97DC 6D99
97DD 7D2F
97DE 985E
97DF 4EE4
97E0 4F36
97E1 4F8B
97E2 51B7
97E3 52B1
97E4 5DBA
97E5 601C
97E6 73B2
97E7 793C
97E8 82D3
97E9 9234
97EA 96B7
97EB 96F6
97EC 970A
97ED 9E97
97EE 9F62
97EF 66A6
97F0 6B74
97F1 5217
97F2 52A3
97F3 70C8
97F4 88C2
97F5 5EC9
97F6 604B
97F7 6190
97F8 6F23
97F9 7149
97FA 7C3E
97FB 7DF4
97FC 806F
9840 84EE
9841 9023
9842 932C
9843 5442
9844 9B6F
9845 6AD3
9846 7089
9847 8CC2
9848 8DEF
9849 9732
984A 52B4
984B 5A41
984C 5ECA
984D 5F04
984E 6717
984F 697C
9850 6994
9851 6D6A
9852 6F0F
9853 7262
9854 72FC
9855 7BED
9856 8001
9857 807E
9858 874B
9859 90CE
985A 516D
985B 9E93
985C 7984
985D 808B
985E 9332
985F 8AD6
9860 502D
9861 548C
9862 8A71
9863 6B6A
9864 8CC4
9865 8107
9866 60D1
9867 67A0
9868 9DF2
9869 4E99
986A 4E98
986B 9C10
986C 8A6B
986D 85C1
986E 8568
986F 6900
9870 6E7E
9871 7897
9872 8155
989F 5F0C
98A0 4E10
98A1 4E15
98A2 4E2A
98A3 4E31
98A4 4E36
98A5 4E3C
98A6 4E3F
98A7 4E42
98A8 4E56
98A9 4E58
98AA 4E82
98AB 4E85
98AC 8C6B
98AD 4E8A
98AE 8212
98AF 5F0D
98B0 4E8E
98B1 4E9E
98B2 4E9F
98B3 4EA0
98B4 4EA2
98B5 4EB0
98B6 4EB3
98B7 4EB6
98B8 4ECE
98B9 4ECD
98BA 4EC4
98BB 4EC6
98BC 4EC2
98BD 4ED7
98BE 4EDE
98BF 4EED
98C0 4EDF
98C1 4EF7
98C2 4F09
98C3 4F5A
98C4 4F30
98C5 4F5B
98C6 4F5D
98C7 4F57
98C8 4F47
98C9 4F76
98CA 4F88
98CB 4F8F
98CC 4F98
98CD 4F7B
98CE 4F69
98CF 4F70
98D0 4F91
98D1 4F6F
98D2 4F86
98D3 4F96
98D4 5118
98D5 4FD4
98D6 4FDF
98D7 4FCE
98D8 4FD8
98D9 4FDB
98DA 4FD1
98DB 4FDA
98DC 4FD0
98DD 4FE4
98DE 4FE5
98DF 501A
98E0 5028
98E1 5014
98E2 502A
98E3 5025
98E4 5005
98E5 4F1C
98E6 4FF6
98E7 5021
98E8 5029
98E9 502C
98EA 4FFE
98EB 4FEF
98EC 5011
98ED 5006
98EE 5043
98EF 5047
98F0 6703
98F1 5055
98F2 5050
98F3 5048
98F4 505A
98F5 5056
98F6 506C
98F7 5078
98F8 5080
98F9 509A
98FA 5085
98FB 50B4
98FC 50B2
9940 50C9
9941 50CA
9942 50B3
9943 50C2
9944 50D6
9945 50DE
9946 50E5
9947 50ED
9948 50E3
9949 50EE
994A 50F9
994B 50F5
994C 5109
994D 5101
994E 5102
994F 5116
9950 5115
9951 5114
9952 511A
9953 5121
9954 513A
9955 5137
9956 513C
9957 513B
9958 513F
9959 5140
995A 5152
995B 514C
995C 5154
995D 5162
995E 7AF8
995F 5169
9960 516A
9961 516E
9962 5180
9963 5182
9964 56D8
9965 518C
9966 5189
9967 518F
9968 5191
9969 5193
996A 5195
996B 5196
996C 51A4
996D 51A6
996E 51A2
996F 51A9
9970 51AA
9971 51AB
9972 51B3
9973 51B1
9974 51B2
9975 51B0
9976 51B5
9977 51BD
9978 51C5
9979 51C9
997A 51DB
997B 51E0
997C 8655
997D 51E9
997E 51ED
9980 51F0
9981 51F5
9982 51FE
9983 5204
9984 520B
9985 5214
9986 520E
9987 5227
9988 522A
9989 522E
998A 5233
998B 5239
998C 524F
998D 5244
998E 524B
998F 524C
9990 525E
9991 5254
9992 526A
9993 5274
9994 5269
9995 5273
9996 527F
9997 527D
9998 528D
9999 5294
999A 5292
999B 5271
999C 5288
999D 5291
999E 8FA8
999F 8FA7
99A0 52AC
99A1 52AD
99A2 52BC
99A3 52B5
99A4 52C1
99A5 52CD
99A6 52D7
99A7 52DE
99A8 52E3
99A9 52E6
99AA 98ED
99AB 52E0
99AC 52F3
99AD 52F5
99AE 52F8
99AF 52F9
99B0 5306
99B1 5308
99B2 7538
99B3 530D
99B4 5310
99B5 530F
99B6 5315
99B7 531A
99B8 5323
99B9 532F
99BA 5331
99BB 5333
99BC 5338
99BD 5340
99BE 5346
99BF 5345
99C0 4E17
99C1 5349
99C2 534D
99C3 51D6
99C4 535E
99C5 5369
99C6 536E
99C7 5918
99C8 537B
99C9 5377
99CA 5382
99CB 5396
99CC 53A0
99CD 53A6
99CE 53A5
99CF 53AE
99D0 53B0
99D1 53B6
99D2 53C3
99D3 7C12
99D4 96D9
99D5 53DF
99D6 66FC
99D7 71EE
99D8 53EE
99D9 53E8
99DA 53ED
99DB 53FA
99DC 5401
99DD 543D
99DE 5440
99DF 542C
99E0 542D
99E1 543C
99E2 542E
99E3 5436
99E4 5429
99E5 541D
99E6 544E
99E7 548F
99E8 5475
99E9 548E
99EA 545F
99EB 5471
99EC 5477
99ED 5470
99EE 5492
99EF 547B
99F0 5480
99F1 5476
99F2 5484
99F3 5490
99F4 5486
99F5 54C7
99F6 54A2
99F7 54B8
99F8 54A5
99F9 54AC
99FA 54C4
99FB 54C8
99FC 54A8
9A40 54AB
9A41 54C2
9A42 54A4
9A43 54BE
9A44 54BC
9A45 54D8
9A46 54E5
9A47 54E6
9A48 550F
9A49 5514
9A4A 54FD
9A4B 54EE
9A4C 54ED
9A4D 54FA
9A4E 54E2
9A4F 5539
9A50 5540
9A51 5563
9A52 554C
9A53 552E
9A54 555C
9A55 5545
9A56 5556
9A57 5557
9A58 5538
9A59 5533
9A5A 555D
9A5B 5599
9A5C 5580
9A5D 54AF
9A5E 558A
9A5F 559F
9A60 557B
9A61 557E
9A62 5598
9A63 559E
9A64 55AE
9A65 557C
9A66 5583
9A67 55A9
9A68 5587
9A69 55A8
9A6A 55DA
9A6B 55C5
9A6C 55DF
9A6D 55C4
9A6E 55DC
9A6F 55E4
9A70 55D4
9A71 5614
9A72 55F7
9A73 5616
9A74 55FE
9A75 55FD
9A76 561B
9A77 55F9
9A78 564E
9A79 5650
9A7A 71DF
9A7B 5634
9A7C 5636
9A7D 5632
9A7E 5638
9A80 566B
9A81 5664
9A82 562F
9A83 566C
9A84 566A
9A85 5686
9A86 5680
9A87 568A
9A88 56A0
9A89 5694
9A8A 568F
9A8B 56A5
9A8C 56AE
9A8D 56B6
9A8E 56B4
9A8F 56C2
9A90 56BC
9A91 56C1
9A92 56C3
9A93 56C0
9A94 56C8
9A95 56CE
9A96 56D1
9A97 56D3
9A98 56D7
9A99 56EE
9A9A 56F9
9A9B 5700
9A9C 56FF
9A9D 5704
9A9E 5709
9A9F 5708
9AA0 570B
9AA1 570D
9AA2 5713
9AA3 5718
9AA4 5716
9AA5 55C7
9AA6 571C
9AA7 5726
9AA8 5737
9AA9 5738
9AAA 574E
9AAB 573B
9AAC 5740
9AAD 574F
9AAE 5769
9AAF 57C0
9AB0 5788
9AB1 5761
9AB2 577F
9AB3 5789
9AB4 5793
9AB5 57A0
9AB6 57B3
9AB7 57A4
9AB8 57AA
9AB9 57B0
9ABA 57C3
9ABB 57C6
9ABC 57D4
9ABD 57D2
9ABE 57D3
9ABF 580A
9AC0 57D6
9AC1 57E3
9AC2 580B
9AC3 5819
9AC4 581D
9AC5 5872
9AC6 5821
9AC7 5862
9AC8 584B
9AC9 5870
9ACA 6BC0
9ACB 5852
9ACC 583D
9ACD 5879
9ACE 5885
9ACF 58B9
9AD0 589F
9AD1 58AB
9AD2 58BA
9AD3 58DE
9AD4 58BB
9AD5 58B8
9AD6 58AE
9AD7 58C5
9AD8 58D3
9AD9 58D1
9ADA 58D7
9ADB 58D9
9ADC 58D8
9ADD 58E5
9ADE 58DC
9ADF 58E4
9AE0 58DF
9AE1 58EF
9AE2 58FA
9AE3 58F9
9AE4 58FB
9AE5 58FC
9AE6 58FD
9AE7 5902
9AE8 590A
9AE9 5910
9AEA 591B
9AEB 68A6
9AEC 5925
9AED 592C
9AEE 592D
9AEF 5932
9AF0 5938
9AF1 593E
9AF2 7AD2
9AF3 5955
9AF4 5950
9AF5 594E
9AF6 595A
9AF7 5958
9AF8 5962
9AF9 5960
9AFA 5967
9AFB 596C
9AFC 5969
9B40 5978
9B41 5981
9B42 599D
9B43 4F5E
9B44 4FAB
9B45 59A3
9B46 59B2
9B47 59C6
9B48 59E8
9B49 59DC
9B4A 598D
9B4B 59D9
9B4C 59DA
9B4D 5A25
9B4E 5A1F
9B4F 5A11
9B50 5A1C
9B51 5A09
9B52 5A1A
9B53 5A40
9B54 5A6C
9B55 5A49
9B56 5A35
9B57 5A36
9B58 5A62
9B59 5A6A
9B5A 5A9A
9B5B 5ABC
9B5C 5ABE
9B5D 5ACB
9B5E 5AC2
9B5F 5ABD
9B60 5AE3
9B61 5AD7
9B62 5AE6
9B63 5AE9
9B64 5AD6
9B65 5AFA
9B66 5AFB
9B67 5B0C
9B68 5B0B
9B69 5B16
9B6A 5B32
9B6B 5AD0
9B6C 5B2A
9B6D 5B36
9B6E 5B3E
9B6F 5B43
9B70 5B45
9B71 5B40
9B72 5B51
9B73 5B55
9B74 5B5A
9B75 5B5B
9B76 5B65
9B77 5B69
9B78 5B70
9B79 5B73
9B7A 5B75
9B7B 5B78
9B7C 6588
9B7D 5B7A
9B7E 5B80
9B80 5B83
9B81 5BA6
9B82 5BB8
9B83 5BC3
9B84 5BC7
9B85 5BC9
9B86 5BD4
9B87 5BD0
9B88 5BE4
9B89 5BE6
9B8A 5BE2
9B8B 5BDE
9B8C 5BE5
9B8D 5BEB
9B8E 5BF0
9B8F 5BF6
9B90 5BF3
9B91 5C05
9B92 5C07
9B93 5C08
9B94 5C0D
9B95 5C13
9B96 5C20
9B97 5C22
9B98 5C28
9B99 5C38
9B9A 5C39
9B9B 5C41
9B9C 5C46
9B9D 5C4E
9B9E 5C53
9B9F 5C50
9BA0 5C4F
9BA1 5B71
9BA2 5C6C
9BA3 5C6E
9BA4 4E62
9BA5 5C76
9BA6 5C79
9BA7 5C8C
9BA8 5C91
9BA9 5C94
9BAA 599B
9BAB 5CAB
9BAC 5CBB
9BAD 5CB6
9BAE 5CBC
9BAF 5CB7
9BB0 5CC5
9BB1 5CBE
9BB2 5CC7
9BB3 5CD9
9BB4 5CE9
9BB5 5CFD
9BB6 5CFA
9BB7 5CED
9BB8 5D8C
9BB9 5CEA
9BBA 5D0B
9BBB 5D15
9BBC 5D17
9BBD 5D5C
9BBE 5D1F
9BBF 5D1B
9BC0 5D11
9BC1 5D14
9BC2 5D22
9BC3 5D1A
9BC4 5D19
9BC5 5D18
9BC6 5D4C
9BC7 5D52
9BC8 5D4E
9BC9 5D4B
9BCA 5D6C
9BCB 5D73
9BCC 5D76
9BCD 5D87
9BCE 5D84
9BCF 5D82
9BD0 5DA2
9BD1 5D9D
9BD2 5DAC
9BD3 5DAE
9BD4 5DBD
9BD5 5D90
9BD6 5DB7
9BD7 5DBC
9BD8 5DC9
9BD9 5DCD
9BDA 5DD3
9BDB 5DD2
9BDC 5DD6
9BDD 5DDB
9BDE 5DEB
9BDF 5DF2
9BE0 5DF5
9BE1 5E0B
9BE2 5E1A
9BE3 5E19
9BE4 5E11
9BE5 5E1B
9BE6 5E36
9BE7 5E37
9BE8 5E44
9BE9 5E43
9BEA 5E40
9BEB 5E4E
9BEC 5E57
9BED 5E54
9BEE 5E5F
9BEF 5E62
9BF0 5E64
9BF1 5E47
9BF2 5E75
9BF3 5E76
9BF4 5E7A
9BF5 9EBC
9BF6 5E7F
9BF7 5EA0
9BF8 5EC1
9BF9 5EC2
9BFA 5EC8
9BFB 5ED0
9BFC 5ECF
9C40 5ED6
9C41 5EE3
9C42 5EDD
9C43 5EDA
9C44 5EDB
9C45 5EE2
9C46 5EE1
9C47 5EE8
9C48 5EE9
9C49 5EEC
9C4A 5EF1
9C4B 5EF3
9C4C 5EF0
9C4D 5EF4
9C4E 5EF8
9C4F 5EFE
9C50 5F03
9C51 5F09
9C52 5F5D
9C53 5F5C
9C54 5F0B
9C55 5F11
9C56 5F16
9C57 5F29
9C58 5F2D
9C59 5F38
9C5A 5F41
9C5B 5F48
9C5C 5F4C
9C5D 5F4E
9C5E 5F2F
9C5F 5F51
9C60 5F56
9C61 5F57
9C62 5F59
9C63 5F61
9C64 5F6D
9C65 5F73
9C66 5F77
9C67 5F83
9C68 5F82
9C69 5F7F
9C6A 5F8A
9C6B 5F88
9C6C 5F91
9C6D 5F87
9C6E 5F9E
9C6F 5F99
9C70 5F98
9C71 5FA0
9C72 5FA8
9C73 5FAD
9C74 5FBC
9C75 5FD6
9C76 5FFB
9C77 5FE4
9C78 5FF8
9C79 5FF1
9C7A 5FDD
9C7B 60B3
9C7C 5FFF
9C7D 6021
9C7E 6060
9C80 6019
9C81 6010
9C82 6029
9C83 600E
9C84 6031
9C85 601B
9C86 6015
9C87 602B
9C88 6026
9C89 600F
9C8A 603A
9C8B 605A
9C8C 6041
9C8D 606A
9C8E 6077
9C8F 605F
9C90 604A
9C91 6046
9C92 604D
9C93 6063
9C94 6043
9C95 6064
9C96 6042
9C97 606C
9C98 606B
9C99 6059
9C9A 6081
9C9B 608D
9C9C 60E7
9C9D 6083
9C9E 609A
9C9F 6084
9CA0 609B
9CA1 6096
9CA2 6097
9CA3 6092
9CA4 60A7
9CA5 608B
9CA6 60E1
9CA7 60B8
9CA8 60E0
9CA9 60D3
9CAA 60B4
9CAB 5FF0
9CAC 60BD
9CAD 60C6
9CAE 60B5
9CAF 60D8
9CB0 614D
9CB1 6115
9CB2 6106
9CB3 60F6
9CB4 60F7
9CB5 6100
9CB6 60F4
9CB7 60FA
9CB8 6103
9CB9 6121
9CBA 60FB
9CBB 60F1
9CBC 610D
9CBD 610E
9CBE 6147
9CBF 613E
9CC0 6128
9CC1 6127
9CC2 614A
9CC3 613F
9CC4 613C
9CC5 612C
9CC6 6134
9CC7 613D
9CC8 6142
9CC9 6144
9CCA 6173
9CCB 6177
9CCC 6158
9CCD 6159
9CCE 615A
9CCF 616B
9CD0 6174
9CD1 616F
9CD2 6165
9CD3 6171
9CD4 615F
9CD5 615D
9CD6 6153
9CD7 6175
9CD8 6199
9CD9 6196
9CDA 6187
9CDB 61AC
9CDC 6194
9CDD 619A
9CDE 618A
9CDF 6191
9CE0 61AB
9CE1 61AE
9CE2 61CC
9CE3 61CA
9CE4 61C9
9CE5 61F7
9CE6 61C8
9CE7 61C3
9CE8 61C6
9CE9 61BA
9CEA 61CB
9CEB 7F79
9CEC 61CD
9CED 61E6
9CEE 61E3
9CEF 61F6
9CF0 61FA
9CF1 61F4
9CF2 61FF
9CF3 61FD
9CF4 61FC
9CF5 61FE
9CF6 6200
9CF7 6208
9CF8 6209
9CF9 620D
9CFA 620C
9CFB 6214
9CFC 621B
9D40 621E
9D41 6221
9D42 622A
9D43 622E
9D44 6230
9D45 6232
9D46 6233
9D47 6241
9D48 624E
9D49 625E
9D4A 6263
9D4B 625B
9D4C 6260
9D4D 6268
9D4E 627C
9D4F 6282
9D50 6289
9D51 627E
9D52 6292
9D53 6293
9D54 6296
9D55 62D4
9D56 6283
9D57 6294
9D58 62D7
9D59 62D1
9D5A 62BB
9D5B 62CF
9D5C 62FF
9D5D 62C6
9D5E 64D4
9D5F 62C8
9D60 62DC
9D61 62CC
9D62 62CA
9D63 62C2
9D64 62C7
9D65 629B
9D66 62C9
9D67 630C
9D68 62EE
9D69 62F1
9D6A 6327
9D6B 6302
9D6C 6308
9D6D 62EF
9D6E 62F5
9D6F 6350
9D70 633E
9D71 634D
9D72 641C
9D73 634F
9D74 6396
9D75 638E
9D76 6380
9D77 63AB
9D78 6376
9D79 63A3
9D7A 638F
9D7B 6389
9D7C 639F
9D7D 63B5
9D7E 636B
9D80 6369
9D81 63BE
9D82 63E9
9D83 63C0
9D84 63C6
9D85 63E3
9D86 63C9
9D87 63D2
9D88 63F6
9D89 63C4
9D8A 6416
9D8B 6434
9D8C 6406
9D8D 6413
9D8E 6426
9D8F 6436
9D90 651D
9D91 6417
9D92 6428
9D93 640F
9D94 6467
9D95 646F
9D96 6476
9D97 644E
9D98 652A
9D99 6495
9D9A 6493
9D9B 64A5
9D9C 64A9
9D9D 6488
9D9E 64BC
9D9F 64DA
9DA0 64D2
9DA1 64C5
9DA2 64C7
9DA3 64BB
9DA4 64D8
9DA5 64C2
9DA6 64F1
9DA7 64E7
9DA8 8209
9DA9 64E0
9DAA 64E1
9DAB 62AC
9DAC 64E3
9DAD 64EF
9DAE 652C
9DAF 64F6
9DB0 64F4
9DB1 64F2
9DB2 64FA
9DB3 6500
9DB4 64FD
9DB5 6518
9DB6 651C
9DB7 6505
9DB8 6524
9DB9 6523
9DBA 652B
9DBB 6534
9DBC 6535
9DBD 6537
9DBE 6536
9DBF 6538
9DC0 754B
9DC1 6548
9DC2 6556
9DC3 6555
9DC4 654D
9DC5 6558
9DC6 655E
9DC7 655D
9DC8 6572
9DC9 6578
9DCA 6582
9DCB 6583
9DCC 8B8A
9DCD 659B
9DCE 659F
9DCF 65AB
9DD0 65B7
9DD1 65C3
9DD2 65C6
9DD3 65C1
9DD4 65C4
9DD5 65CC
9DD6 65D2
9DD7 65DB
9DD8 65D9
9DD9 65E0
9DDA 65E1
9DDB 65F1
9DDC 6772
9DDD 660A
9DDE 6603
9DDF 65FB
9DE0 6773
9DE1 6635
9DE2 6636
9DE3 6634
9DE4 661C
9DE5 664F
9DE6 6644
9DE7 6649
9DE8 6641
9DE9 665E
9DEA 665D
9DEB 6664
9DEC 6667
9DED 6668
9DEE 665F
9DEF 6662
9DF0 6670
9DF1 6683
9DF2 6688
9DF3 668E
9DF4 6689
9DF5 6684
9DF6 6698
9DF7 669D
9DF8 66C1
9DF9 66B9
9DFA 66C9
9DFB 66BE
9DFC 66BC
9E40 66C4
9E41 66B8
9E42 66D6
9E43 66DA
9E44 66E0
9E45 663F
9E46 66E6
9E47 66E9
9E48 66F0
9E49 66F5
9E4A 66F7
9E4B 670F
9E4C 6716
9E4D 671E
9E4E 6726
9E4F 6727
9E50 9738
9E51 672E
9E52 673F
9E53 6736
9E54 6741
9E55 6738
9E56 6737
9E57 6746
9E58 675E
9E59 6760
9E5A 6759
9E5B 6763
9E5C 6764
9E5D 6789
9E5E 6770
9E5F 67A9
9E60 677C
9E61 676A
9E62 678C
9E63 678B
9E64 67A6
9E65 67A1
9E66 6785
9E67 67B7
9E68 67EF
9E69 67B4
9E6A 67EC
9E6B 67B3
9E6C 67E9
9E6D 67B8
9E6E 67E4
9E6F 67DE
9E70 67DD
9E71 67E2
9E72 67EE
9E73 67B9
9E74 67CE
9E75 67C6
9E76 67E7
9E77 6A9C
9E78 681E
9E79 6846
9E7A 6829
9E7B 6840
9E7C 684D
9E7D 6832
9E7E 684E
9E80 68B3
9E81 682B
9E82 6859
9E83 6863
9E84 6877
9E85 687F
9E86 689F
9E87 688F
9E88 68AD
9E89 6894
9E8A 689D
9E8B 689B
9E8C 6883
9E8D 6AAE
9E8E 68B9
9E8F 6874
9E90 68B5
9E91 68A0
9E92 68BA
9E93 690F
9E94 688D
9E95 687E
9E96 6901
9E97 68CA
9E98 6908
9E99 68D8
9E9A 6922
9E9B 6926
9E9C 68E1
9E9D 690C
9E9E 68CD
9E9F 68D4
9EA0 68E7
9EA1 68D5
9EA2 6936
9EA3 6912
9EA4 6904
9EA5 68D7
9EA6 68E3
9EA7 6925
9EA8 68F9
9EA9 68E0
9EAA 68EF
9EAB 6928
9EAC 692A
9EAD 691A
9EAE 6923
9EAF 6921
9EB0 68C6
9EB1 6979
9EB2 6977
9EB3 695C
9EB4 6978
9EB5 696B
9EB6 6954
9EB7 697E
9EB8 696E
9EB9 6939
9EBA 6974
9EBB 693D
9EBC 6959
9EBD 6930
9EBE 6961
9EBF 695E
9EC0 695D
9EC1 6981
9EC2 696A
9EC3 69B2
9EC4 69AE
9EC5 69D0
9EC6 69BF
9EC7 69C1
9EC8 69D3
9EC9 69BE
9ECA 69CE
9ECB 5BE8
9ECC 69CA
9ECD 69DD
9ECE 69BB
9ECF 69C3
9ED0 69A7
9ED1 6A2E
9ED2 6991
9ED3 69A0
9ED4 699C
9ED5 6995
9ED6 69B4
9ED7 69DE
9ED8 69E8
9ED9 6A02
9EDA 6A1B
9EDB 69FF
9EDC 6B0A
9EDD 69F9
9EDE 69F2
9EDF 69E7
9EE0 6A05
9EE1 69B1
9EE2 6A1E
9EE3 69ED
9EE4 6A14
9EE5 69EB
9EE6 6A0A
9EE7 6A12
9EE8 6AC1
9EE9 6A23
9EEA 6A13
9EEB 6A44
9EEC 6A0C
9EED 6A72
9EEE 6A36
9EEF 6A78
9EF0 6A47
9EF1 6A62
9EF2 6A59
9EF3 6A66
9EF4 6A48
9EF5 6A38
9EF6 6A22
9EF7 6A90
9EF8 6A8D
9EF9 6AA0
9EFA 6A84
9EFB 6AA2
9EFC 6AA3
9F40 6A97
9F41 8617
9F42 6ABB
9F43 6AC3
9F44 6AC2
9F45 6AB8
9F46 6AB3
9F47 6AAC
9F48 6ADE
9F49 6AD1
9F4A 6ADF
9F4B 6AAA
9F4C 6ADA
9F4D 6AEA
9F4E 6AFB
9F4F 6B05
9F50 8616
9F51 6AFA
9F52 6B12
9F53 6B16
9F54 9B31
9F55 6B1F
9F56 6B38
9F57 6B37
9F58 76DC
9F59 6B39
9F5A 98EE
9F5B 6B47
9F5C 6B43
9F5D 6B49
9F5E 6B50
9F5F 6B59
9F60 6B54
9F61 6B5B
9F62 6B5F
9F63 6B61
9F64 6B78
9F65 6B79
9F66 6B7F
9F67 6B80
9F68 6B84
9F69 6B83
9F6A 6B8D
9F6B 6B98
9F6C 6B95
9F6D 6B9E
9F6E 6BA4
9F6F 6BAA
9F70 6BAB
9F71 6BAF
9F72 6BB2
9F73 6BB1
9F74 6BB3
9F75 6BB7
9F76 6BBC
9F77 6BC6
9F78 6BCB
9F79 6BD3
9F7A 6BDF
9F7B 6BEC
9F7C 6BEB
9F7D 6BF3
9F7E 6BEF
9F80 9EBE
9F81 6C08
9F82 6C13
9F83 6C14
9F84 6C1B
9F85 6C24
9F86 6C23
9F87 6C5E
9F88 6C55
9F89 6C62
9F8A 6C6A
9F8B 6C82
9F8C 6C8D
9F8D 6C9A
9F8E 6C81
9F8F 6C9B
9F90 6C7E
9F91 6C68
9F92 6C73
9F93 6C92
9F94 6C90
9F95 6CC4
9F96 6CF1
9F97 6CD3
9F98 6CBD
9F99 6CD7
9F9A 6CC5
9F9B 6CDD
9F9C 6CAE
9F9D 6CB1
9F9E 6CBE
9F9F 6CBA
9FA0 6CDB
9FA1 6CEF
9FA2 6CD9
9FA3 6CEA
9FA4 6D1F
9FA5 884D
9FA6 6D36
9FA7 6D2B
9FA8 6D3D
9FA9 6D38
9FAA 6D19
9FAB 6D35
9FAC 6D33
9FAD 6D12
9FAE 6D0C
9FAF 6D63
9FB0 6D93
9FB1 6D64
9FB2 6D5A
9FB3 6D79
9FB4 6D59
9FB5 6D8E
9FB6 6D95
9FB7 6FE4
9FB8 6D85
9FB9 6DF9
9FBA 6E15
9FBB 6E0A
9FBC 6DB5
9FBD 6DC7
9FBE 6DE6
9FBF 6DB8
9FC0 6DC6
9FC1 6DEC
9FC2 6DDE
9FC3 6DCC
9FC4 6DE8
9FC5 6DD2
9FC6 6DC5
9FC7 6DFA
9FC8 6DD9
9FC9 6DE4
9FCA 6DD5
9FCB 6DEA
9FCC 6DEE
9FCD 6E2D
9FCE 6E6E
9FCF 6E2E
9FD0 6E19
9FD1 6E72
9FD2 6E5F
9FD3 6E3E
9FD4 6E23
9FD5 6E6B
9FD6 6E2B
9FD7 6E76
9FD8 6E4D
9FD9 6E1F
9FDA 6E43
9FDB 6E3A
9FDC 6E4E
9FDD 6E24
9FDE 6EFF
9FDF 6E1D
9FE0 6E38
9FE1 6E82
9FE2 6EAA
9FE3 6E98
9FE4 6EC9
9FE5 6EB7
9FE6 6ED3
9FE7 6EBD
9FE8 6EAF
9FE9 6EC4
9FEA 6EB2
9FEB 6ED4
9FEC 6ED5
9FED 6E8F
9FEE 6EA5
9FEF 6EC2
9FF0 6E9F
9FF1 6F41
9FF2 6F11
9FF3 704C
9FF4 6EEC
9FF5 6EF8
9FF6 6EFE
9FF7 6F3F
9FF8 6EF2
9FF9 6F31
9FFA 6EEF
9FFB 6F32
9FFC 6ECC
E040 6F3E
E041 6F13
E042 6EF7
E043 6F86
E044 6F7A
E045 6F78
E046 6F81
E047 6F80
E048 6F6F
E049 6F5B
E04A 6FF3
E04B 6F6D
E04C 6F82
E04D 6F7C
E04E 6F58
E04F 6F8E
E050 6F91
E051 6FC2
E052 6F66
E053 6FB3
E054 6FA3
E055 6FA1
E056 6FA4
E057 6FB9
E058 6FC6
E059 6FAA
E05A 6FDF
E05B 6FD5
E05C 6FEC
E05D 6FD4
E05E 6FD8
E05F 6FF1
E060 6FEE
E061 6FDB
E062 7009
E063 700B
E064 6FFA
E065 7011
E066 7001
E067 700F
E068 6FFE
E069 701B
E06A 701A
E06B 6F74
E06C 701D
E06D 7018
E06E 701F
E06F 7030
E070 703E
E071 7032
E072 7051
E073 7063
E074 7099
E075 7092
E076 70AF
E077 70F1
E078 70AC
E079 70B8
E07A 70B3
E07B 70AE
E07C 70DF
E07D 70CB
E07E 70DD
E080 70D9
E081 7109
E082 70FD
E083 711C
E084 7119
E085 7165
E086 7155
E087 7188
E088 7166
E089 7162
E08A 714C
E08B 7156
E08C 716C
E08D 718F
E08E 71FB
E08F 7184
E090 7195
E091 71A8
E092 71AC
E093 71D7
E094 71B9
E095 71BE
E096 71D2
E097 71C9
E098 71D4
E099 71CE
E09A 71E0
E09B 71EC
E09C 71E7
E09D 71F5
E09E 71FC
E09F 71F9
E0A0 71FF
E0A1 720D
E0A2 7210
E0A3 721B
E0A4 7228
E0A5 722D
E0A6 722C
E0A7 7230
E0A8 7232
E0A9 723B
E0AA 723C
E0AB 723F
E0AC 7240
E0AD 7246
E0AE 724B
E0AF 7258
E0B0 7274
E0B1 727E
E0B2 7282
E0B3 7281
E0B4 7287
E0B5 7292
E0B6 7296
E0B7 72A2
E0B8 72A7
E0B9 72B9
E0BA 72B2
E0BB 72C3
E0BC 72C6
E0BD 72C4
E0BE 72CE
E0BF 72D2
E0C0 72E2
E0C1 72E0
E0C2 72E1
E0C3 72F9
E0C4 72F7
E0C5 500F
E0C6 7317
E0C7 730A
E0C8 731C
E0C9 7316
E0CA 731D
E0CB 7334
E0CC 732F
E0CD 7329
E0CE 7325
E0CF 733E
E0D0 734E
E0D1 734F
E0D2 9ED8
E0D3 7357
E0D4 736A
E0D5 7368
E0D6 7370
E0D7 7378
E0D8 7375
E0D9 737B
E0DA 737A
E0DB 73C8
E0DC 73B3
E0DD 73CE
E0DE 73BB
E0DF 73C0
E0E0 73E5
E0E1 73EE
E0E2 73DE
E0E3 74A2
E0E4 7405
E0E5 746F
E0E6 7425
E0E7 73F8
E0E8 7432
E0E9 743A
E0EA 7455
E0EB 743F
E0EC 745F
E0ED 7459
E0EE 7441
E0EF 745C
E0F0 7469
E0F1 7470
E0F2 7463
E0F3 746A
E0F4 7476
E0F5 747E
E0F6 748B
E0F7 749E
E0F8 74A7
E0F9 74CA
E0FA 74CF
E0FB 74D4
E0FC 73F1
E140 74E0
E141 74E3
E142 74E7
E143 74E9
E144 74EE
E145 74F2
E146 74F0
E147 74F1
E148 74F8
E149 74F7
E14A 7504
E14B 7503
E14C 7505
E14D 750C
E14E 750E
E14F 750D
E150 7515
E151 7513
E152 751E
E153 7526
E154 752C
E155 753C
E156 7544
E157 754D
E158 754A
E159 7549
E15A 755B
E15B 7546
E15C 755A
E15D 7569
E15E 7564
E15F 7567
E160 756B
E161 756D
E162 7578
E163 7576
E164 7586
E165 7587
E166 7574
E167 758A
E168 7589
E169 7582
E16A 7594
E16B 759A
E16C 759D
E16D 75A5
E16E 75A3
E16F 75C2
E170 75B3
E171 75C3
E172 75B5
E173 75BD
E174 75B8
E175 75BC
E176 75B1
E177 75CD
E178 75CA
E179 75D2
E17A 75D9
E17B 75E3
E17C 75DE
E17D 75FE
E17E 75FF
E180 75FC
E181 7601
E182 75F0
E183 75FA
E184 75F2
E185 75F3
E186 760B
E187 760D
E188 7609
E189 761F
E18A 7627
E18B 7620
E18C 7621
E18D 7622
E18E 7624
E18F 7634
E190 7630
E191 763B
E192 7647
E193 7648
E194 7646
E195 765C
E196 7658
E197 7661
E198 7662
E199 7668
E19A 7669
E19B 766A
E19C 7667
E19D 766C
E19E 7670
E19F 7672
E1A0 7676
E1A1 7678
E1A2 767C
E1A3 7680
E1A4 7683
E1A5 7688
E1A6 768B
E1A7 768E
E1A8 7696
E1A9 7693
E1AA 7699
E1AB 769A
E1AC 76B0
E1AD 76B4
E1AE 76B8
E1AF 76B9
E1B0 76BA
E1B1 76C2
E1B2 76CD
E1B3 76D6
E1B4 76D2
E1B5 76DE
E1B6 76E1
E1B7 76E5
E1B8 76E7
E1B9 76EA
E1BA 862F
E1BB 76FB
E1BC 7708
E1BD 7707
E1BE 7704
E1BF 7729
E1C0 7724
E1C1 771E
E1C2 7725
E1C3 7726
E1C4 771B
E1C5 7737
E1C6 7738
E1C7 7747
E1C8 775A
E1C9 7768
E1CA 776B
E1CB 775B
E1CC 7765
E1CD 777F
E1CE 777E
E1CF 7779
E1D0 778E
E1D1 778B
E1D2 7791
E1D3 77A0
E1D4 779E
E1D5 77B0
E1D6 77B6
E1D7 77B9
E1D8 77BF
E1D9 77BC
E1DA 77BD
E1DB 77BB
E1DC 77C7
E1DD 77CD
E1DE 77D7
E1DF 77DA
E1E0 77DC
E1E1 77E3
E1E2 77EE
E1E3 77FC
E1E4 780C
E1E5 7812
E1E6 7926
E1E7 7820
E1E8 792A
E1E9 7845
E1EA 788E
E1EB 7874
E1EC 7886
E1ED 787C
E1EE 789A
E1EF 788C
E1F0 78A3
E1F1 78B5
E1F2 78AA
E1F3 78AF
E1F4 78D1
E1F5 78C6
E1F6 78CB
E1F7 78D4
E1F8 78BE
E1F9 78BC
E1FA 78C5
E1FB 78CA
E1FC 78EC
E240 78E7
E241 78DA
E242 78FD
E243 78F4
E244 7907
E245 7912
E246 7911
E247 7919
E248 792C
E249 792B
E24A 7940
E24B 7960
E24C 7957
E24D 795F
E24E 795A
E24F 7955
E250 7953
E251 797A
E252 797F
E253 798A
E254 799D
E255 79A7
E256 9F4B
E257 79AA
E258 79AE
E259 79B3
E25A 79B9
E25B 79BA
E25C 79C9
E25D 79D5
E25E 79E7
E25F 79EC
E260 79E1
E261 79E3
E262 7A08
E263 7A0D
E264 7A18
E265 7A19
E266 7A20
E267 7A1F
E268 7980
E269 7A31
E26A 7A3B
E26B 7A3E
E26C 7A37
E26D 7A43
E26E 7A57
E26F 7A49
E270 7A61
E271 7A62
E272 7A69
E273 9F9D
E274 7A70
E275 7A79
E276 7A7D
E277 7A88
E278 7A97
E279 7A95
E27A 7A98
E27B 7A96
E27C 7AA9
E27D 7AC8
E27E 7AB0
E280 7AB6
E281 7AC5
E282 7AC4
E283 7ABF
E284 9083
E285 7AC7
E286 7ACA
E287 7ACD
E288 7ACF
E289 7AD5
E28A 7AD3
E28B 7AD9
E28C 7ADA
E28D 7ADD
E28E 7AE1
E28F 7AE2
E290 7AE6
E291 7AED
E292 7AF0
E293 7B02
E294 7B0F
E295 7B0A
E296 7B06
E297 7B33
E298 7B18
E299 7B19
E29A 7B1E
E29B 7B35
E29C 7B28
E29D 7B36
E29E 7B50
E29F 7B7A
E2A0 7B04
E2A1 7B4D
E2A2 7B0B
E2A3 7B4C
E2A4 7B45
E2A5 7B75
E2A6 7B65
E2A7 7B74
E2A8 7B67
E2A9 7B70
E2AA 7B71
E2AB 7B6C
E2AC 7B6E
E2AD 7B9D
E2AE 7B98
E2AF 7B9F
E2B0 7B8D
E2B1 7B9C
E2B2 7B9A
E2B3 7B8B
E2B4 7B92
E2B5 7B8F
E2B6 7B5D
E2B7 7B99
E2B8 7BCB
E2B9 7BC1
E2BA 7BCC
E2BB 7BCF
E2BC 7BB4
E2BD 7BC6
E2BE 7BDD
E2BF 7BE9
E2C0 7C11
E2C1 7C14
E2C2 7BE6
E2C3 7BE5
E2C4 7C60
E2C5 7C00
E2C6 7C07
E2C7 7C13
E2C8 7BF3
E2C9 7BF7
E2CA 7C17
E2CB 7C0D
E2CC 7BF6
E2CD 7C23
E2CE 7C27
E2CF 7C2A
E2D0 7C1F
E2D1 7C37
E2D2 7C2B
E2D3 7C3D
E2D4 7C4C
E2D5 7C43
E2D6 7C54
E2D7 7C4F
E2D8 7C40
E2D9 7C50
E2DA 7C58
E2DB 7C5F
E2DC 7C64
E2DD 7C56
E2DE 7C65
E2DF 7C6C
E2E0 7C75
E2E1 7C83
E2E2 7C90
E2E3 7CA4
E2E4 7CAD
E2E5 7CA2
E2E6 7CAB
E2E7 7CA1
E2E8 7CA8
E2E9 7CB3
E2EA 7CB2
E2EB 7CB1
E2EC 7CAE
E2ED 7CB9
E2EE 7CBD
E2EF 7CC0
E2F0 7CC5
E2F1 7CC2
E2F2 7CD8
E2F3 7CD2
E2F4 7CDC
E2F5 7CE2
E2F6 9B3B
E2F7 7CEF
E2F8 7CF2
E2F9 7CF4
E2FA 7CF6
E2FB 7CFA
E2FC 7D06
E340 7D02
E341 7D1C
E342 7D15
E343 7D0A
E344 7D45
E345 7D4B
E346 7D2E
E347 7D32
E348 7D3F
E349 7D35
E34A 7D46
E34B 7D73
E34C 7D56
E34D 7D4E
E34E 7D72
E34F 7D68
E350 7D6E
E351 7D4F
E352 7D63
E353 7D93
E354 7D89
E355 7D5B
E356 7D8F
E357 7D7D
E358 7D9B
E359 7DBA
E35A 7DAE
E35B 7DA3
E35C 7DB5
E35D 7DC7
E35E 7DBD
E35F 7DAB
E360 7E3D
E361 7DA2
E362 7DAF
E363 7DDC
E364 7DB8
E365 7D9F
E366 7DB0
E367 7DD8
E368 7DDD
E369 7DE4
E36A 7DDE
E36B 7DFB
E36C 7DF2
E36D 7DE1
E36E 7E05
E36F 7E0A
E370 7E23
E371 7E21
E372 7E12
E373 7E31
E374 7E1F
E375 7E09
E376 7E0B
E377 7E22
E378 7E46
E379 7E66
E37A 7E3B
E37B 7E35
E37C 7E39
E37D 7E43
E37E 7E37
E380 7E32
E381 7E3A
E382 7E67
E383 7E5D
E384 7E56
E385 7E5E
E386 7E59
E387 7E5A
E388 7E79
E389 7E6A
E38A 7E69
E38B 7E7C
E38C 7E7B
E38D 7E83
E38E 7DD5
E38F 7E7D
E390 8FAE
E391 7E7F
E392 7E88
E393 7E89
E394 7E8C
E395 7E92
E396 7E90
E397 7E93
E398 7E94
E399 7E96
E39A 7E8E
E39B 7E9B
E39C 7E9C
E39D 7F38
E39E 7F3A
E39F 7F45
E3A0 7F4C
E3A1 7F4D
E3A2 7F4E
E3A3 7F50
E3A4 7F51
E3A5 7F55
E3A6 7F54
E3A7 7F58
E3A8 7F5F
E3A9 7F60
E3AA 7F68
E3AB 7F69
E3AC 7F67
E3AD 7F78
E3AE 7F82
E3AF 7F86
E3B0 7F83
E3B1 7F88
E3B2 7F87
E3B3 7F8C
E3B4 7F94
E3B5 7F9E
E3B6 7F9D
E3B7 7F9A
E3B8 7FA3
E3B9 7FAF
E3BA 7FB2
E3BB 7FB9
E3BC 7FAE
E3BD 7FB6
E3BE 7FB8
E3BF 8B71
E3C0 7FC5
E3C1 7FC6
E3C2 7FCA
E3C3 7FD5
E3C4 7FD4
E3C5 7FE1
E3C6 7FE6
E3C7 7FE9
E3C8 7FF3
E3C9 7FF9
E3CA 98DC
E3CB 8006
E3CC 8004
E3CD 800B
E3CE 8012
E3CF 8018
E3D0 8019
E3D1 801C
E3D2 8021
E3D3 8028
E3D4 803F
E3D5 803B
E3D6 804A
E3D7 8046
E3D8 8052
E3D9 8058
E3DA 805A
E3DB 805F
E3DC 8062
E3DD 8068
E3DE 8073
E3DF 8072
E3E0 8070
E3E1 8076
E3E2 8079
E3E3 807D
E3E4 807F
E3E5 8084
E3E6 8086
E3E7 8085
E3E8 809B
E3E9 8093
E3EA 809A
E3EB 80AD
E3EC 5190
E3ED 80AC
E3EE 80DB
E3EF 80E5
E3F0 80D9
E3F1 80DD
E3F2 80C4
E3F3 80DA
E3F4 80D6
E3F5 8109
E3F6 80EF
E3F7 80F1
E3F8 811B
E3F9 8129
E3FA 8123
E3FB 812F
E3FC 814B
E440 968B
E441 8146
E442 813E
E443 8153
E444 8151
E445 80FC
E446 8171
E447 816E
E448 8165
E449 8166
E44A 8174
E44B 8183
E44C 8188
E44D 818A
E44E 8180
E44F 8182
E450 81A0
E451 8195
E452 81A4
E453 81A3
E454 815F
E455 8193
E456 81A9
E457 81B0
E458 81B5
E459 81BE
E45A 81B8
E45B 81BD
E45C 81C0
E45D 81C2
E45E 81BA
E45F 81C9
E460 81CD
E461 81D1
E462 81D9
E463 81D8
E464 81C8
E465 81DA
E466 81DF
E467 81E0
E468 81E7
E469 81FA
E46A 81FB
E46B 81FE
E46C 8201
E46D 8202
E46E 8205
E46F 8207
E470 820A
E471 820D
E472 8210
E473 8216
E474 8229
E475 822B
E476 8238
E477 8233
E478 8240
E479 8259
E47A 8258
E47B 825D
E47C 825A
E47D 825F
E47E 8264
E480 8262
E481 8268
E482 826A
E483 826B
E484 822E
E485 8271
E486 8277
E487 8278
E488 827E
E489 828D
E48A 8292
E48B 82AB
E48C 829F
E48D 82BB
E48E 82AC
E48F 82E1
E490 82E3
E491 82DF
E492 82D2
E493 82F4
E494 82F3
E495 82FA
E496 8393
E497 8303
E498 82FB
E499 82F9
E49A 82DE
E49B 8306
E49C 82DC
E49D 8309
E49E 82D9
E49F 8335
E4A0 8334
E4A1 8316
E4A2 8332
E4A3 8331
E4A4 8340
E4A5 8339
E4A6 8350
E4A7 8345
E4A8 832F
E4A9 832B
E4AA 8317
E4AB 8318
E4AC 8385
E4AD 839A
E4AE 83AA
E4AF 839F
E4B0 83A2
E4B1 8396
E4B2 8323
E4B3 838E
E4B4 8387
E4B5 838A
E4B6 837C
E4B7 83B5
E4B8 8373
E4B9 8375
E4BA 83A0
E4BB 8389
E4BC 83A8
E4BD 83F4
E4BE 8413
E4BF 83EB
E4C0 83CE
E4C1 83FD
E4C2 8403
E4C3 83D8
E4C4 840B
E4C5 83C1
E4C6 83F7
E4C7 8407
E4C8 83E0
E4C9 83F2
E4CA 840D
E4CB 8422
E4CC 8420
E4CD 83BD
E4CE 8438
E4CF 8506
E4D0 83FB
E4D1 846D
E4D2 842A
E4D3 843C
E4D4 855A
E4D5 8484
E4D6 8477
E4D7 846B
E4D8 84AD
E4D9 846E
E4DA 8482
E4DB 8469
E4DC 8446
E4DD 842C
E4DE 846F
E4DF 8479
E4E0 8435
E4E1 84CA
E4E2 8462
E4E3 84B9
E4E4 84BF
E4E5 849F
E4E6 84D9
E4E7 84CD
E4E8 84BB
E4E9 84DA
E4EA 84D0
E4EB 84C1
E4EC 84C6
E4ED 84D6
E4EE 84A1
E4EF 8521
E4F0 84FF
E4F1 84F4
E4F2 8517
E4F3 8518
E4F4 852C
E4F5 851F
E4F6 8515
E4F7 8514
E4F8 84FC
E4F9 8540
E4FA 8563
E4FB 8558
E4FC 8548
E540 8541
E541 8602
E542 854B
E543 8555
E544 8580
E545 85A4
E546 8588
E547 8591
E548 858A
E549 85A8
E54A 856D
E54B 8594
E54C 859B
E54D 85EA
E54E 8587
E54F 859C
E550 8577
E551 857E
E552 8590
E553 85C9
E554 85BA
E555 85CF
E556 85B9
E557 85D0
E558 85D5
E559 85DD
E55A 85E5
E55B 85DC
E55C 85F9
E55D 860A
E55E 8613
E55F 860B
E560 85FE
E561 85FA
E562 8606
E563 8622
E564 861A
E565 8630
E566 863F
E567 864D
E568 4E55
E569 8654
E56A 865F
E56B 8667
E56C 8671
E56D 8693
E56E 86A3
E56F 86A9
E570 86AA
E571 868B
E572 868C
E573 86B6
E574 86AF
E575 86C4
E576 86C6
E577 86B0
E578 86C9
E579 8823
E57A 86AB
E57B 86D4
E57C 86DE
E57D 86E9
E57E 86EC
E580 86DF
E581 86DB
E582 86EF
E583 8712
E584 8706
E585 8708
E586 8700
E587 8703
E588 86FB
E589 8711
E58A 8709
E58B 870D
E58C 86F9
E58D 870A
E58E 8734
E58F 873F
E590 8737
E591 873B
E592 8725
E593 8729
E594 871A
E595 8760
E596 875F
E597 8778
E598 874C
E599 874E
E59A 8774
E59B 8757
E59C 8768
E59D 876E
E59E 8759
E59F 8753
E5A0 8763
E5A1 876A
E5A2 8805
E5A3 87A2
E5A4 879F
E5A5 8782
E5A6 87AF
E5A7 87CB
E5A8 87BD
E5A9 87C0
E5AA 87D0
E5AB 96D6
E5AC 87AB
E5AD 87C4
E5AE 87B3
E5AF 87C7
E5B0 87C6
E5B1 87BB
E5B2 87EF
E5B3 87F2
E5B4 87E0
E5B5 880F
E5B6 880D
E5B7 87FE
E5B8 87F6
E5B9 87F7
E5BA 880E
E5BB 87D2
E5BC 8811
E5BD 8816
E5BE 8815
E5BF 8822
E5C0 8821
E5C1 8831
E5C2 8836
E5C3 8839
E5C4 8827
E5C5 883B
E5C6 8844
E5C7 8842
E5C8 8852
E5C9 8859
E5CA 885E
E5CB 8862
E5CC 886B
E5CD 8881
E5CE 887E
E5CF 889E
E5D0 8875
E5D1 887D
E5D2 88B5
E5D3 8872
E5D4 8882
E5D5 8897
E5D6 8892
E5D7 88AE
E5D8 8899
E5D9 88A2
E5DA 888D
E5DB 88A4
E5DC 88B0
E5DD 88BF
E5DE 88B1
E5DF 88C3
E5E0 88C4
E5E1 88D4
E5E2 88D8
E5E3 88D9
E5E4 88DD
E5E5 88F9
E5E6 8902
E5E7 88FC
E5E8 88F4
E5E9 88E8
E5EA 88F2
E5EB 8904
E5EC 890C
E5ED 890A
E5EE 8913
E5EF 8943
E5F0 891E
E5F1 8925
E5F2 892A
E5F3 892B
E5F4 8941
E5F5 8944
E5F6 893B
E5F7 8936
E5F8 8938
E5F9 894C
E5FA 891D
E5FB 8960
E5FC 895E
E640 8966
E641 8964
E642 896D
E643 896A
E644 896F
E645 8974
E646 8977
E647 897E
E648 8983
E649 8988
E64A 898A
E64B 8993
E64C 8998
E64D 89A1
E64E 89A9
E64F 89A6
E650 89AC
E651 89AF
E652 89B2
E653 89BA
E654 89BD
E655 89BF
E656 89C0
E657 89DA
E658 89DC
E659 89DD
E65A 89E7
E65B 89F4
E65C 89F8
E65D 8A03
E65E 8A16
E65F 8A10
E660 8A0C
E661 8A1B
E662 8A1D
E663 8A25
E664 8A36
E665 8A41
E666 8A5B
E667 8A52
E668 8A46
E669 8A48
E66A 8A7C
E66B 8A6D
E66C 8A6C
E66D 8A62
E66E 8A85
E66F 8A82
E670 8A84
E671 8AA8
E672 8AA1
E673 8A91
E674 8AA5
E675 8AA6
E676 8A9A
E677 8AA3
E678 8AC4
E679 8ACD
E67A 8AC2
E67B 8ADA
E67C 8AEB
E67D 8AF3
E67E 8AE7
E680 8AE4
E681 8AF1
E682 8B14
E683 8AE0
E684 8AE2
E685 8AF7
E686 8ADE
E687 8ADB
E688 8B0C
E689 8B07
E68A 8B1A
E68B 8AE1
E68C 8B16
E68D 8B10
E68E 8B17
E68F 8B20
E690 8B33
E691 97AB
E692 8B26
E693 8B2B
E694 8B3E
E695 8B28
E696 8B41
E697 8B4C
E698 8B4F
E699 8B4E
E69A 8B49
E69B 8B56
E69C 8B5B
E69D 8B5A
E69E 8B6B
E69F 8B5F
E6A0 8B6C
E6A1 8B6F
E6A2 8B74
E6A3 8B7D
E6A4 8B80
E6A5 8B8C
E6A6 8B8E
E6A7 8B92
E6A8 8B93
E6A9 8B96
E6AA 8B99
E6AB 8B9A
E6AC 8C3A
E6AD 8C41
E6AE 8C3F
E6AF 8C48
E6B0 8C4C
E6B1 8C4E
E6B2 8C50
E6B3 8C55
E6B4 8C62
E6B5 8C6C
E6B6 8C78
E6B7 8C7A
E6B8 8C82
E6B9 8C89
E6BA 8C85
E6BB 8C8A
E6BC 8C8D
E6BD 8C8E
E6BE 8C94
E6BF 8C7C
E6C0 8C98
E6C1 621D
E6C2 8CAD
E6C3 8CAA
E6C4 8CBD
E6C5 8CB2
E6C6 8CB3
E6C7 8CAE
E6C8 8CB6
E6C9 8CC8
E6CA 8CC1
E6CB 8CE4
E6CC 8CE3
E6CD 8CDA
E6CE 8CFD
E6CF 8CFA
E6D0 8CFB
E6D1 8D04
E6D2 8D05
E6D3 8D0A
E6D4 8D07
E6D5 8D0F
E6D6 8D0D
E6D7 8D10
E6D8 9F4E
E6D9 8D13
E6DA 8CCD
E6DB 8D14
E6DC 8D16
E6DD 8D67
E6DE 8D6D
E6DF 8D71
E6E0 8D73
E6E1 8D81
E6E2 8D99
E6E3 8DC2
E6E4 8DBE
E6E5 8DBA
E6E6 8DCF
E6E7 8DDA
E6E8 8DD6
E6E9 8DCC
E6EA 8DDB
E6EB 8DCB
E6EC 8DEA
E6ED 8DEB
E6EE 8DDF
E6EF 8DE3
E6F0 8DFC
E6F1 8E08
E6F2 8E09
E6F3 8DFF
E6F4 8E1D
E6F5 8E1E
E6F6 8E10
E6F7 8E1F
E6F8 8E42
E6F9 8E35
E6FA 8E30
E6FB 8E34
E6FC 8E4A
E740 8E47
E741 8E49
E742 8E4C
E743 8E50
E744 8E48
E745 8E59
E746 8E64
E747 8E60
E748 8E2A
E749 8E63
E74A 8E55
E74B 8E76
E74C 8E72
E74D 8E7C
E74E 8E81
E74F 8E87
E750 8E85
E751 8E84
E752 8E8B
E753 8E8A
E754 8E93
E755 8E91
E756 8E94
E757 8E99
E758 8EAA
E759 8EA1
E75A 8EAC
E75B 8EB0
E75C 8EC6
E75D 8EB1
E75E 8EBE
E75F 8EC5
E760 8EC8
E761 8ECB
E762 8EDB
E763 8EE3
E764 8EFC
E765 8EFB
E766 8EEB
E767 8EFE
E768 8F0A
E769 8F05
E76A 8F15
E76B 8F12
E76C 8F19
E76D 8F13
E76E 8F1C
E76F 8F1F
E770 8F1B
E771 8F0C
E772 8F26
E773 8F33
E774 8F3B
E775 8F39
E776 8F45
E777 8F42
E778 8F3E
E779 8F4C
E77A 8F49
E77B 8F46
E77C 8F4E
E77D 8F57
E77E 8F5C
E780 8F62
E781 8F63
E782 8F64
E783 8F9C
E784 8F9F
E785 8FA3
E786 8FAD
E787 8FAF
E788 8FB7
E789 8FDA
E78A 8FE5
E78B 8FE2
E78C 8FEA
E78D 8FEF
E78E 9087
E78F 8FF4
E790 9005
E791 8FF9
E792 8FFA
E793 9011
E794 9015
E795 9021
E796 900D
E797 901E
E798 9016
E799 900B
E79A 9027
E79B 9036
E79C 9035
E79D 9039
E79E 8FF8
E79F 904F
E7A0 9050
E7A1 9051
E7A2 9052
E7A3 900E
E7A4 9049
E7A5 903E
E7A6 9056
E7A7 9058
E7A8 905E
E7A9 9068
E7AA 906F
E7AB 9076
E7AC 96A8
E7AD 9072
E7AE 9082
E7AF 907D
E7B0 9081
E7B1 9080
E7B2 908A
E7B3 9089
E7B4 908F
E7B5 90A8
E7B6 90AF
E7B7 90B1
E7B8 90B5
E7B9 90E2
E7BA 90E4
E7BB 6248
E7BC 90DB
E7BD 9102
E7BE 9112
E7BF 9119
E7C0 9132
E7C1 9130
E7C2 914A
E7C3 9156
E7C4 9158
E7C5 9163
E7C6 9165
E7C7 9169
E7C8 9173
E7C9 9172
E7CA 918B
E7CB 9189
E7CC 9182
E7CD 91A2
E7CE 91AB
E7CF 91AF
E7D0 91AA
E7D1 91B5
E7D2 91B4
E7D3 91BA
E7D4 91C0
E7D5 91C1
E7D6 91C9
E7D7 91CB
E7D8 91D0
E7D9 91D6
E7DA 91DF
E7DB 91E1
E7DC 91DB
E7DD 91FC
E7DE 91F5
E7DF 91F6
E7E0 921E
E7E1 91FF
E7E2 9214
E7E3 922C
E7E4 9215
E7E5 9211
E7E6 925E
E7E7 9257
E7E8 9245
E7E9 9249
E7EA 9264
E7EB 9248
E7EC 9295
E7ED 923F
E7EE 924B
E7EF 9250
E7F0 929C
E7F1 9296
E7F2 9293
E7F3 929B
E7F4 925A
E7F5 92CF
E7F6 92B9
E7F7 92B7
E7F8 92E9
E7F9 930F
E7FA 92FA
E7FB 9344
E7FC 932E
E840 9319
E841 9322
E842 931A
E843 9323
E844 933A
E845 9335
E846 933B
E847 935C
E848 9360
E849 937C
E84A 936E
E84B 9356
E84C 93B0
E84D 93AC
E84E 93AD
E84F 9394
E850 93B9
E851 93D6
E852 93D7
E853 93E8
E854 93E5
E855 93D8
E856 93C3
E857 93DD
E858 93D0
E859 93C8
E85A 93E4
E85B 941A
E85C 9414
E85D 9413
E85E 9403
E85F 9407
E860 9410
E861 9436
E862 942B
E863 9435
E864 9421
E865 943A
E866 9441
E867 9452
E868 9444
E869 945B
E86A 9460
E86B 9462
E86C 945E
E86D 946A
E86E 9229
E86F 9470
E870 9475
E871 9477
E872 947D
E873 945A
E874 947C
E875 947E
E876 9481
E877 947F
E878 9582
E879 9587
E87A 958A
E87B 9594
E87C 9596
E87D 9598
E87E 9599
E880 95A0
E881 95A8
E882 95A7
E883 95AD
E884 95BC
E885 95BB
E886 95B9
E887 95BE
E888 95CA
E889 6FF6
E88A 95C3
E88B 95CD
E88C 95CC
E88D 95D5
E88E 95D4
E88F 95D6
E890 95DC
E891 95E1
E892 95E5
E893 95E2
E894 9621
E895 9628
E896 962E
E897 962F
E898 9642
E899 964C
E89A 964F
E89B 964B
E89C 9677
E89D 965C
E89E 965E
E89F 965D
E8A0 965F
E8A1 9666
E8A2 9672
E8A3 966C
E8A4 968D
E8A5 9698
E8A6 9695
E8A7 9697
E8A8 96AA
E8A9 96A7
E8AA 96B1
E8AB 96B2
E8AC 96B0
E8AD 96B4
E8AE 96B6
E8AF 96B8
E8B0 96B9
E8B1 96CE
E8B2 96CB
E8B3 96C9
E8B4 96CD
E8B5 894D
E8B6 96DC
E8B7 970D
E8B8 96D5
E8B9 96F9
E8BA 9704
E8BB 9706
E8BC 9708
E8BD 9713
E8BE 970E
E8BF 9711
E8C0 970F
E8C1 9716
E8C2 9719
E8C3 9724
E8C4 972A
E8C5 9730
E8C6 9739
E8C7 973D
E8C8 973E
E8C9 9744
E8CA 9746
E8CB 9748
E8CC 9742
E8CD 9749
E8CE 975C
E8CF 9760
E8D0 9764
E8D1 9766
E8D2 9768
E8D3 52D2
E8D4 976B
E8D5 9771
E8D6 9779
E8D7 9785
E8D8 977C
E8D9 9781
E8DA 977A
E8DB 9786
E8DC 978B
E8DD 978F
E8DE 9790
E8DF 979C
E8E0 97A8
E8E1 97A6
E8E2 97A3
E8E3 97B3
E8E4 97B4
E8E5 97C3
E8E6 97C6
E8E7 97C8
E8E8 97CB
E8E9 97DC
E8EA 97ED
E8EB 9F4F
E8EC 97F2
E8ED 7ADF
E8EE 97F6
E8EF 97F5
E8F0 980F
E8F1 980C
E8F2 9838
E8F3 9824
E8F4 9821
E8F5 9837
E8F6 983D
E8F7 9846
E8F8 984F
E8F9 984B
E8FA 986B
E8FB 986F
E8FC 9870
E940 9871
E941 9874
E942 9873
E943 98AA
E944 98AF
E945 98B1
E946 98B6
E947 98C4
E948 98C3
E949 98C6
E94A 98E9
E94B 98EB
E94C 9903
E94D 9909
E94E 9912
E94F 9914
E950 9918
E951 9921
E952 991D
E953 991E
E954 9924
E955 9920
E956 992C
E957 992E
E958 993D
E959 993E
E95A 9942
E95B 9949
E95C 9945
E95D 9950
E95E 994B
E95F 9951
E960 9952
E961 994C
E962 9955
E963 9997
E964 9998
E965 99A5
E966 99AD
E967 99AE
E968 99BC
E969 99DF
E96A 99DB
E96B 99DD
E96C 99D8
E96D 99D1
E96E 99ED
E96F 99EE
E970 99F1
E971 99F2
E972 99FB
E973 99F8
E974 9A01
E975 9A0F
E976 9A05
E977 99E2
E978 9A19
E979 9A2B
E97A 9A37
E97B 9A45
E97C 9A42
E97D 9A40
E97E 9A43
E980 9A3E
E981 9A55
E982 9A4D
E983 9A5B
E984 9A57
E985 9A5F
E986 9A62
E987 9A65
E988 9A64
E989 9A69
E98A 9A6B
E98B 9A6A
E98C 9AAD
E98D 9AB0
E98E 9ABC
E98F 9AC0
E990 9ACF
E991 9AD1
E992 9AD3
E993 9AD4
E994 9ADE
E995 9ADF
E996 9AE2
E997 9AE3
E998 9AE6
E999 9AEF
E99A 9AEB
E99B 9AEE
E99C 9AF4
E99D 9AF1
E99E 9AF7
E99F 9AFB
E9A0 9B06
E9A1 9B18
E9A2 9B1A
E9A3 9B1F
E9A4 9B22
E9A5 9B23
E9A6 9B25
E9A7 9B27
E9A8 9B28
E9A9 9B29
E9AA 9B2A
E9AB 9B2E
E9AC 9B2F
E9AD 9B32
E9AE 9B44
E9AF 9B43
E9B0 9B4F
E9B1 9B4D
E9B2 9B4E
E9B3 9B51
E9B4 9B58
E9B5 9B74
E9B6 9B93
E9B7 9B83
E9B8 9B91
E9B9 9B96
E9BA 9B97
E9BB 9B9F
E9BC 9BA0
E9BD 9BA8
E9BE 9BB4
E9BF 9BC0
E9C0 9BCA
E9C1 9BB9
E9C2 9BC6
E9C3 9BCF
E9C4 9BD1
E9C5 9BD2
E9C6 9BE3
E9C7 9BE2
E9C8 9BE4
E9C9 9BD4
E9CA 9BE1
E9CB 9C3A
E9CC 9BF2
E9CD 9BF1
E9CE 9BF0
E9CF 9C15
E9D0 9C14
E9D1 9C09
E9D2 9C13
E9D3 9C0C
E9D4 9C06
E9D5 9C08
E9D6 9C12
E9D7 9C0A
E9D8 9C04
E9D9 9C2E
E9DA 9C1B
E9DB 9C25
E9DC 9C24
E9DD 9C21
E9DE 9C30
E9DF 9C47
E9E0 9C32
E9E1 9C46
E9E2 9C3E
E9E3 9C5A
E9E4 9C60
E9E5 9C67
E9E6 9C76
E9E7 9C78
E9E8 9CE7
E9E9 9CEC
E9EA 9CF0
E9EB 9D09
E9EC 9D08
E9ED 9CEB
E9EE 9D03
E9EF 9D06
E9F0 9D2A
E9F1 9D26
E9F2 9DAF
E9F3 9D23
E9F4 9D1F
E9F5 9D44
E9F6 9D15
E9F7 9D12
E9F8 9D41
E9F9 9D3F
E9FA 9D3E
E9FB 9D46
E9FC 9D48
EA40 9D5D
EA41 9D5E
EA42 9D64
EA43 9D51
EA44 9D50
EA45 9D59
EA46 9D72
EA47 9D89
EA48 9D87
EA49 9DAB
EA4A 9D6F
EA4B 9D7A
EA4C 9D9A
EA4D 9DA4
EA4E 9DA9
EA4F 9DB2
EA50 9DC4
EA51 9DC1
EA52 9DBB
EA53 9DB8
EA54 9DBA
EA55 9DC6
EA56 9DCF
EA57 9DC2
EA58 9DD9
EA59 9DD3
EA5A 9DF8
EA5B 9DE6
EA5C 9DED
EA5D 9DEF
EA5E 9DFD
EA5F 9E1A
EA60 9E1B
EA61 9E1E
EA62 9E75
EA63 9E79
EA64 9E7D
EA65 9E81
EA66 9E88
EA67 9E8B
EA68 9E8C
EA69 9E92
EA6A 9E95
EA6B 9E91
EA6C 9E9D
EA6D 9EA5
EA6E 9EA9
EA6F 9EB8
EA70 9EAA
EA71 9EAD
EA72 9761
EA73 9ECC
EA74 9ECE
EA75 9ECF
EA76 9ED0
EA77 9ED4
EA78 9EDC
EA79 9EDE
EA7A 9EDD
EA7B 9EE0
EA7C 9EE5
EA7D 9EE8
EA7E 9EEF
EA80 9EF4
EA81 9EF6
EA82 9EF7
EA83 9EF9
EA84 9EFB
EA85 9EFC
EA86 9EFD
EA87 9F07
EA88 9F08
EA89 76B7
EA8A 9F15
EA8B 9F21
EA8C 9F2C
EA8D 9F3E
EA8E 9F4A
EA8F 9F52
EA90 9F54
EA91 9F63
EA92 9F5F
EA93 9F60
EA94 9F61
EA95 9F66
EA96 9F67
EA97 9F6C
EA98 9F6A
EA99 9F77
EA9A 9F72
EA9B 9F76
EA9C 9F95
EA9D 9F9C
EA9E 9FA0
EA9F 582F
EAA0 69C7
EAA1 9059
EAA2 7464
EAA3 51DC
EAA4 7199
ED40 7E8A
ED41 891C
ED42 9348
ED43 9288
ED44 84DC
ED45 4FC9
ED46 70BB
ED47 6631
ED48 68C8
ED49 92F9
ED4A 66FB
ED4B 5F45
ED4C 4E28
ED4D 4EE1
ED4E 4EFC
ED4F 4F00
ED50 4F03
ED51 4F39
ED52 4F56
ED53 4F92
ED54 4F8A
ED55 4F9A
ED56 4F94
ED57 4FCD
ED58 5040
ED59 5022
ED5A 4FFF
ED5B 501E
ED5C 5046
ED5D 5070
ED5E 5042
ED5F 5094
ED60 50F4
ED61 50D8
ED62 514A
ED63 5164
ED64 519D
ED65 51BE
ED66 51EC
ED67 5215
ED68 529C
ED69 52A6
ED6A 52C0
ED6B 52DB
ED6C 5300
ED6D 5307
ED6E 5324
ED6F 5372
ED70 5393
ED71 53B2
ED72 53DD
ED73 FA0E
ED74 549C
ED75 548A
ED76 54A9
ED77 54FF
ED78 5586
ED79 5759
ED7A 5765
ED7B 57AC
ED7C 57C8
ED7D 57C7
ED7E FA0F
ED80 FA10
ED81 589E
ED82 58B2
ED83 590B
ED84 5953
ED85 595B
ED86 595D
ED87 5963
ED88 59A4
ED89 59BA
ED8A 5B56
ED8B 5BC0
ED8C 752F
ED8D 5BD8
ED8E 5BEC
ED8F 5C1E
ED90 5CA6
ED91 5CBA
ED92 5CF5
ED93 5D27
ED94 5D53
ED95 FA11
ED96 5D42
ED97 5D6D
ED98 5DB8
ED99 5DB9
ED9A 5DD0
ED9B 5F21
ED9C 5F34
ED9D 5F67
ED9E 5FB7
ED9F 5FDE
EDA0 605D
EDA1 6085
EDA2 608A
EDA3 60DE
EDA4 60D5
EDA5 6120
EDA6 60F2
EDA7 6111
EDA8 6137
EDA9 6130
EDAA 6198
EDAB 6213
EDAC 62A6
EDAD 63F5
EDAE 6460
EDAF 649D
EDB0 64CE
EDB1 654E
EDB2 6600
EDB3 6615
EDB4 663B
EDB5 6609
EDB6 662E
EDB7 661E
EDB8 6624
EDB9 6665
EDBA 6657
EDBB 6659
EDBC FA12
EDBD 6673
EDBE 6699
EDBF 66A0
EDC0 66B2
EDC1 66BF
EDC2 66FA
EDC3 670E
EDC4 F929
EDC5 6766
EDC6 67BB
EDC7 6852
EDC8 67C0
EDC9 6801
EDCA 6844
EDCB 68CF
EDCC FA13
EDCD 6968
EDCE FA14
EDCF 6998
EDD0 69E2
EDD1 6A30
EDD2 6A6B
EDD3 6A46
EDD4 6A73
EDD5 6A7E
EDD6 6AE2
EDD7 6AE4
EDD8 6BD6
EDD9 6C3F
EDDA 6C5C
EDDB 6C86
EDDC 6C6F
EDDD 6CDA
EDDE 6D04
EDDF 6D87
EDE0 6D6F
EDE1 6D96
EDE2 6DAC
EDE3 6DCF
EDE4 6DF8
EDE5 6DF2
EDE6 6DFC
EDE7 6E39
EDE8 6E5C
EDE9 6E27
EDEA 6E3C
EDEB 6EBF
EDEC 6F88
EDED 6FB5
EDEE 6FF5
EDEF 7005
EDF0 7007
EDF1 7028
EDF2 7085
EDF3 70AB
EDF4 710F
EDF5 7104
EDF6 715C
EDF7 7146
EDF8 7147
EDF9 FA15
EDFA 71C1
EDFB 71FE
EDFC 72B1
EE40 72BE
EE41 7324
EE42 FA16
EE43 7377
EE44 73BD
EE45 73C9
EE46 73D6
EE47 73E3
EE48 73D2
EE49 7407
EE4A 73F5
EE4B 7426
EE4C 742A
EE4D 7429
EE4E 742E
EE4F 7462
EE50 7489
EE51 749F
EE52 7501
EE53 756F
EE54 7682
EE55 769C
EE56 769E
EE57 769B
EE58 76A6
EE59 FA17
EE5A 7746
EE5B 52AF
EE5C 7821
EE5D 784E
EE5E 7864
EE5F 787A
EE60 7930
EE61 FA18
EE62 FA19
EE63 FA1A
EE64 7994
EE65 FA1B
EE66 799B
EE67 7AD1
EE68 7AE7
EE69 FA1C
EE6A 7AEB
EE6B 7B9E
EE6C FA1D
EE6D 7D48
EE6E 7D5C
EE6F 7DB7
EE70 7DA0
EE71 7DD6
EE72 7E52
EE73 7F47
EE74 7FA1
EE75 FA1E
EE76 8301
EE77 8362
EE78 837F
EE79 83C7
EE7A 83F6
EE7B 8448
EE7C 84B4
EE7D 8553
EE7E 8559
EE80 856B
EE81 FA1F
EE82 85B0
EE83 FA20
EE84 FA21
EE85 8807
EE86 88F5
EE87 8A12
EE88 8A37
EE89 8A79
EE8A 8AA7
EE8B 8ABE
EE8C 8ADF
EE8D FA22
EE8E 8AF6
EE8F 8B53
EE90 8B7F
EE91 8CF0
EE92 8CF4
EE93 8D12
EE94 8D76
EE95 FA23
EE96 8ECF
EE97 FA24
EE98 FA25
EE99 9067
EE9A 90DE
EE9B FA26
EE9C 9115
EE9D 9127
EE9E 91DA
EE9F 91D7
EEA0 91DE
EEA1 91ED
EEA2 91EE
EEA3 91E4
EEA4 91E5
EEA5 9206
EEA6 9210
EEA7 920A
EEA8 923A
EEA9 9240
EEAA 923C
EEAB 924E
EEAC 9259
EEAD 9251
EEAE 9239
EEAF 9267
EEB0 92A7
EEB1 9277
EEB2 9278
EEB3 92E7
EEB4 92D7
EEB5 92D9
EEB6 92D0
EEB7 FA27
EEB8 92D5
EEB9 92E0
EEBA 92D3
EEBB 9325
EEBC 9321
EEBD 92FB
EEBE FA28
EEBF 931E
EEC0 92FF
EEC1 931D
EEC2 9302
EEC3 9370
EEC4 9357
EEC5 93A4
EEC6 93C6
EEC7 93DE
EEC8 93F8
EEC9 9431
EECA 9445
EECB 9448
EECC 9592
EECD F9DC
EECE FA29
EECF 969D
EED0 96AF
EED1 9733
EED2 973B
EED3 9743
EED4 974D
EED5 974F
EED6 9751
EED7 9755
EED8 9857
EED9 9865
EEDA FA2A
EEDB FA2B
EEDC 9927
EEDD FA2C
EEDE 999E
EEDF 9A4E
EEE0 9AD9
EEE1 9ADC
EEE2 9B75
EEE3 9B72
EEE4 9B8F
EEE5 9BB1
EEE6 9BBB
EEE7 9C00
EEE8 9D70
EEE9 9D6B
EEEA FA2D
EEEB 9E19
EEEC 9ED1
EEEF 2170
EEF0 2171
EEF1 2172
EEF2 2173
EEF3 2174
EEF4 2175
EEF5 2176
EEF6 2177
EEF7 2178
EEF8 2179
EEF9 FFE2
EEFA FFE4
EEFB FF07
EEFC FF02
FA40 2170
FA41 2171
FA42 2172
FA43 2173
FA44 2174
FA45 2175
FA46 2176
FA47 2177
FA48 2178
FA49 2179
FA4A 2160
FA4B 2161
FA4C 2162
FA4D 2163
FA4E 2164
FA4F 2165
FA50 2166
FA51 2167
FA52 2168
FA53 2169
FA54 FFE2
FA55 FFE4
FA56 FF07
FA57 FF02
FA58 3231
FA59 2116
FA5A 2121
FA5B 2235
FA5C 7E8A
FA5D 891C
FA5E 9348
FA5F 9288
FA60 84DC
FA61 4FC9
FA62 70BB
FA63 6631
FA64 68C8
FA65 92F9
FA66 66FB
FA67 5F45
FA68 4E28
FA69 4EE1
FA6A 4EFC
FA6B 4F00
FA6C 4F03
FA6D 4F39
FA6E 4F56
FA6F 4F92
FA70 4F8A
FA71 4F9A
FA72 4F94
FA73 4FCD
FA74 5040
FA75 5022
FA76 4FFF
FA77 501E
FA78 5046
FA79 5070
FA7A 5042
FA7B 5094
FA7C 50F4
FA7D 50D8
FA7E 514A
FA80 5164
FA81 519D
FA82 51BE
FA83 51EC
FA84 5215
FA85 529C
FA86 52A6
FA87 52C0
FA88 52DB
FA89 5300
FA8A 5307
FA8B 5324
FA8C 5372
FA8D 5393
FA8E 53B2
FA8F 53DD
FA90 FA0E
FA91 549C
FA92 548A
FA93 54A9
FA94 54FF
FA95 5586
FA96 5759
FA97 5765
FA98 57AC
FA99 57C8
FA9A 57C7
FA9B FA0F
FA9C FA10
FA9D 589E
FA9E 58B2
FA9F 590B
FAA0 5953
FAA1 595B
FAA2 595D
FAA3 5963
FAA4 59A4
FAA5 59BA
FAA6 5B56
FAA7 5BC0
FAA8 752F
FAA9 5BD8
FAAA 5BEC
FAAB 5C1E
FAAC 5CA6
FAAD 5CBA
FAAE 5CF5
FAAF 5D27
FAB0 5D53
FAB1 FA11
FAB2 5D42
FAB3 5D6D
FAB4 5DB8
FAB5 5DB9
FAB6 5DD0
FAB7 5F21
FAB8 5F34
FAB9 5F67
FABA 5FB7
FABB 5FDE
FABC 605D
FABD 6085
FABE 608A
FABF 60DE
FAC0 60D5
FAC1 6120
FAC2 60F2
FAC3 6111
FAC4 6137
FAC5 6130
FAC6 6198
FAC7 6213
FAC8 62A6
FAC9 63F5
FACA 6460
FACB 649D
FACC 64CE
FACD 654E
FACE 6600
FACF 6615
FAD0 663B
FAD1 6609
FAD2 662E
FAD3 661E
FAD4 6624
FAD5 6665
FAD6 6657
FAD7 6659
FAD8 FA12
FAD9 6673
FADA 6699
FADB 66A0
FADC 66B2
FADD 66BF
FADE 66FA
FADF 670E
FAE0 F929
FAE1 6766
FAE2 67BB
FAE3 6852
FAE4 67C0
FAE5 6801
FAE6 6844
FAE7 68CF
FAE8 FA13
FAE9 6968
FAEA FA14
FAEB 6998
FAEC 69E2
FAED 6A30
FAEE 6A6B
FAEF 6A46
FAF0 6A73
FAF1 6A7E
FAF2 6AE2
FAF3 6AE4
FAF4 6BD6
FAF5 6C3F
FAF6 6C5C
FAF7 6C86
FAF8 6C6F
FAF9 6CDA
FAFA 6D04
FAFB 6D87
FAFC 6D6F
FB40 6D96
FB41 6DAC
FB42 6DCF
FB43 6DF8
FB44 6DF2
FB45 6DFC
FB46 6E39
FB47 6E5C
FB48 6E27
FB49 6E3C
FB4A 6EBF
FB4B 6F88
FB4C 6FB5
FB4D 6FF5
FB4E 7005
FB4F 7007
FB50 7028
FB51 7085
FB52 70AB
FB53 710F
FB54 7104
FB55 715C
FB56 7146
FB57 7147
FB58 FA15
FB59 71C1
FB5A 71FE
FB5B 72B1
FB5C 72BE
FB5D 7324
FB5E FA16
FB5F 7377
FB60 73BD
FB61 73C9
FB62 73D6
FB63 73E3
FB64 73D2
FB65 7407
FB66 73F5
FB67 7426
FB68 742A
FB69 7429
FB6A 742E
FB6B 7462
FB6C 7489
FB6D 749F
FB6E 7501
FB6F 756F
FB70 7682
FB71 769C
FB72 769E
FB73 769B
FB74 76A6
FB75 FA17
FB76 7746
FB77 52AF
FB78 7821
FB79 784E
FB7A 7864
FB7B 787A
FB7C 7930
FB7D FA18
FB7E FA19
FB80 FA1A
FB81 7994
FB82 FA1B
FB83 799B
FB84 7AD1
FB85 7AE7
FB86 FA1C
FB87 7AEB
FB88 7B9E
FB89 FA1D
FB8A 7D48
FB8B 7D5C
FB8C 7DB7
FB8D 7DA0
FB8E 7DD6
FB8F 7E52
FB90 7F47
FB91 7FA1
FB92 FA1E
FB93 8301
FB94 8362
FB95 837F
FB96 83C7
FB97 83F6
FB98 8448
FB99 84B4
FB9A 8553
FB9B 8559
FB9C 856B
FB9D FA1F
FB9E 85B0
FB9F FA20
FBA0 FA21
FBA1 8807
FBA2 88F5
FBA3 8A12
FBA4 8A37
FBA5 8A79
FBA6 8AA7
FBA7 8ABE
FBA8 8ADF
FBA9 FA22
FBAA 8AF6
FBAB 8B53
FBAC 8B7F
FBAD 8CF0
FBAE 8CF4
FBAF 8D12
FBB0 8D76
FBB1 FA23
FBB2 8ECF
FBB3 FA24
FBB4 FA25
FBB5 9067
FBB6 90DE
FBB7 FA26
FBB8 9115
FBB9 9127
FBBA 91DA
FBBB 91D7
FBBC 91DE
FBBD 91ED
FBBE 91EE
FBBF 91E4
FBC0 91E5
FBC1 9206
FBC2 9210
FBC3 920A
FBC4 923A
FBC5 9240
FBC6 923C
FBC7 924E
FBC8 9259
FBC9 9251
FBCA 9239
FBCB 9267
FBCC 92A7
FBCD 9277
FBCE 9278
FBCF 92E7
FBD0 92D7
FBD1 92D9
FBD2 92D0
FBD3 FA27
FBD4 92D5
FBD5 92E0
FBD6 92D3
FBD7 9325
FBD8 9321
FBD9 92FB
FBDA FA28
FBDB 931E
FBDC 92FF
FBDD 931D
FBDE 9302
FBDF 9370
FBE0 9357
FBE1 93A4
FBE2 93C6
FBE3 93DE
FBE4 93F8
FBE5 9431
FBE6 9445
FBE7 9448
FBE8 9592
FBE9 F9DC
FBEA FA29
FBEB 969D
FBEC 96AF
FBED 9733
FBEE 973B
FBEF 9743
FBF0 974D
FBF1 974F
FBF2 9751
FBF3 9755
FBF4 9857
FBF5 9865
FBF6 FA2A
FBF7 FA2B
FBF8 9927
FBF9 FA2C
FBFA 999E
FBFB 9A4E
FBFC 9AD9
FC40 9ADC
FC41 9B75
FC42 9B72
FC43 9B8F
FC44 9BB1
FC45 9BBB
FC46 9C00
FC47 9D70
FC48 9D6B
FC49 FA2D
FC4A 9E19
FC4B 9ED1
| 79,439 | 7,999 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_smtplib.py | import asyncore
import base64
import email.mime.text
from email.message import EmailMessage
from email.base64mime import body_encode as encode_base64
import email.utils
import hmac
import socket
import smtpd
import smtplib
import io
import re
import sys
import time
import select
import errno
import textwrap
import unittest
from test import support, mock_socket
from unittest.mock import Mock
HOST = "localhost"
HOSTv4 = "127.0.0.1"
HOSTv6 = "::1"
try:
import _thread
import threading
except ImportError:
threading = None
HOST = support.HOST
if sys.platform == 'darwin':
# select.poll returns a select.POLLHUP at the end of the tests
# on darwin, so just ignore it
def handle_expt(self):
pass
smtpd.SMTPChannel.handle_expt = handle_expt
def server(evt, buf, serv):
serv.listen()
evt.set()
try:
conn, addr = serv.accept()
except socket.timeout:
pass
else:
n = 500
while buf and n > 0:
r, w, e = select.select([], [conn], [])
if w:
sent = conn.send(buf)
buf = buf[sent:]
n -= 1
conn.close()
finally:
serv.close()
evt.set()
class GeneralTests(unittest.TestCase):
def setUp(self):
smtplib.socket = mock_socket
self.port = 25
def tearDown(self):
smtplib.socket = socket
# This method is no longer used but is retained for backward compatibility,
# so test to make sure it still works.
def testQuoteData(self):
teststr = "abc\n.jkl\rfoo\r\n..blue"
expected = "abc\r\n..jkl\r\nfoo\r\n...blue"
self.assertEqual(expected, smtplib.quotedata(teststr))
def testBasic1(self):
mock_socket.reply_with(b"220 Hola mundo")
# connects
smtp = smtplib.SMTP(HOST, self.port)
smtp.close()
def testSourceAddress(self):
mock_socket.reply_with(b"220 Hola mundo")
# connects
smtp = smtplib.SMTP(HOST, self.port,
source_address=('127.0.0.1',19876))
self.assertEqual(smtp.source_address, ('127.0.0.1', 19876))
smtp.close()
def testBasic2(self):
mock_socket.reply_with(b"220 Hola mundo")
# connects, include port in host name
smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
smtp.close()
def testLocalHostName(self):
mock_socket.reply_with(b"220 Hola mundo")
# check that supplied local_hostname is used
smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
self.assertEqual(smtp.local_hostname, "testhost")
smtp.close()
def testTimeoutDefault(self):
mock_socket.reply_with(b"220 Hola mundo")
self.assertIsNone(mock_socket.getdefaulttimeout())
mock_socket.setdefaulttimeout(30)
self.assertEqual(mock_socket.getdefaulttimeout(), 30)
try:
smtp = smtplib.SMTP(HOST, self.port)
finally:
mock_socket.setdefaulttimeout(None)
self.assertEqual(smtp.sock.gettimeout(), 30)
smtp.close()
def testTimeoutNone(self):
mock_socket.reply_with(b"220 Hola mundo")
self.assertIsNone(socket.getdefaulttimeout())
socket.setdefaulttimeout(30)
try:
smtp = smtplib.SMTP(HOST, self.port, timeout=None)
finally:
socket.setdefaulttimeout(None)
self.assertIsNone(smtp.sock.gettimeout())
smtp.close()
def testTimeoutValue(self):
mock_socket.reply_with(b"220 Hola mundo")
smtp = smtplib.SMTP(HOST, self.port, timeout=30)
self.assertEqual(smtp.sock.gettimeout(), 30)
smtp.close()
def test_debuglevel(self):
mock_socket.reply_with(b"220 Hello world")
smtp = smtplib.SMTP()
smtp.set_debuglevel(1)
with support.captured_stderr() as stderr:
smtp.connect(HOST, self.port)
smtp.close()
expected = re.compile(r"^connect:", re.MULTILINE)
self.assertRegex(stderr.getvalue(), expected)
def test_debuglevel_2(self):
mock_socket.reply_with(b"220 Hello world")
smtp = smtplib.SMTP()
smtp.set_debuglevel(2)
with support.captured_stderr() as stderr:
smtp.connect(HOST, self.port)
smtp.close()
expected = re.compile(r"^\d{2}:\d{2}:\d{2}\.\d{6} connect: ",
re.MULTILINE)
self.assertRegex(stderr.getvalue(), expected)
# Test server thread using the specified SMTP server class
def debugging_server(serv, serv_evt, client_evt):
serv_evt.set()
try:
if hasattr(select, 'poll'):
poll_fun = asyncore.poll2
else:
poll_fun = asyncore.poll
n = 1000
while asyncore.socket_map and n > 0:
poll_fun(0.01, asyncore.socket_map)
# when the client conversation is finished, it will
# set client_evt, and it's then ok to kill the server
if client_evt.is_set():
serv.close()
break
n -= 1
except socket.timeout:
pass
finally:
if not client_evt.is_set():
# allow some time for the client to read the result
time.sleep(0.5)
serv.close()
asyncore.close_all()
serv_evt.set()
MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
MSG_END = '------------ END MESSAGE ------------\n'
# NOTE: Some SMTP objects in the tests below are created with a non-default
# local_hostname argument to the constructor, since (on some systems) the FQDN
# lookup caused by the default local_hostname sometimes takes so long that the
# test server times out, causing the test to fail.
# Test behavior of smtpd.DebuggingServer
@unittest.skipUnless(threading, 'Threading required for this test.')
class DebuggingServerTests(unittest.TestCase):
maxDiff = None
def setUp(self):
self.real_getfqdn = socket.getfqdn
socket.getfqdn = mock_socket.getfqdn
# temporarily replace sys.stdout to capture DebuggingServer output
self.old_stdout = sys.stdout
self.output = io.StringIO()
sys.stdout = self.output
self.serv_evt = threading.Event()
self.client_evt = threading.Event()
# Capture SMTPChannel debug output
self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
smtpd.DEBUGSTREAM = io.StringIO()
# Pick a random unused port by passing 0 for the port number
self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1),
decode_data=True)
# Keep a note of what port was assigned
self.port = self.serv.socket.getsockname()[1]
serv_args = (self.serv, self.serv_evt, self.client_evt)
self.thread = threading.Thread(target=debugging_server, args=serv_args)
self.thread.start()
# wait until server thread has assigned a port number
self.serv_evt.wait()
self.serv_evt.clear()
def tearDown(self):
socket.getfqdn = self.real_getfqdn
# indicate that the client is finished
self.client_evt.set()
# wait for the server thread to terminate
self.serv_evt.wait()
self.thread.join()
# restore sys.stdout
sys.stdout = self.old_stdout
# restore DEBUGSTREAM
smtpd.DEBUGSTREAM.close()
smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
def testBasic(self):
# connect
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
smtp.quit()
def testSourceAddress(self):
# connect
port = support.find_unused_port()
try:
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
timeout=3, source_address=('127.0.0.1', port))
self.assertEqual(smtp.source_address, ('127.0.0.1', port))
self.assertEqual(smtp.local_hostname, 'localhost')
smtp.quit()
except OSError as e:
if e.errno == errno.EADDRINUSE:
self.skipTest("couldn't bind to port %d" % port)
raise
def testNOOP(self):
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
expected = (250, b'OK')
self.assertEqual(smtp.noop(), expected)
smtp.quit()
def testRSET(self):
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
expected = (250, b'OK')
self.assertEqual(smtp.rset(), expected)
smtp.quit()
def testELHO(self):
# EHLO isn't implemented in DebuggingServer
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
expected = (250, b'\nSIZE 33554432\nHELP')
self.assertEqual(smtp.ehlo(), expected)
smtp.quit()
def testEXPNNotImplemented(self):
# EXPN isn't implemented in DebuggingServer
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
expected = (502, b'EXPN not implemented')
smtp.putcmd('EXPN')
self.assertEqual(smtp.getreply(), expected)
smtp.quit()
def testVRFY(self):
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
expected = (252, b'Cannot VRFY user, but will accept message ' + \
b'and attempt delivery')
self.assertEqual(smtp.vrfy('[email protected]'), expected)
self.assertEqual(smtp.verify('[email protected]'), expected)
smtp.quit()
def testSecondHELO(self):
# check that a second HELO returns a message that it's a duplicate
# (this behavior is specific to smtpd.SMTPChannel)
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
smtp.helo()
expected = (503, b'Duplicate HELO/EHLO')
self.assertEqual(smtp.helo(), expected)
smtp.quit()
def testHELP(self):
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
self.assertEqual(smtp.help(), b'Supported commands: EHLO HELO MAIL ' + \
b'RCPT DATA RSET NOOP QUIT VRFY')
smtp.quit()
def testSend(self):
# connect and send mail
m = 'A test message'
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
smtp.sendmail('John', 'Sally', m)
# XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
# in asyncore. This sleep might help, but should really be fixed
# properly by using an Event variable.
time.sleep(0.01)
smtp.quit()
self.client_evt.set()
self.serv_evt.wait()
self.output.flush()
mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
self.assertEqual(self.output.getvalue(), mexpect)
def testSendBinary(self):
m = b'A test message'
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
smtp.sendmail('John', 'Sally', m)
# XXX (see comment in testSend)
time.sleep(0.01)
smtp.quit()
self.client_evt.set()
self.serv_evt.wait()
self.output.flush()
mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
self.assertEqual(self.output.getvalue(), mexpect)
def testSendNeedingDotQuote(self):
# Issue 12283
m = '.A test\n.mes.sage.'
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
smtp.sendmail('John', 'Sally', m)
# XXX (see comment in testSend)
time.sleep(0.01)
smtp.quit()
self.client_evt.set()
self.serv_evt.wait()
self.output.flush()
mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
self.assertEqual(self.output.getvalue(), mexpect)
def testSendNullSender(self):
m = 'A test message'
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
smtp.sendmail('<>', 'Sally', m)
# XXX (see comment in testSend)
time.sleep(0.01)
smtp.quit()
self.client_evt.set()
self.serv_evt.wait()
self.output.flush()
mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
self.assertEqual(self.output.getvalue(), mexpect)
debugout = smtpd.DEBUGSTREAM.getvalue()
sender = re.compile("^sender: <>$", re.MULTILINE)
self.assertRegex(debugout, sender)
def testSendMessage(self):
m = email.mime.text.MIMEText('A test message')
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
smtp.send_message(m, from_addr='John', to_addrs='Sally')
# XXX (see comment in testSend)
time.sleep(0.01)
smtp.quit()
self.client_evt.set()
self.serv_evt.wait()
self.output.flush()
# Add the X-Peer header that DebuggingServer adds
m['X-Peer'] = socket.gethostbyname('localhost')
mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
self.assertEqual(self.output.getvalue(), mexpect)
def testSendMessageWithAddresses(self):
m = email.mime.text.MIMEText('A test message')
m['From'] = '[email protected]'
m['To'] = 'John'
m['CC'] = 'Sally, Fred'
m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <[email protected]>'
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
smtp.send_message(m)
# XXX (see comment in testSend)
time.sleep(0.01)
smtp.quit()
# make sure the Bcc header is still in the message.
self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
'<[email protected]>')
self.client_evt.set()
self.serv_evt.wait()
self.output.flush()
# Add the X-Peer header that DebuggingServer adds
m['X-Peer'] = socket.gethostbyname('localhost')
# The Bcc header should not be transmitted.
del m['Bcc']
mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
self.assertEqual(self.output.getvalue(), mexpect)
debugout = smtpd.DEBUGSTREAM.getvalue()
sender = re.compile("^sender: [email protected]$", re.MULTILINE)
self.assertRegex(debugout, sender)
for addr in ('John', 'Sally', 'Fred', 'root@localhost',
'[email protected]'):
to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
re.MULTILINE)
self.assertRegex(debugout, to_addr)
def testSendMessageWithSomeAddresses(self):
# Make sure nothing breaks if not all of the three 'to' headers exist
m = email.mime.text.MIMEText('A test message')
m['From'] = '[email protected]'
m['To'] = 'John, Dinsdale'
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
smtp.send_message(m)
# XXX (see comment in testSend)
time.sleep(0.01)
smtp.quit()
self.client_evt.set()
self.serv_evt.wait()
self.output.flush()
# Add the X-Peer header that DebuggingServer adds
m['X-Peer'] = socket.gethostbyname('localhost')
mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
self.assertEqual(self.output.getvalue(), mexpect)
debugout = smtpd.DEBUGSTREAM.getvalue()
sender = re.compile("^sender: [email protected]$", re.MULTILINE)
self.assertRegex(debugout, sender)
for addr in ('John', 'Dinsdale'):
to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
re.MULTILINE)
self.assertRegex(debugout, to_addr)
def testSendMessageWithSpecifiedAddresses(self):
# Make sure addresses specified in call override those in message.
m = email.mime.text.MIMEText('A test message')
m['From'] = '[email protected]'
m['To'] = 'John, Dinsdale'
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
smtp.send_message(m, from_addr='[email protected]', to_addrs='[email protected]')
# XXX (see comment in testSend)
time.sleep(0.01)
smtp.quit()
self.client_evt.set()
self.serv_evt.wait()
self.output.flush()
# Add the X-Peer header that DebuggingServer adds
m['X-Peer'] = socket.gethostbyname('localhost')
mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
self.assertEqual(self.output.getvalue(), mexpect)
debugout = smtpd.DEBUGSTREAM.getvalue()
sender = re.compile("^sender: [email protected]$", re.MULTILINE)
self.assertRegex(debugout, sender)
for addr in ('John', 'Dinsdale'):
to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
re.MULTILINE)
self.assertNotRegex(debugout, to_addr)
recip = re.compile(r"^recips: .*'[email protected]'.*$", re.MULTILINE)
self.assertRegex(debugout, recip)
def testSendMessageWithMultipleFrom(self):
# Sender overrides To
m = email.mime.text.MIMEText('A test message')
m['From'] = 'Bernard, Bianca'
m['Sender'] = '[email protected]'
m['To'] = 'John, Dinsdale'
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
smtp.send_message(m)
# XXX (see comment in testSend)
time.sleep(0.01)
smtp.quit()
self.client_evt.set()
self.serv_evt.wait()
self.output.flush()
# Add the X-Peer header that DebuggingServer adds
m['X-Peer'] = socket.gethostbyname('localhost')
mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
self.assertEqual(self.output.getvalue(), mexpect)
debugout = smtpd.DEBUGSTREAM.getvalue()
sender = re.compile("^sender: [email protected]$", re.MULTILINE)
self.assertRegex(debugout, sender)
for addr in ('John', 'Dinsdale'):
to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
re.MULTILINE)
self.assertRegex(debugout, to_addr)
def testSendMessageResent(self):
m = email.mime.text.MIMEText('A test message')
m['From'] = '[email protected]'
m['To'] = 'John'
m['CC'] = 'Sally, Fred'
m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <[email protected]>'
m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
m['Resent-From'] = '[email protected]'
m['Resent-To'] = 'Martha <[email protected]>, Jeff'
m['Resent-Bcc'] = '[email protected]'
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
smtp.send_message(m)
# XXX (see comment in testSend)
time.sleep(0.01)
smtp.quit()
self.client_evt.set()
self.serv_evt.wait()
self.output.flush()
# The Resent-Bcc headers are deleted before serialization.
del m['Bcc']
del m['Resent-Bcc']
# Add the X-Peer header that DebuggingServer adds
m['X-Peer'] = socket.gethostbyname('localhost')
mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
self.assertEqual(self.output.getvalue(), mexpect)
debugout = smtpd.DEBUGSTREAM.getvalue()
sender = re.compile("^sender: [email protected]$", re.MULTILINE)
self.assertRegex(debugout, sender)
for addr in ('[email protected]', 'Jeff', '[email protected]'):
to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
re.MULTILINE)
self.assertRegex(debugout, to_addr)
def testSendMessageMultipleResentRaises(self):
m = email.mime.text.MIMEText('A test message')
m['From'] = '[email protected]'
m['To'] = 'John'
m['CC'] = 'Sally, Fred'
m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <[email protected]>'
m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
m['Resent-From'] = '[email protected]'
m['Resent-To'] = 'Martha <[email protected]>, Jeff'
m['Resent-Bcc'] = '[email protected]'
m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
m['Resent-To'] = '[email protected]'
m['Resent-From'] = 'Martha <[email protected]>, Jeff'
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
with self.assertRaises(ValueError):
smtp.send_message(m)
smtp.close()
class NonConnectingTests(unittest.TestCase):
def testNotConnected(self):
# Test various operations on an unconnected SMTP object that
# should raise exceptions (at present the attempt in SMTP.send
# to reference the nonexistent 'sock' attribute of the SMTP object
# causes an AttributeError)
smtp = smtplib.SMTP()
self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
self.assertRaises(smtplib.SMTPServerDisconnected,
smtp.send, 'test msg')
def testNonnumericPort(self):
# check that non-numeric port raises OSError
self.assertRaises(OSError, smtplib.SMTP,
"localhost", "bogus")
self.assertRaises(OSError, smtplib.SMTP,
"localhost:bogus")
class DefaultArgumentsTests(unittest.TestCase):
def setUp(self):
self.msg = EmailMessage()
self.msg['From'] = 'Páolo <fÅ[email protected]>'
self.smtp = smtplib.SMTP()
self.smtp.ehlo = Mock(return_value=(200, 'OK'))
self.smtp.has_extn, self.smtp.sendmail = Mock(), Mock()
def testSendMessage(self):
expected_mail_options = ('SMTPUTF8', 'BODY=8BITMIME')
self.smtp.send_message(self.msg)
self.smtp.send_message(self.msg)
self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
expected_mail_options)
self.assertEqual(self.smtp.sendmail.call_args_list[1][0][3],
expected_mail_options)
def testSendMessageWithMailOptions(self):
mail_options = ['STARTTLS']
expected_mail_options = ('STARTTLS', 'SMTPUTF8', 'BODY=8BITMIME')
self.smtp.send_message(self.msg, None, None, mail_options)
self.assertEqual(mail_options, ['STARTTLS'])
self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
expected_mail_options)
# test response of client to a non-successful HELO message
@unittest.skipUnless(threading, 'Threading required for this test.')
class BadHELOServerTests(unittest.TestCase):
def setUp(self):
smtplib.socket = mock_socket
mock_socket.reply_with(b"199 no hello for you!")
self.old_stdout = sys.stdout
self.output = io.StringIO()
sys.stdout = self.output
self.port = 25
def tearDown(self):
smtplib.socket = socket
sys.stdout = self.old_stdout
def testFailingHELO(self):
self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
HOST, self.port, 'localhost', 3)
@unittest.skipUnless(threading, 'Threading required for this test.')
class TooLongLineTests(unittest.TestCase):
respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n'
def setUp(self):
self.old_stdout = sys.stdout
self.output = io.StringIO()
sys.stdout = self.output
self.evt = threading.Event()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(15)
self.port = support.bind_port(self.sock)
servargs = (self.evt, self.respdata, self.sock)
thread = threading.Thread(target=server, args=servargs)
thread.start()
self.addCleanup(thread.join)
self.evt.wait()
self.evt.clear()
def tearDown(self):
self.evt.wait()
sys.stdout = self.old_stdout
def testLineTooLong(self):
self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
HOST, self.port, 'localhost', 3)
sim_users = {'[email protected]':'John A',
'[email protected]':'Sally B',
'[email protected]':'Ruth C',
}
sim_auth = ('[email protected]', 'somepassword')
sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
sim_lists = {'list-1':['[email protected]','[email protected]'],
'list-2':['[email protected]',],
}
# Simulated SMTP channel & server
class ResponseException(Exception): pass
class SimSMTPChannel(smtpd.SMTPChannel):
quit_response = None
mail_response = None
rcpt_response = None
data_response = None
rcpt_count = 0
rset_count = 0
disconnect = 0
AUTH = 99 # Add protocol state to enable auth testing.
authenticated_user = None
def __init__(self, extra_features, *args, **kw):
self._extrafeatures = ''.join(
[ "250-{0}\r\n".format(x) for x in extra_features ])
super(SimSMTPChannel, self).__init__(*args, **kw)
# AUTH related stuff. It would be nice if support for this were in smtpd.
def found_terminator(self):
if self.smtp_state == self.AUTH:
line = self._emptystring.join(self.received_lines)
print('Data:', repr(line), file=smtpd.DEBUGSTREAM)
self.received_lines = []
try:
self.auth_object(line)
except ResponseException as e:
self.smtp_state = self.COMMAND
self.push('%s %s' % (e.smtp_code, e.smtp_error))
return
super().found_terminator()
def smtp_AUTH(self, arg):
if not self.seen_greeting:
self.push('503 Error: send EHLO first')
return
if not self.extended_smtp or 'AUTH' not in self._extrafeatures:
self.push('500 Error: command "AUTH" not recognized')
return
if self.authenticated_user is not None:
self.push(
'503 Bad sequence of commands: already authenticated')
return
args = arg.split()
if len(args) not in [1, 2]:
self.push('501 Syntax: AUTH <mechanism> [initial-response]')
return
auth_object_name = '_auth_%s' % args[0].lower().replace('-', '_')
try:
self.auth_object = getattr(self, auth_object_name)
except AttributeError:
self.push('504 Command parameter not implemented: unsupported '
' authentication mechanism {!r}'.format(auth_object_name))
return
self.smtp_state = self.AUTH
self.auth_object(args[1] if len(args) == 2 else None)
def _authenticated(self, user, valid):
if valid:
self.authenticated_user = user
self.push('235 Authentication Succeeded')
else:
self.push('535 Authentication credentials invalid')
self.smtp_state = self.COMMAND
def _decode_base64(self, string):
return base64.decodebytes(string.encode('ascii')).decode('utf-8')
def _auth_plain(self, arg=None):
if arg is None:
self.push('334 ')
else:
logpass = self._decode_base64(arg)
try:
*_, user, password = logpass.split('\0')
except ValueError as e:
self.push('535 Splitting response {!r} into user and password'
' failed: {}'.format(logpass, e))
return
self._authenticated(user, password == sim_auth[1])
def _auth_login(self, arg=None):
if arg is None:
# base64 encoded 'Username:'
self.push('334 VXNlcm5hbWU6')
elif not hasattr(self, '_auth_login_user'):
self._auth_login_user = self._decode_base64(arg)
# base64 encoded 'Password:'
self.push('334 UGFzc3dvcmQ6')
else:
password = self._decode_base64(arg)
self._authenticated(self._auth_login_user, password == sim_auth[1])
del self._auth_login_user
def _auth_cram_md5(self, arg=None):
if arg is None:
self.push('334 {}'.format(sim_cram_md5_challenge))
else:
logpass = self._decode_base64(arg)
try:
user, hashed_pass = logpass.split()
except ValueError as e:
self.push('535 Splitting response {!r} into user and password '
'failed: {}'.format(logpass, e))
return False
valid_hashed_pass = hmac.HMAC(
sim_auth[1].encode('ascii'),
self._decode_base64(sim_cram_md5_challenge).encode('ascii'),
'md5').hexdigest()
self._authenticated(user, hashed_pass == valid_hashed_pass)
# end AUTH related stuff.
def smtp_EHLO(self, arg):
resp = ('250-testhost\r\n'
'250-EXPN\r\n'
'250-SIZE 20000000\r\n'
'250-STARTTLS\r\n'
'250-DELIVERBY\r\n')
resp = resp + self._extrafeatures + '250 HELP'
self.push(resp)
self.seen_greeting = arg
self.extended_smtp = True
def smtp_VRFY(self, arg):
# For max compatibility smtplib should be sending the raw address.
if arg in sim_users:
self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
else:
self.push('550 No such user: %s' % arg)
def smtp_EXPN(self, arg):
list_name = arg.lower()
if list_name in sim_lists:
user_list = sim_lists[list_name]
for n, user_email in enumerate(user_list):
quoted_addr = smtplib.quoteaddr(user_email)
if n < len(user_list) - 1:
self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
else:
self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
else:
self.push('550 No access for you!')
def smtp_QUIT(self, arg):
if self.quit_response is None:
super(SimSMTPChannel, self).smtp_QUIT(arg)
else:
self.push(self.quit_response)
self.close_when_done()
def smtp_MAIL(self, arg):
if self.mail_response is None:
super().smtp_MAIL(arg)
else:
self.push(self.mail_response)
if self.disconnect:
self.close_when_done()
def smtp_RCPT(self, arg):
if self.rcpt_response is None:
super().smtp_RCPT(arg)
return
self.rcpt_count += 1
self.push(self.rcpt_response[self.rcpt_count-1])
def smtp_RSET(self, arg):
self.rset_count += 1
super().smtp_RSET(arg)
def smtp_DATA(self, arg):
if self.data_response is None:
super().smtp_DATA(arg)
else:
self.push(self.data_response)
def handle_error(self):
raise
class SimSMTPServer(smtpd.SMTPServer):
channel_class = SimSMTPChannel
def __init__(self, *args, **kw):
self._extra_features = []
self._addresses = {}
smtpd.SMTPServer.__init__(self, *args, **kw)
def handle_accepted(self, conn, addr):
self._SMTPchannel = self.channel_class(
self._extra_features, self, conn, addr,
decode_data=self._decode_data)
def process_message(self, peer, mailfrom, rcpttos, data):
self._addresses['from'] = mailfrom
self._addresses['tos'] = rcpttos
def add_feature(self, feature):
self._extra_features.append(feature)
def handle_error(self):
raise
# Test various SMTP & ESMTP commands/behaviors that require a simulated server
# (i.e., something with more features than DebuggingServer)
@unittest.skipUnless(threading, 'Threading required for this test.')
class SMTPSimTests(unittest.TestCase):
def setUp(self):
self.real_getfqdn = socket.getfqdn
socket.getfqdn = mock_socket.getfqdn
self.serv_evt = threading.Event()
self.client_evt = threading.Event()
# Pick a random unused port by passing 0 for the port number
self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1), decode_data=True)
# Keep a note of what port was assigned
self.port = self.serv.socket.getsockname()[1]
serv_args = (self.serv, self.serv_evt, self.client_evt)
self.thread = threading.Thread(target=debugging_server, args=serv_args)
self.thread.start()
# wait until server thread has assigned a port number
self.serv_evt.wait()
self.serv_evt.clear()
def tearDown(self):
socket.getfqdn = self.real_getfqdn
# indicate that the client is finished
self.client_evt.set()
# wait for the server thread to terminate
self.serv_evt.wait()
self.thread.join()
def testBasic(self):
# smoke test
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
smtp.quit()
def testEHLO(self):
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
# no features should be present before the EHLO
self.assertEqual(smtp.esmtp_features, {})
# features expected from the test server
expected_features = {'expn':'',
'size': '20000000',
'starttls': '',
'deliverby': '',
'help': '',
}
smtp.ehlo()
self.assertEqual(smtp.esmtp_features, expected_features)
for k in expected_features:
self.assertTrue(smtp.has_extn(k))
self.assertFalse(smtp.has_extn('unsupported-feature'))
smtp.quit()
def testVRFY(self):
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
for addr_spec, name in sim_users.items():
expected_known = (250, bytes('%s %s' %
(name, smtplib.quoteaddr(addr_spec)),
"ascii"))
self.assertEqual(smtp.vrfy(addr_spec), expected_known)
u = '[email protected]'
expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
self.assertEqual(smtp.vrfy(u), expected_unknown)
smtp.quit()
def testEXPN(self):
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
for listname, members in sim_lists.items():
users = []
for m in members:
users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
expected_known = (250, bytes('\n'.join(users), "ascii"))
self.assertEqual(smtp.expn(listname), expected_known)
u = 'PSU-Members-List'
expected_unknown = (550, b'No access for you!')
self.assertEqual(smtp.expn(u), expected_unknown)
smtp.quit()
def testAUTH_PLAIN(self):
self.serv.add_feature("AUTH PLAIN")
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
resp = smtp.login(sim_auth[0], sim_auth[1])
self.assertEqual(resp, (235, b'Authentication Succeeded'))
smtp.close()
def testAUTH_LOGIN(self):
self.serv.add_feature("AUTH LOGIN")
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
resp = smtp.login(sim_auth[0], sim_auth[1])
self.assertEqual(resp, (235, b'Authentication Succeeded'))
smtp.close()
def testAUTH_CRAM_MD5(self):
self.serv.add_feature("AUTH CRAM-MD5")
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
resp = smtp.login(sim_auth[0], sim_auth[1])
self.assertEqual(resp, (235, b'Authentication Succeeded'))
smtp.close()
def testAUTH_multiple(self):
# Test that multiple authentication methods are tried.
self.serv.add_feature("AUTH BOGUS PLAIN LOGIN CRAM-MD5")
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
resp = smtp.login(sim_auth[0], sim_auth[1])
self.assertEqual(resp, (235, b'Authentication Succeeded'))
smtp.close()
def test_auth_function(self):
supported = {'CRAM-MD5', 'PLAIN', 'LOGIN'}
for mechanism in supported:
self.serv.add_feature("AUTH {}".format(mechanism))
for mechanism in supported:
with self.subTest(mechanism=mechanism):
smtp = smtplib.SMTP(HOST, self.port,
local_hostname='localhost', timeout=15)
smtp.ehlo('foo')
smtp.user, smtp.password = sim_auth[0], sim_auth[1]
method = 'auth_' + mechanism.lower().replace('-', '_')
resp = smtp.auth(mechanism, getattr(smtp, method))
self.assertEqual(resp, (235, b'Authentication Succeeded'))
smtp.close()
def test_quit_resets_greeting(self):
smtp = smtplib.SMTP(HOST, self.port,
local_hostname='localhost',
timeout=15)
code, message = smtp.ehlo()
self.assertEqual(code, 250)
self.assertIn('size', smtp.esmtp_features)
smtp.quit()
self.assertNotIn('size', smtp.esmtp_features)
smtp.connect(HOST, self.port)
self.assertNotIn('size', smtp.esmtp_features)
smtp.ehlo_or_helo_if_needed()
self.assertIn('size', smtp.esmtp_features)
smtp.quit()
def test_with_statement(self):
with smtplib.SMTP(HOST, self.port) as smtp:
code, message = smtp.noop()
self.assertEqual(code, 250)
self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
with smtplib.SMTP(HOST, self.port) as smtp:
smtp.close()
self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
def test_with_statement_QUIT_failure(self):
with self.assertRaises(smtplib.SMTPResponseException) as error:
with smtplib.SMTP(HOST, self.port) as smtp:
smtp.noop()
self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
self.assertEqual(error.exception.smtp_code, 421)
self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
#TODO: add tests for correct AUTH method fallback now that the
#test infrastructure can support it.
# Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception
def test__rest_from_mail_cmd(self):
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
smtp.noop()
self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
self.serv._SMTPchannel.disconnect = True
with self.assertRaises(smtplib.SMTPSenderRefused):
smtp.sendmail('John', 'Sally', 'test message')
self.assertIsNone(smtp.sock)
# Issue 5713: make sure close, not rset, is called if we get a 421 error
def test_421_from_mail_cmd(self):
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
smtp.noop()
self.serv._SMTPchannel.mail_response = '421 closing connection'
with self.assertRaises(smtplib.SMTPSenderRefused):
smtp.sendmail('John', 'Sally', 'test message')
self.assertIsNone(smtp.sock)
self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
def test_421_from_rcpt_cmd(self):
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
smtp.noop()
self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
self.assertIsNone(smtp.sock)
self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
def test_421_from_data_cmd(self):
class MySimSMTPChannel(SimSMTPChannel):
def found_terminator(self):
if self.smtp_state == self.DATA:
self.push('421 closing')
else:
super().found_terminator()
self.serv.channel_class = MySimSMTPChannel
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
smtp.noop()
with self.assertRaises(smtplib.SMTPDataError):
smtp.sendmail('[email protected]', ['[email protected]'], 'test message')
self.assertIsNone(smtp.sock)
self.assertEqual(self.serv._SMTPchannel.rcpt_count, 0)
def test_smtputf8_NotSupportedError_if_no_server_support(self):
smtp = smtplib.SMTP(
HOST, self.port, local_hostname='localhost', timeout=3)
self.addCleanup(smtp.close)
smtp.ehlo()
self.assertTrue(smtp.does_esmtp)
self.assertFalse(smtp.has_extn('smtputf8'))
self.assertRaises(
smtplib.SMTPNotSupportedError,
smtp.sendmail,
'John', 'Sally', '', mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
self.assertRaises(
smtplib.SMTPNotSupportedError,
smtp.mail, 'John', options=['BODY=8BITMIME', 'SMTPUTF8'])
def test_send_unicode_without_SMTPUTF8(self):
smtp = smtplib.SMTP(
HOST, self.port, local_hostname='localhost', timeout=3)
self.addCleanup(smtp.close)
self.assertRaises(UnicodeEncodeError, smtp.sendmail, 'Alice', 'Böb', '')
self.assertRaises(UnicodeEncodeError, smtp.mail, 'Ãlice')
def test_send_message_error_on_non_ascii_addrs_if_no_smtputf8(self):
# This test is located here and not in the SMTPUTF8SimTests
# class because it needs a "regular" SMTP server to work
msg = EmailMessage()
msg['From'] = "Páolo <fÅ[email protected]>"
msg['To'] = 'Dinsdale'
msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
smtp = smtplib.SMTP(
HOST, self.port, local_hostname='localhost', timeout=3)
self.addCleanup(smtp.close)
with self.assertRaises(smtplib.SMTPNotSupportedError):
smtp.send_message(msg)
def test_name_field_not_included_in_envelop_addresses(self):
smtp = smtplib.SMTP(
HOST, self.port, local_hostname='localhost', timeout=3
)
self.addCleanup(smtp.close)
message = EmailMessage()
message['From'] = email.utils.formataddr(('Michaël', '[email protected]'))
message['To'] = email.utils.formataddr(('René', '[email protected]'))
self.assertDictEqual(smtp.send_message(message), {})
self.assertEqual(self.serv._addresses['from'], '[email protected]')
self.assertEqual(self.serv._addresses['tos'], ['[email protected]'])
class SimSMTPUTF8Server(SimSMTPServer):
def __init__(self, *args, **kw):
# The base SMTP server turns these on automatically, but our test
# server is set up to munge the EHLO response, so we need to provide
# them as well. And yes, the call is to SMTPServer not SimSMTPServer.
self._extra_features = ['SMTPUTF8', '8BITMIME']
smtpd.SMTPServer.__init__(self, *args, **kw)
def handle_accepted(self, conn, addr):
self._SMTPchannel = self.channel_class(
self._extra_features, self, conn, addr,
decode_data=self._decode_data,
enable_SMTPUTF8=self.enable_SMTPUTF8,
)
def process_message(self, peer, mailfrom, rcpttos, data, mail_options=None,
rcpt_options=None):
self.last_peer = peer
self.last_mailfrom = mailfrom
self.last_rcpttos = rcpttos
self.last_message = data
self.last_mail_options = mail_options
self.last_rcpt_options = rcpt_options
@unittest.skipUnless(threading, 'Threading required for this test.')
class SMTPUTF8SimTests(unittest.TestCase):
maxDiff = None
def setUp(self):
self.real_getfqdn = socket.getfqdn
socket.getfqdn = mock_socket.getfqdn
self.serv_evt = threading.Event()
self.client_evt = threading.Event()
# Pick a random unused port by passing 0 for the port number
self.serv = SimSMTPUTF8Server((HOST, 0), ('nowhere', -1),
decode_data=False,
enable_SMTPUTF8=True)
# Keep a note of what port was assigned
self.port = self.serv.socket.getsockname()[1]
serv_args = (self.serv, self.serv_evt, self.client_evt)
self.thread = threading.Thread(target=debugging_server, args=serv_args)
self.thread.start()
# wait until server thread has assigned a port number
self.serv_evt.wait()
self.serv_evt.clear()
def tearDown(self):
socket.getfqdn = self.real_getfqdn
# indicate that the client is finished
self.client_evt.set()
# wait for the server thread to terminate
self.serv_evt.wait()
self.thread.join()
def test_test_server_supports_extensions(self):
smtp = smtplib.SMTP(
HOST, self.port, local_hostname='localhost', timeout=3)
self.addCleanup(smtp.close)
smtp.ehlo()
self.assertTrue(smtp.does_esmtp)
self.assertTrue(smtp.has_extn('smtputf8'))
def test_send_unicode_with_SMTPUTF8_via_sendmail(self):
m = '¡a test message containing unicode!'.encode('utf-8')
smtp = smtplib.SMTP(
HOST, self.port, local_hostname='localhost', timeout=3)
self.addCleanup(smtp.close)
smtp.sendmail('JÅhn', 'Sálly', m,
mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
self.assertEqual(self.serv.last_mailfrom, 'JÅhn')
self.assertEqual(self.serv.last_rcpttos, ['Sálly'])
self.assertEqual(self.serv.last_message, m)
self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
self.assertIn('SMTPUTF8', self.serv.last_mail_options)
self.assertEqual(self.serv.last_rcpt_options, [])
def test_send_unicode_with_SMTPUTF8_via_low_level_API(self):
m = '¡a test message containing unicode!'.encode('utf-8')
smtp = smtplib.SMTP(
HOST, self.port, local_hostname='localhost', timeout=3)
self.addCleanup(smtp.close)
smtp.ehlo()
self.assertEqual(
smtp.mail('JÅ', options=['BODY=8BITMIME', 'SMTPUTF8']),
(250, b'OK'))
self.assertEqual(smtp.rcpt('János'), (250, b'OK'))
self.assertEqual(smtp.data(m), (250, b'OK'))
self.assertEqual(self.serv.last_mailfrom, 'JÅ')
self.assertEqual(self.serv.last_rcpttos, ['János'])
self.assertEqual(self.serv.last_message, m)
self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
self.assertIn('SMTPUTF8', self.serv.last_mail_options)
self.assertEqual(self.serv.last_rcpt_options, [])
def test_send_message_uses_smtputf8_if_addrs_non_ascii(self):
msg = EmailMessage()
msg['From'] = "Páolo <fÅ[email protected]>"
msg['To'] = 'Dinsdale'
msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
# XXX I don't know why I need two \n's here, but this is an existing
# bug (if it is one) and not a problem with the new functionality.
msg.set_content("oh là là , know what I mean, know what I mean?\n\n")
# XXX smtpd converts received /r/n to /n, so we can't easily test that
# we are successfully sending /r/n :(.
expected = textwrap.dedent("""\
From: Páolo <fÅ[email protected]>
To: Dinsdale
Subject: Nudge nudge, wink, wink \u1F609
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit
MIME-Version: 1.0
oh là là , know what I mean, know what I mean?
""")
smtp = smtplib.SMTP(
HOST, self.port, local_hostname='localhost', timeout=3)
self.addCleanup(smtp.close)
self.assertEqual(smtp.send_message(msg), {})
self.assertEqual(self.serv.last_mailfrom, 'fÅ[email protected]')
self.assertEqual(self.serv.last_rcpttos, ['Dinsdale'])
self.assertEqual(self.serv.last_message.decode(), expected)
self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
self.assertIn('SMTPUTF8', self.serv.last_mail_options)
self.assertEqual(self.serv.last_rcpt_options, [])
EXPECTED_RESPONSE = encode_base64(b'\0psu\0doesnotexist', eol='')
class SimSMTPAUTHInitialResponseChannel(SimSMTPChannel):
def smtp_AUTH(self, arg):
# RFC 4954's AUTH command allows for an optional initial-response.
# Not all AUTH methods support this; some require a challenge. AUTH
# PLAIN does those, so test that here. See issue #15014.
args = arg.split()
if args[0].lower() == 'plain':
if len(args) == 2:
# AUTH PLAIN <initial-response> with the response base 64
# encoded. Hard code the expected response for the test.
if args[1] == EXPECTED_RESPONSE:
self.push('235 Ok')
return
self.push('571 Bad authentication')
class SimSMTPAUTHInitialResponseServer(SimSMTPServer):
channel_class = SimSMTPAUTHInitialResponseChannel
@unittest.skipUnless(threading, 'Threading required for this test.')
class SMTPAUTHInitialResponseSimTests(unittest.TestCase):
def setUp(self):
self.real_getfqdn = socket.getfqdn
socket.getfqdn = mock_socket.getfqdn
self.serv_evt = threading.Event()
self.client_evt = threading.Event()
# Pick a random unused port by passing 0 for the port number
self.serv = SimSMTPAUTHInitialResponseServer(
(HOST, 0), ('nowhere', -1), decode_data=True)
# Keep a note of what port was assigned
self.port = self.serv.socket.getsockname()[1]
serv_args = (self.serv, self.serv_evt, self.client_evt)
self.thread = threading.Thread(target=debugging_server, args=serv_args)
self.thread.start()
# wait until server thread has assigned a port number
self.serv_evt.wait()
self.serv_evt.clear()
def tearDown(self):
socket.getfqdn = self.real_getfqdn
# indicate that the client is finished
self.client_evt.set()
# wait for the server thread to terminate
self.serv_evt.wait()
self.thread.join()
def testAUTH_PLAIN_initial_response_login(self):
self.serv.add_feature('AUTH PLAIN')
smtp = smtplib.SMTP(HOST, self.port,
local_hostname='localhost', timeout=15)
smtp.login('psu', 'doesnotexist')
smtp.close()
def testAUTH_PLAIN_initial_response_auth(self):
self.serv.add_feature('AUTH PLAIN')
smtp = smtplib.SMTP(HOST, self.port,
local_hostname='localhost', timeout=15)
smtp.user = 'psu'
smtp.password = 'doesnotexist'
code, response = smtp.auth('plain', smtp.auth_plain)
smtp.close()
self.assertEqual(code, 235)
if __name__ == '__main__':
unittest.main()
| 51,778 | 1,332 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_smtpnet.py | import unittest
from test import support
import smtplib
import socket
ssl = support.import_module("ssl")
support.requires("network")
def check_ssl_verifiy(host, port):
context = ssl.create_default_context()
with socket.create_connection((host, port)) as sock:
try:
sock = context.wrap_socket(sock, server_hostname=host)
except Exception:
return False
else:
sock.close()
return True
class SmtpTest(unittest.TestCase):
testServer = 'smtp.gmail.com'
remotePort = 587
def test_connect_starttls(self):
support.get_attribute(smtplib, 'SMTP_SSL')
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
with support.transient_internet(self.testServer):
server = smtplib.SMTP(self.testServer, self.remotePort)
try:
server.starttls(context=context)
except smtplib.SMTPException as e:
if e.args[0] == 'STARTTLS extension not supported by server.':
unittest.skip(e.args[0])
else:
raise
server.ehlo()
server.quit()
class SmtpSSLTest(unittest.TestCase):
testServer = 'smtp.gmail.com'
remotePort = 465
def test_connect(self):
support.get_attribute(smtplib, 'SMTP_SSL')
with support.transient_internet(self.testServer):
server = smtplib.SMTP_SSL(self.testServer, self.remotePort)
server.ehlo()
server.quit()
def test_connect_default_port(self):
support.get_attribute(smtplib, 'SMTP_SSL')
with support.transient_internet(self.testServer):
server = smtplib.SMTP_SSL(self.testServer)
server.ehlo()
server.quit()
def test_connect_using_sslcontext(self):
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
support.get_attribute(smtplib, 'SMTP_SSL')
with support.transient_internet(self.testServer):
server = smtplib.SMTP_SSL(self.testServer, self.remotePort, context=context)
server.ehlo()
server.quit()
def test_connect_using_sslcontext_verified(self):
with support.transient_internet(self.testServer):
can_verify = check_ssl_verifiy(self.testServer, self.remotePort)
if not can_verify:
self.skipTest("SSL certificate can't be verified")
support.get_attribute(smtplib, 'SMTP_SSL')
context = ssl.create_default_context()
with support.transient_internet(self.testServer):
server = smtplib.SMTP_SSL(self.testServer, self.remotePort, context=context)
server.ehlo()
server.quit()
if __name__ == "__main__":
unittest.main()
| 2,763 | 84 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_doctest2.py | """A module to test whether doctest recognizes some 2.2 features,
like static and class methods.
>>> print('yup') # 1
yup
We include some (random) encoded (utf-8) text in the text surrounding
the example. It should be ignored:
ÐÐÐÐÐ
"""
import sys
import cosmo
import unittest
from test import support
if sys.flags.optimize >= 2:
raise unittest.SkipTest("Cannot test docstrings with -O2")
class C(object):
"""Class C.
>>> print(C()) # 2
42
We include some (random) encoded (utf-8) text in the text surrounding
the example. It should be ignored:
ÐÐÐÐÐ
"""
def __init__(self):
"""C.__init__.
>>> print(C()) # 3
42
"""
def __str__(self):
"""
>>> print(C()) # 4
42
"""
return "42"
class D(object):
"""A nested D class.
>>> print("In D!") # 5
In D!
"""
def nested(self):
"""
>>> print(3) # 6
3
"""
def getx(self):
"""
>>> c = C() # 7
>>> c.x = 12 # 8
>>> print(c.x) # 9
-12
"""
return -self._x
def setx(self, value):
"""
>>> c = C() # 10
>>> c.x = 12 # 11
>>> print(c.x) # 12
-12
"""
self._x = value
x = property(getx, setx, doc="""\
>>> c = C() # 13
>>> c.x = 12 # 14
>>> print(c.x) # 15
-12
""")
@staticmethod
def statm():
"""
A static method.
>>> print(C.statm()) # 16
666
>>> print(C().statm()) # 17
666
"""
return 666
@classmethod
def clsm(cls, val):
"""
A class method.
>>> print(C.clsm(22)) # 18
22
>>> print(C().clsm(23)) # 19
23
"""
return val
def test_main():
if cosmo.MODE == 'tiny':
return
from test import test_doctest2
EXPECTED = 19
f, t = support.run_doctest(test_doctest2)
if t != EXPECTED:
raise support.TestFailed("expected %d tests to run, not %d" %
(EXPECTED, t))
# Pollute the namespace with a bunch of imported functions and classes,
# to make sure they don't get tested.
from doctest import *
if __name__ == '__main__':
test_main()
| 2,416 | 127 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_utf8source.py | # This file is marked as binary in the CVS, to prevent MacCVS from recoding it.
import unittest
class PEP3120Test(unittest.TestCase):
def test_pep3120(self):
self.assertEqual(
"ÐиÑон".encode("utf-8"),
b'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
)
self.assertEqual(
"\Ð".encode("utf-8"),
b'\\\xd0\x9f'
)
# def test_badsyntax(self):
# try:
# import test.badsyntax_pep3120
# except SyntaxError as msg:
# msg = str(msg).lower()
# self.assertTrue('utf-8' in msg)
# else:
# self.fail("expected exception didn't occur")
class BuiltinCompileTests(unittest.TestCase):
# Issue 3574.
def test_latin1(self):
# Allow compile() to read Latin-1 source.
source_code = '# coding: Latin-1\nu = "Ã"\n'.encode("Latin-1")
try:
code = compile(source_code, '<dummy>', 'exec')
except SyntaxError:
self.fail("compile() cannot handle Latin-1 source")
ns = {}
exec(code, ns)
self.assertEqual('Ã', ns['u'])
if __name__ == "__main__":
unittest.main()
| 1,191 | 44 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/mp_fork_bomb.py | import multiprocessing, sys
def foo():
print("123")
# Because "if __name__ == '__main__'" is missing this will not work
# correctly on Windows. However, we should get a RuntimeError rather
# than the Windows equivalent of a fork bomb.
if len(sys.argv) > 1:
multiprocessing.set_start_method(sys.argv[1])
else:
multiprocessing.set_start_method('spawn')
p = multiprocessing.Process(target=foo)
p.start()
p.join()
sys.exit(p.exitcode)
| 448 | 19 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_contains.py | from collections import deque
import unittest
class base_set:
def __init__(self, el):
self.el = el
class myset(base_set):
def __contains__(self, el):
return self.el == el
class seq(base_set):
def __getitem__(self, n):
return [self.el][n]
class TestContains(unittest.TestCase):
def test_common_tests(self):
a = base_set(1)
b = myset(1)
c = seq(1)
self.assertIn(1, b)
self.assertNotIn(0, b)
self.assertIn(1, c)
self.assertNotIn(0, c)
self.assertRaises(TypeError, lambda: 1 in a)
self.assertRaises(TypeError, lambda: 1 not in a)
# test char in string
self.assertIn('c', 'abc')
self.assertNotIn('d', 'abc')
self.assertIn('', '')
self.assertIn('', 'abc')
self.assertRaises(TypeError, lambda: None in 'abc')
def test_builtin_sequence_types(self):
# a collection of tests on builtin sequence types
a = range(10)
for i in a:
self.assertIn(i, a)
self.assertNotIn(16, a)
self.assertNotIn(a, a)
a = tuple(a)
for i in a:
self.assertIn(i, a)
self.assertNotIn(16, a)
self.assertNotIn(a, a)
class Deviant1:
"""Behaves strangely when compared
This class is designed to make sure that the contains code
works when the list is modified during the check.
"""
aList = list(range(15))
def __eq__(self, other):
if other == 12:
self.aList.remove(12)
self.aList.remove(13)
self.aList.remove(14)
return 0
self.assertNotIn(Deviant1(), Deviant1.aList)
def test_nonreflexive(self):
# containment and equality tests involving elements that are
# not necessarily equal to themselves
class MyNonReflexive(object):
def __eq__(self, other):
return False
def __hash__(self):
return 28
values = float('nan'), 1, None, 'abc', MyNonReflexive()
constructors = list, tuple, dict.fromkeys, set, frozenset, deque
for constructor in constructors:
container = constructor(values)
for elem in container:
self.assertIn(elem, container)
self.assertTrue(container == constructor(values))
self.assertTrue(container == container)
def test_block_fallback(self):
# blocking fallback with __contains__ = None
class ByContains(object):
def __contains__(self, other):
return False
c = ByContains()
class BlockContains(ByContains):
"""Is not a container
This class is a perfectly good iterable (as tested by
list(bc)), as well as inheriting from a perfectly good
container, but __contains__ = None prevents the usual
fallback to iteration in the container protocol. That
is, normally, 0 in bc would fall back to the equivalent
of any(x==0 for x in bc), but here it's blocked from
doing so.
"""
def __iter__(self):
while False:
yield None
__contains__ = None
bc = BlockContains()
self.assertFalse(0 in c)
self.assertFalse(0 in list(bc))
self.assertRaises(TypeError, lambda: 0 in bc)
if __name__ == '__main__':
unittest.main()
| 3,569 | 115 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/time_hashlib.py | # It's intended that this script be run by hand. It runs speed tests on
# hashlib functions; it does not test for correctness.
import sys
import time
import hashlib
def creatorFunc():
raise RuntimeError("eek, creatorFunc not overridden")
def test_scaled_msg(scale, name):
iterations = 106201//scale * 20
longStr = b'Z'*scale
localCF = creatorFunc
start = time.time()
for f in range(iterations):
x = localCF(longStr).digest()
end = time.time()
print(('%2.2f' % (end-start)), "seconds", iterations, "x", len(longStr), "bytes", name)
def test_create():
start = time.time()
for f in range(20000):
d = creatorFunc()
end = time.time()
print(('%2.2f' % (end-start)), "seconds", '[20000 creations]')
def test_zero():
start = time.time()
for f in range(20000):
x = creatorFunc().digest()
end = time.time()
print(('%2.2f' % (end-start)), "seconds", '[20000 "" digests]')
hName = sys.argv[1]
#
# setup our creatorFunc to test the requested hash
#
if hName in ('_md5', '_sha'):
exec('import '+hName)
exec('creatorFunc = '+hName+'.new')
print("testing speed of old", hName, "legacy interface")
elif hName == '_hashlib' and len(sys.argv) > 3:
import _hashlib
exec('creatorFunc = _hashlib.%s' % sys.argv[2])
print("testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2]))
elif hName == '_hashlib' and len(sys.argv) == 3:
import _hashlib
exec('creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2])
print("testing speed of _hashlib.new(%r)" % sys.argv[2])
elif hasattr(hashlib, hName) and hasattr(getattr(hashlib, hName), '__call__'):
creatorFunc = getattr(hashlib, hName)
print("testing speed of hashlib."+hName, getattr(hashlib, hName))
else:
exec("creatorFunc = lambda x=hashlib.new : x(%r)" % hName)
print("testing speed of hashlib.new(%r)" % hName)
try:
test_create()
except ValueError:
print()
print("pass argument(s) naming the hash to run a speed test on:")
print(" '_md5' and '_sha' test the legacy builtin md5 and sha")
print(" '_hashlib' 'openssl_hName' 'fast' tests the builtin _hashlib")
print(" '_hashlib' 'hName' tests builtin _hashlib.new(shaFOO)")
print(" 'hName' tests the hashlib.hName() implementation if it exists")
print(" otherwise it uses hashlib.new(hName).")
print()
raise
test_zero()
test_scaled_msg(scale=106201, name='[huge data]')
test_scaled_msg(scale=10620, name='[large data]')
test_scaled_msg(scale=1062, name='[medium data]')
test_scaled_msg(scale=424, name='[4*small data]')
test_scaled_msg(scale=336, name='[3*small data]')
test_scaled_msg(scale=212, name='[2*small data]')
test_scaled_msg(scale=106, name='[small data]')
test_scaled_msg(scale=creatorFunc().digest_size, name='[digest_size data]')
test_scaled_msg(scale=10, name='[tiny data]')
| 2,895 | 89 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/coding20731.py | #coding:latin1
| 18 | 5 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_opcodes.py | # Python test set -- part 2, opcodes
import unittest
from test import ann_module, support
class OpcodeTest(unittest.TestCase):
def test_try_inside_for_loop(self):
n = 0
for i in range(10):
n = n+i
try: 1/0
except NameError: pass
except ZeroDivisionError: pass
except TypeError: pass
try: pass
except: pass
try: pass
finally: pass
n = n+i
if n != 90:
self.fail('try inside for')
@unittest.skip("todo(jart): deal with __file__ needing .py somehow")
def test_setup_annotations_line(self):
# check that SETUP_ANNOTATIONS does not create spurious line numbers
try:
with open(ann_module.__file__) as f:
txt = f.read()
co = compile(txt, ann_module.__file__, 'exec')
self.assertEqual(co.co_firstlineno, 6)
except OSError:
pass
def test_no_annotations_if_not_needed(self):
class C: pass
with self.assertRaises(AttributeError):
C.__annotations__
def test_use_existing_annotations(self):
ns = {'__annotations__': {1: 2}}
exec('x: int', ns)
self.assertEqual(ns['__annotations__'], {'x': int, 1: 2})
def test_do_not_recreate_annotations(self):
# Don't rely on the existence of the '__annotations__' global.
with support.swap_item(globals(), '__annotations__', {}):
del globals()['__annotations__']
class C:
del __annotations__
with self.assertRaises(NameError):
x: int
def test_raise_class_exceptions(self):
class AClass(Exception): pass
class BClass(AClass): pass
class CClass(Exception): pass
class DClass(AClass):
def __init__(self, ignore):
pass
try: raise AClass()
except: pass
try: raise AClass()
except AClass: pass
try: raise BClass()
except AClass: pass
try: raise BClass()
except CClass: self.fail()
except: pass
a = AClass()
b = BClass()
try:
raise b
except AClass as v:
self.assertEqual(v, b)
else:
self.fail("no exception")
# not enough arguments
##try: raise BClass, a
##except TypeError: pass
##else: self.fail("no exception")
try: raise DClass(a)
except DClass as v:
self.assertIsInstance(v, DClass)
else:
self.fail("no exception")
def test_compare_function_objects(self):
f = eval('lambda: None')
g = eval('lambda: None')
self.assertNotEqual(f, g)
f = eval('lambda a: a')
g = eval('lambda a: a')
self.assertNotEqual(f, g)
f = eval('lambda a=1: a')
g = eval('lambda a=1: a')
self.assertNotEqual(f, g)
f = eval('lambda: 0')
g = eval('lambda: 1')
self.assertNotEqual(f, g)
f = eval('lambda: None')
g = eval('lambda a: None')
self.assertNotEqual(f, g)
f = eval('lambda a: None')
g = eval('lambda b: None')
self.assertNotEqual(f, g)
f = eval('lambda a: None')
g = eval('lambda a=None: None')
self.assertNotEqual(f, g)
f = eval('lambda a=0: None')
g = eval('lambda a=1: None')
self.assertNotEqual(f, g)
def test_modulo_of_string_subclasses(self):
class MyString(str):
def __mod__(self, value):
return 42
self.assertEqual(MyString() % 3, 42)
if __name__ == '__main__':
unittest.main()
| 3,765 | 140 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_rlcompleter.py | import unittest
from unittest.mock import patch
import builtins
import rlcompleter
class CompleteMe:
""" Trivial class used in testing rlcompleter.Completer. """
spam = 1
_ham = 2
class TestRlcompleter(unittest.TestCase):
def setUp(self):
self.stdcompleter = rlcompleter.Completer()
self.completer = rlcompleter.Completer(dict(spam=int,
egg=str,
CompleteMe=CompleteMe))
# forces stdcompleter to bind builtins namespace
self.stdcompleter.complete('', 0)
def test_namespace(self):
class A(dict):
pass
class B(list):
pass
self.assertTrue(self.stdcompleter.use_main_ns)
self.assertFalse(self.completer.use_main_ns)
self.assertFalse(rlcompleter.Completer(A()).use_main_ns)
self.assertRaises(TypeError, rlcompleter.Completer, B((1,)))
def test_global_matches(self):
# test with builtins namespace
self.assertEqual(sorted(self.stdcompleter.global_matches('di')),
[x+'(' for x in dir(builtins) if x.startswith('di')])
self.assertEqual(sorted(self.stdcompleter.global_matches('st')),
[x+'(' for x in dir(builtins) if x.startswith('st')])
self.assertEqual(self.stdcompleter.global_matches('akaksajadhak'), [])
# test with a customized namespace
self.assertEqual(self.completer.global_matches('CompleteM'),
['CompleteMe('])
self.assertEqual(self.completer.global_matches('eg'),
['egg('])
# XXX: see issue5256
self.assertEqual(self.completer.global_matches('CompleteM'),
['CompleteMe('])
def test_attr_matches(self):
# test with builtins namespace
self.assertEqual(self.stdcompleter.attr_matches('str.s'),
['str.{}('.format(x) for x in dir(str)
if x.startswith('s')])
self.assertEqual(self.stdcompleter.attr_matches('tuple.foospamegg'), [])
expected = sorted({'None.%s%s' % (x, '(' if x != '__doc__' else '')
for x in dir(None)})
self.assertEqual(self.stdcompleter.attr_matches('None.'), expected)
self.assertEqual(self.stdcompleter.attr_matches('None._'), expected)
self.assertEqual(self.stdcompleter.attr_matches('None.__'), expected)
# test with a customized namespace
self.assertEqual(self.completer.attr_matches('CompleteMe.sp'),
['CompleteMe.spam'])
self.assertEqual(self.completer.attr_matches('Completeme.egg'), [])
self.assertEqual(self.completer.attr_matches('CompleteMe.'),
['CompleteMe.mro(', 'CompleteMe.spam'])
self.assertEqual(self.completer.attr_matches('CompleteMe._'),
['CompleteMe._ham'])
matches = self.completer.attr_matches('CompleteMe.__')
for x in matches:
self.assertTrue(x.startswith('CompleteMe.__'), x)
self.assertIn('CompleteMe.__name__', matches)
self.assertIn('CompleteMe.__new__(', matches)
with patch.object(CompleteMe, "me", CompleteMe, create=True):
self.assertEqual(self.completer.attr_matches('CompleteMe.me.me.sp'),
['CompleteMe.me.me.spam'])
self.assertEqual(self.completer.attr_matches('egg.s'),
['egg.{}('.format(x) for x in dir(str)
if x.startswith('s')])
def test_excessive_getattr(self):
# Ensure getattr() is invoked no more than once per attribute
class Foo:
calls = 0
@property
def bar(self):
self.calls += 1
return None
f = Foo()
completer = rlcompleter.Completer(dict(f=f))
self.assertEqual(completer.complete('f.b', 0), 'f.bar')
self.assertEqual(f.calls, 1)
def test_uncreated_attr(self):
# Attributes like properties and slots should be completed even when
# they haven't been created on an instance
class Foo:
__slots__ = ("bar",)
completer = rlcompleter.Completer(dict(f=Foo()))
self.assertEqual(completer.complete('f.', 0), 'f.bar')
@unittest.mock.patch('rlcompleter._readline_available', False)
def test_complete(self):
completer = rlcompleter.Completer()
self.assertEqual(completer.complete('', 0), '\t')
self.assertEqual(completer.complete('a', 0), 'and ')
self.assertEqual(completer.complete('a', 1), 'as ')
self.assertEqual(completer.complete('as', 2), 'assert ')
self.assertEqual(completer.complete('an', 0), 'and ')
self.assertEqual(completer.complete('pa', 0), 'pass')
self.assertEqual(completer.complete('Fa', 0), 'False')
self.assertEqual(completer.complete('el', 0), 'elif ')
self.assertEqual(completer.complete('el', 1), 'else')
self.assertEqual(completer.complete('tr', 0), 'try:')
def test_duplicate_globals(self):
namespace = {
'False': None, # Keyword vs builtin vs namespace
'assert': None, # Keyword vs namespace
'try': lambda: None, # Keyword vs callable
'memoryview': None, # Callable builtin vs non-callable
'Ellipsis': lambda: None, # Non-callable builtin vs callable
}
completer = rlcompleter.Completer(namespace)
self.assertEqual(completer.complete('False', 0), 'False')
self.assertIsNone(completer.complete('False', 1)) # No duplicates
# Space or colon added due to being a reserved keyword
self.assertEqual(completer.complete('assert', 0), 'assert ')
self.assertIsNone(completer.complete('assert', 1))
self.assertEqual(completer.complete('try', 0), 'try:')
self.assertIsNone(completer.complete('try', 1))
# No opening bracket "(" because we overrode the built-in class
self.assertEqual(completer.complete('memoryview', 0), 'memoryview')
self.assertIsNone(completer.complete('memoryview', 1))
self.assertEqual(completer.complete('Ellipsis', 0), 'Ellipsis(')
self.assertIsNone(completer.complete('Ellipsis', 1))
if __name__ == '__main__':
unittest.main()
| 6,449 | 142 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_crypt.py | import sys
from test import support
import unittest
crypt = support.import_module('crypt')
if sys.platform.startswith('openbsd'):
raise unittest.SkipTest('The only supported method on OpenBSD is Blowfish')
class CryptTestCase(unittest.TestCase):
def test_crypt(self):
cr = crypt.crypt('mypassword')
cr2 = crypt.crypt('mypassword', cr)
self.assertEqual(cr2, cr)
cr = crypt.crypt('mypassword', 'ab')
if cr is not None:
cr2 = crypt.crypt('mypassword', cr)
self.assertEqual(cr2, cr)
def test_salt(self):
self.assertEqual(len(crypt._saltchars), 64)
for method in crypt.methods:
salt = crypt.mksalt(method)
self.assertIn(len(salt) - method.salt_chars, {0, 1, 3, 4, 6, 7})
if method.ident:
self.assertIn(method.ident, salt[:len(salt)-method.salt_chars])
def test_saltedcrypt(self):
for method in crypt.methods:
cr = crypt.crypt('assword', method)
self.assertEqual(len(cr), method.total_size)
cr2 = crypt.crypt('assword', cr)
self.assertEqual(cr2, cr)
cr = crypt.crypt('assword', crypt.mksalt(method))
self.assertEqual(len(cr), method.total_size)
def test_methods(self):
# Guarantee that METHOD_CRYPT is the last method in crypt.methods.
self.assertTrue(len(crypt.methods) >= 1)
self.assertEqual(crypt.METHOD_CRYPT, crypt.methods[-1])
if __name__ == "__main__":
unittest.main()
| 1,539 | 46 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_errno.py | """Test the errno module
Roger E. Masse
"""
import errno
import unittest
std_c_errors = frozenset(['EDOM', 'ERANGE'])
class ErrnoAttributeTests(unittest.TestCase):
def test_for_improper_attributes(self):
# No unexpected attributes should be on the module.
for error_code in std_c_errors:
self.assertTrue(hasattr(errno, error_code),
"errno is missing %s" % error_code)
def test_using_errorcode(self):
# Every key value in errno.errorcode should be on the module.
for value in errno.errorcode.values():
self.assertTrue(hasattr(errno, value),
'no %s attr in errno' % value)
class ErrorcodeTests(unittest.TestCase):
def test_attributes_in_errorcode(self):
for attribute in errno.__dict__.keys():
if attribute.isupper():
self.assertIn(getattr(errno, attribute), errno.errorcode,
'no %s attr in errno.errorcode' % attribute)
if __name__ == '__main__':
unittest.main()
| 1,069 | 36 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_bufio.py | import unittest
from test import support
import io # C implementation.
import _pyio as pyio # Python implementation.
# Simple test to ensure that optimizations in the IO library deliver the
# expected results. For best testing, run this under a debug-build Python too
# (to exercise asserts in the C code).
lengths = list(range(1, 257)) + [512, 1000, 1024, 2048, 4096, 8192, 10000,
16384, 32768, 65536, 1000000]
class BufferSizeTest:
def try_one(self, s):
# Write s + "\n" + s to file, then open it and ensure that successive
# .readline()s deliver what we wrote.
# Ensure we can open TESTFN for writing.
support.unlink(support.TESTFN)
# Since C doesn't guarantee we can write/read arbitrary bytes in text
# files, use binary mode.
f = self.open(support.TESTFN, "wb")
try:
# write once with \n and once without
f.write(s)
f.write(b"\n")
f.write(s)
f.close()
f = open(support.TESTFN, "rb")
line = f.readline()
self.assertEqual(line, s + b"\n")
line = f.readline()
self.assertEqual(line, s)
line = f.readline()
self.assertFalse(line) # Must be at EOF
f.close()
finally:
support.unlink(support.TESTFN)
def drive_one(self, pattern):
for length in lengths:
# Repeat string 'pattern' as often as needed to reach total length
# 'length'. Then call try_one with that string, a string one larger
# than that, and a string one smaller than that. Try this with all
# small sizes and various powers of 2, so we exercise all likely
# stdio buffer sizes, and "off by one" errors on both sides.
q, r = divmod(length, len(pattern))
teststring = pattern * q + pattern[:r]
self.assertEqual(len(teststring), length)
self.try_one(teststring)
self.try_one(teststring + b"x")
self.try_one(teststring[:-1])
def test_primepat(self):
# A pattern with prime length, to avoid simple relationships with
# stdio buffer sizes.
self.drive_one(b"1234567890\00\01\02\03\04\05\06")
def test_nullpat(self):
self.drive_one(b'\0' * 1000)
class CBufferSizeTest(BufferSizeTest, unittest.TestCase):
open = io.open
class PyBufferSizeTest(BufferSizeTest, unittest.TestCase):
open = staticmethod(pyio.open)
if __name__ == "__main__":
unittest.main()
| 2,597 | 74 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_dictviews.py | import collections
import copy
import pickle
import sys
import cosmo
import unittest
class DictSetTest(unittest.TestCase):
def test_constructors_not_callable(self):
kt = type({}.keys())
self.assertRaises(TypeError, kt, {})
self.assertRaises(TypeError, kt)
it = type({}.items())
self.assertRaises(TypeError, it, {})
self.assertRaises(TypeError, it)
vt = type({}.values())
self.assertRaises(TypeError, vt, {})
self.assertRaises(TypeError, vt)
def test_dict_keys(self):
d = {1: 10, "a": "ABC"}
keys = d.keys()
self.assertEqual(len(keys), 2)
self.assertEqual(set(keys), {1, "a"})
self.assertEqual(keys, {1, "a"})
self.assertNotEqual(keys, {1, "a", "b"})
self.assertNotEqual(keys, {1, "b"})
self.assertNotEqual(keys, {1})
self.assertNotEqual(keys, 42)
self.assertIn(1, keys)
self.assertIn("a", keys)
self.assertNotIn(10, keys)
self.assertNotIn("Z", keys)
self.assertEqual(d.keys(), d.keys())
e = {1: 11, "a": "def"}
self.assertEqual(d.keys(), e.keys())
del e["a"]
self.assertNotEqual(d.keys(), e.keys())
def test_dict_items(self):
d = {1: 10, "a": "ABC"}
items = d.items()
self.assertEqual(len(items), 2)
self.assertEqual(set(items), {(1, 10), ("a", "ABC")})
self.assertEqual(items, {(1, 10), ("a", "ABC")})
self.assertNotEqual(items, {(1, 10), ("a", "ABC"), "junk"})
self.assertNotEqual(items, {(1, 10), ("a", "def")})
self.assertNotEqual(items, {(1, 10)})
self.assertNotEqual(items, 42)
self.assertIn((1, 10), items)
self.assertIn(("a", "ABC"), items)
self.assertNotIn((1, 11), items)
self.assertNotIn(1, items)
self.assertNotIn((), items)
self.assertNotIn((1,), items)
self.assertNotIn((1, 2, 3), items)
self.assertEqual(d.items(), d.items())
e = d.copy()
self.assertEqual(d.items(), e.items())
e["a"] = "def"
self.assertNotEqual(d.items(), e.items())
def test_dict_mixed_keys_items(self):
d = {(1, 1): 11, (2, 2): 22}
e = {1: 1, 2: 2}
self.assertEqual(d.keys(), e.items())
self.assertNotEqual(d.items(), e.keys())
def test_dict_values(self):
d = {1: 10, "a": "ABC"}
values = d.values()
self.assertEqual(set(values), {10, "ABC"})
self.assertEqual(len(values), 2)
def test_dict_repr(self):
d = {1: 10, "a": "ABC"}
self.assertIsInstance(repr(d), str)
r = repr(d.items())
self.assertIsInstance(r, str)
self.assertTrue(r == "dict_items([('a', 'ABC'), (1, 10)])" or
r == "dict_items([(1, 10), ('a', 'ABC')])")
r = repr(d.keys())
self.assertIsInstance(r, str)
self.assertTrue(r == "dict_keys(['a', 1])" or
r == "dict_keys([1, 'a'])")
r = repr(d.values())
self.assertIsInstance(r, str)
self.assertTrue(r == "dict_values(['ABC', 10])" or
r == "dict_values([10, 'ABC'])")
def test_keys_set_operations(self):
d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 2}
d3 = {'d': 4, 'e': 5}
self.assertEqual(d1.keys() & d1.keys(), {'a', 'b'})
self.assertEqual(d1.keys() & d2.keys(), {'b'})
self.assertEqual(d1.keys() & d3.keys(), set())
self.assertEqual(d1.keys() & set(d1.keys()), {'a', 'b'})
self.assertEqual(d1.keys() & set(d2.keys()), {'b'})
self.assertEqual(d1.keys() & set(d3.keys()), set())
self.assertEqual(d1.keys() & tuple(d1.keys()), {'a', 'b'})
self.assertEqual(d1.keys() | d1.keys(), {'a', 'b'})
self.assertEqual(d1.keys() | d2.keys(), {'a', 'b', 'c'})
self.assertEqual(d1.keys() | d3.keys(), {'a', 'b', 'd', 'e'})
self.assertEqual(d1.keys() | set(d1.keys()), {'a', 'b'})
self.assertEqual(d1.keys() | set(d2.keys()), {'a', 'b', 'c'})
self.assertEqual(d1.keys() | set(d3.keys()),
{'a', 'b', 'd', 'e'})
self.assertEqual(d1.keys() | (1, 2), {'a', 'b', 1, 2})
self.assertEqual(d1.keys() ^ d1.keys(), set())
self.assertEqual(d1.keys() ^ d2.keys(), {'a', 'c'})
self.assertEqual(d1.keys() ^ d3.keys(), {'a', 'b', 'd', 'e'})
self.assertEqual(d1.keys() ^ set(d1.keys()), set())
self.assertEqual(d1.keys() ^ set(d2.keys()), {'a', 'c'})
self.assertEqual(d1.keys() ^ set(d3.keys()),
{'a', 'b', 'd', 'e'})
self.assertEqual(d1.keys() ^ tuple(d2.keys()), {'a', 'c'})
self.assertEqual(d1.keys() - d1.keys(), set())
self.assertEqual(d1.keys() - d2.keys(), {'a'})
self.assertEqual(d1.keys() - d3.keys(), {'a', 'b'})
self.assertEqual(d1.keys() - set(d1.keys()), set())
self.assertEqual(d1.keys() - set(d2.keys()), {'a'})
self.assertEqual(d1.keys() - set(d3.keys()), {'a', 'b'})
self.assertEqual(d1.keys() - (0, 1), {'a', 'b'})
self.assertFalse(d1.keys().isdisjoint(d1.keys()))
self.assertFalse(d1.keys().isdisjoint(d2.keys()))
self.assertFalse(d1.keys().isdisjoint(list(d2.keys())))
self.assertFalse(d1.keys().isdisjoint(set(d2.keys())))
self.assertTrue(d1.keys().isdisjoint({'x', 'y', 'z'}))
self.assertTrue(d1.keys().isdisjoint(['x', 'y', 'z']))
self.assertTrue(d1.keys().isdisjoint(set(['x', 'y', 'z'])))
self.assertTrue(d1.keys().isdisjoint(set(['x', 'y'])))
self.assertTrue(d1.keys().isdisjoint(['x', 'y']))
self.assertTrue(d1.keys().isdisjoint({}))
self.assertTrue(d1.keys().isdisjoint(d3.keys()))
de = {}
self.assertTrue(de.keys().isdisjoint(set()))
self.assertTrue(de.keys().isdisjoint([]))
self.assertTrue(de.keys().isdisjoint(de.keys()))
self.assertTrue(de.keys().isdisjoint([1]))
def test_items_set_operations(self):
d1 = {'a': 1, 'b': 2}
d2 = {'a': 2, 'b': 2}
d3 = {'d': 4, 'e': 5}
self.assertEqual(
d1.items() & d1.items(), {('a', 1), ('b', 2)})
self.assertEqual(d1.items() & d2.items(), {('b', 2)})
self.assertEqual(d1.items() & d3.items(), set())
self.assertEqual(d1.items() & set(d1.items()),
{('a', 1), ('b', 2)})
self.assertEqual(d1.items() & set(d2.items()), {('b', 2)})
self.assertEqual(d1.items() & set(d3.items()), set())
self.assertEqual(d1.items() | d1.items(),
{('a', 1), ('b', 2)})
self.assertEqual(d1.items() | d2.items(),
{('a', 1), ('a', 2), ('b', 2)})
self.assertEqual(d1.items() | d3.items(),
{('a', 1), ('b', 2), ('d', 4), ('e', 5)})
self.assertEqual(d1.items() | set(d1.items()),
{('a', 1), ('b', 2)})
self.assertEqual(d1.items() | set(d2.items()),
{('a', 1), ('a', 2), ('b', 2)})
self.assertEqual(d1.items() | set(d3.items()),
{('a', 1), ('b', 2), ('d', 4), ('e', 5)})
self.assertEqual(d1.items() ^ d1.items(), set())
self.assertEqual(d1.items() ^ d2.items(),
{('a', 1), ('a', 2)})
self.assertEqual(d1.items() ^ d3.items(),
{('a', 1), ('b', 2), ('d', 4), ('e', 5)})
self.assertEqual(d1.items() - d1.items(), set())
self.assertEqual(d1.items() - d2.items(), {('a', 1)})
self.assertEqual(d1.items() - d3.items(), {('a', 1), ('b', 2)})
self.assertEqual(d1.items() - set(d1.items()), set())
self.assertEqual(d1.items() - set(d2.items()), {('a', 1)})
self.assertEqual(d1.items() - set(d3.items()), {('a', 1), ('b', 2)})
self.assertFalse(d1.items().isdisjoint(d1.items()))
self.assertFalse(d1.items().isdisjoint(d2.items()))
self.assertFalse(d1.items().isdisjoint(list(d2.items())))
self.assertFalse(d1.items().isdisjoint(set(d2.items())))
self.assertTrue(d1.items().isdisjoint({'x', 'y', 'z'}))
self.assertTrue(d1.items().isdisjoint(['x', 'y', 'z']))
self.assertTrue(d1.items().isdisjoint(set(['x', 'y', 'z'])))
self.assertTrue(d1.items().isdisjoint(set(['x', 'y'])))
self.assertTrue(d1.items().isdisjoint({}))
self.assertTrue(d1.items().isdisjoint(d3.items()))
de = {}
self.assertTrue(de.items().isdisjoint(set()))
self.assertTrue(de.items().isdisjoint([]))
self.assertTrue(de.items().isdisjoint(de.items()))
self.assertTrue(de.items().isdisjoint([1]))
def test_recursive_repr(self):
d = {}
d[42] = d.values()
r = repr(d)
# Cannot perform a stronger test, as the contents of the repr
# are implementation-dependent. All we can say is that we
# want a str result, not an exception of any sort.
self.assertIsInstance(r, str)
d[42] = d.items()
r = repr(d)
# Again.
self.assertIsInstance(r, str)
@unittest.skipUnless(cosmo.MODE == "dbg", "disabled recursion checking")
def test_deeply_nested_repr(self):
d = {}
for i in range(sys.getrecursionlimit() + 100):
d = {42: d.values()}
try:
repr(d)
except (RecursionError, MemoryError):
pass
else:
assert False
def test_copy(self):
d = {1: 10, "a": "ABC"}
self.assertRaises(TypeError, copy.copy, d.keys())
self.assertRaises(TypeError, copy.copy, d.values())
self.assertRaises(TypeError, copy.copy, d.items())
def test_compare_error(self):
class Exc(Exception):
pass
class BadEq:
def __hash__(self):
return 7
def __eq__(self, other):
raise Exc
k1, k2 = BadEq(), BadEq()
v1, v2 = BadEq(), BadEq()
d = {k1: v1}
self.assertIn(k1, d)
self.assertIn(k1, d.keys())
self.assertIn(v1, d.values())
self.assertIn((k1, v1), d.items())
self.assertRaises(Exc, d.__contains__, k2)
self.assertRaises(Exc, d.keys().__contains__, k2)
self.assertRaises(Exc, d.items().__contains__, (k2, v1))
self.assertRaises(Exc, d.items().__contains__, (k1, v2))
with self.assertRaises(Exc):
v2 in d.values()
def test_pickle(self):
d = {1: 10, "a": "ABC"}
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
self.assertRaises((TypeError, pickle.PicklingError),
pickle.dumps, d.keys(), proto)
self.assertRaises((TypeError, pickle.PicklingError),
pickle.dumps, d.values(), proto)
self.assertRaises((TypeError, pickle.PicklingError),
pickle.dumps, d.items(), proto)
def test_abc_registry(self):
d = dict(a=1)
self.assertIsInstance(d.keys(), collections.KeysView)
self.assertIsInstance(d.keys(), collections.MappingView)
self.assertIsInstance(d.keys(), collections.Set)
self.assertIsInstance(d.keys(), collections.Sized)
self.assertIsInstance(d.keys(), collections.Iterable)
self.assertIsInstance(d.keys(), collections.Container)
self.assertIsInstance(d.values(), collections.ValuesView)
self.assertIsInstance(d.values(), collections.MappingView)
self.assertIsInstance(d.values(), collections.Sized)
self.assertIsInstance(d.items(), collections.ItemsView)
self.assertIsInstance(d.items(), collections.MappingView)
self.assertIsInstance(d.items(), collections.Set)
self.assertIsInstance(d.items(), collections.Sized)
self.assertIsInstance(d.items(), collections.Iterable)
self.assertIsInstance(d.items(), collections.Container)
if __name__ == "__main__":
unittest.main()
| 12,074 | 295 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/badsyntax_future5.py | """This is a test"""
from __future__ import nested_scopes
import foo
from __future__ import nested_scopes
def f(x):
def g(y):
return x + y
return g
result = f(2)(4)
| 184 | 13 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_bytes.py | """Unit tests for the bytes and bytearray types.
XXX This is a mess. Common tests should be unified with string_tests.py (and
the latter should be modernized).
"""
import array
import os
import re
import sys
import copy
import cosmo
import functools
import pickle
import tempfile
import unittest
import test.support
import test.string_tests
import test.list_tests
from test.support import bigaddrspacetest, MAX_Py_ssize_t
if sys.flags.bytes_warning:
def check_bytes_warnings(func):
@functools.wraps(func)
def wrapper(*args, **kw):
with test.support.check_warnings(('', BytesWarning)):
return func(*args, **kw)
return wrapper
else:
# no-op
def check_bytes_warnings(func):
return func
class Indexable:
def __init__(self, value=0):
self.value = value
def __index__(self):
return self.value
class BaseBytesTest:
def test_basics(self):
b = self.type2test()
self.assertEqual(type(b), self.type2test)
self.assertEqual(b.__class__, self.type2test)
def test_copy(self):
a = self.type2test(b"abcd")
for copy_method in (copy.copy, copy.deepcopy):
b = copy_method(a)
self.assertEqual(a, b)
self.assertEqual(type(a), type(b))
def test_empty_sequence(self):
b = self.type2test()
self.assertEqual(len(b), 0)
self.assertRaises(IndexError, lambda: b[0])
self.assertRaises(IndexError, lambda: b[1])
self.assertRaises(IndexError, lambda: b[sys.maxsize])
self.assertRaises(IndexError, lambda: b[sys.maxsize+1])
self.assertRaises(IndexError, lambda: b[10**100])
self.assertRaises(IndexError, lambda: b[-1])
self.assertRaises(IndexError, lambda: b[-2])
self.assertRaises(IndexError, lambda: b[-sys.maxsize])
self.assertRaises(IndexError, lambda: b[-sys.maxsize-1])
self.assertRaises(IndexError, lambda: b[-sys.maxsize-2])
self.assertRaises(IndexError, lambda: b[-10**100])
def test_from_iterable(self):
b = self.type2test(range(256))
self.assertEqual(len(b), 256)
self.assertEqual(list(b), list(range(256)))
# Non-sequence iterable.
b = self.type2test({42})
self.assertEqual(b, b"*")
b = self.type2test({43, 45})
self.assertIn(tuple(b), {(43, 45), (45, 43)})
# Iterator that has a __length_hint__.
b = self.type2test(iter(range(256)))
self.assertEqual(len(b), 256)
self.assertEqual(list(b), list(range(256)))
# Iterator that doesn't have a __length_hint__.
b = self.type2test(i for i in range(256) if i % 2)
self.assertEqual(len(b), 128)
self.assertEqual(list(b), list(range(256))[1::2])
# Sequence without __iter__.
class S:
def __getitem__(self, i):
return (1, 2, 3)[i]
b = self.type2test(S())
self.assertEqual(b, b"\x01\x02\x03")
def test_from_tuple(self):
# There is a special case for tuples.
b = self.type2test(tuple(range(256)))
self.assertEqual(len(b), 256)
self.assertEqual(list(b), list(range(256)))
b = self.type2test((1, 2, 3))
self.assertEqual(b, b"\x01\x02\x03")
def test_from_list(self):
# There is a special case for lists.
b = self.type2test(list(range(256)))
self.assertEqual(len(b), 256)
self.assertEqual(list(b), list(range(256)))
b = self.type2test([1, 2, 3])
self.assertEqual(b, b"\x01\x02\x03")
def test_from_mutating_list(self):
# Issue #34973: Crash in bytes constructor with mutating list.
class X:
def __index__(self):
a.clear()
return 42
a = [X(), X()]
self.assertEqual(bytes(a), b'*')
class Y:
def __index__(self):
if len(a) < 1000:
a.append(self)
return 42
a = [Y()]
self.assertEqual(bytes(a), b'*' * 1000) # should not crash
def test_from_index(self):
b = self.type2test([Indexable(), Indexable(1), Indexable(254),
Indexable(255)])
self.assertEqual(list(b), [0, 1, 254, 255])
self.assertRaises(ValueError, self.type2test, [Indexable(-1)])
self.assertRaises(ValueError, self.type2test, [Indexable(256)])
def test_from_buffer(self):
a = self.type2test(array.array('B', [1, 2, 3]))
self.assertEqual(a, b"\x01\x02\x03")
a = self.type2test(b"\x01\x02\x03")
self.assertEqual(a, b"\x01\x02\x03")
# Issues #29159 and #34974.
# Fallback when __index__ raises a TypeError
class B(bytes):
def __index__(self):
raise TypeError
self.assertEqual(self.type2test(B(b"foobar")), b"foobar")
def test_from_ssize(self):
self.assertEqual(self.type2test(0), b'')
self.assertEqual(self.type2test(1), b'\x00')
self.assertEqual(self.type2test(5), b'\x00\x00\x00\x00\x00')
self.assertRaises(ValueError, self.type2test, -1)
self.assertEqual(self.type2test('0', 'ascii'), b'0')
self.assertEqual(self.type2test(b'0'), b'0')
self.assertRaises(OverflowError, self.type2test, sys.maxsize + 1)
def test_constructor_type_errors(self):
self.assertRaises(TypeError, self.type2test, 0.0)
class C:
pass
self.assertRaises(TypeError, self.type2test, ["0"])
self.assertRaises(TypeError, self.type2test, [0.0])
self.assertRaises(TypeError, self.type2test, [None])
self.assertRaises(TypeError, self.type2test, [C()])
self.assertRaises(TypeError, self.type2test, 0, 'ascii')
self.assertRaises(TypeError, self.type2test, b'', 'ascii')
self.assertRaises(TypeError, self.type2test, 0, errors='ignore')
self.assertRaises(TypeError, self.type2test, b'', errors='ignore')
self.assertRaises(TypeError, self.type2test, '')
self.assertRaises(TypeError, self.type2test, '', errors='ignore')
self.assertRaises(TypeError, self.type2test, '', b'ascii')
self.assertRaises(TypeError, self.type2test, '', 'ascii', b'ignore')
def test_constructor_value_errors(self):
self.assertRaises(ValueError, self.type2test, [-1])
self.assertRaises(ValueError, self.type2test, [-sys.maxsize])
self.assertRaises(ValueError, self.type2test, [-sys.maxsize-1])
self.assertRaises(ValueError, self.type2test, [-sys.maxsize-2])
self.assertRaises(ValueError, self.type2test, [-10**100])
self.assertRaises(ValueError, self.type2test, [256])
self.assertRaises(ValueError, self.type2test, [257])
self.assertRaises(ValueError, self.type2test, [sys.maxsize])
self.assertRaises(ValueError, self.type2test, [sys.maxsize+1])
self.assertRaises(ValueError, self.type2test, [10**100])
@bigaddrspacetest
def test_constructor_overflow(self):
size = MAX_Py_ssize_t
self.assertRaises((OverflowError, MemoryError), self.type2test, size)
try:
# Should either pass or raise an error (e.g. on debug builds with
# additional malloc() overhead), but shouldn't crash.
bytearray(size - 4)
except (OverflowError, MemoryError):
pass
def test_constructor_exceptions(self):
# Issue #34974: bytes and bytearray constructors replace unexpected
# exceptions.
class BadInt:
def __index__(self):
1/0
self.assertRaises(ZeroDivisionError, self.type2test, BadInt())
self.assertRaises(ZeroDivisionError, self.type2test, [BadInt()])
class BadIterable:
def __iter__(self):
1/0
self.assertRaises(ZeroDivisionError, self.type2test, BadIterable())
def test_compare(self):
b1 = self.type2test([1, 2, 3])
b2 = self.type2test([1, 2, 3])
b3 = self.type2test([1, 3])
self.assertEqual(b1, b2)
self.assertTrue(b2 != b3)
self.assertTrue(b1 <= b2)
self.assertTrue(b1 <= b3)
self.assertTrue(b1 < b3)
self.assertTrue(b1 >= b2)
self.assertTrue(b3 >= b2)
self.assertTrue(b3 > b2)
self.assertFalse(b1 != b2)
self.assertFalse(b2 == b3)
self.assertFalse(b1 > b2)
self.assertFalse(b1 > b3)
self.assertFalse(b1 >= b3)
self.assertFalse(b1 < b2)
self.assertFalse(b3 < b2)
self.assertFalse(b3 <= b2)
@check_bytes_warnings
def test_compare_to_str(self):
# Byte comparisons with unicode should always fail!
# Test this for all expected byte orders and Unicode character
# sizes.
self.assertEqual(self.type2test(b"\0a\0b\0c") == "abc", False)
self.assertEqual(self.type2test(b"\0\0\0a\0\0\0b\0\0\0c") == "abc",
False)
self.assertEqual(self.type2test(b"a\0b\0c\0") == "abc", False)
self.assertEqual(self.type2test(b"a\0\0\0b\0\0\0c\0\0\0") == "abc",
False)
self.assertEqual(self.type2test() == str(), False)
self.assertEqual(self.type2test() != str(), True)
def test_reversed(self):
input = list(map(ord, "Hello"))
b = self.type2test(input)
output = list(reversed(b))
input.reverse()
self.assertEqual(output, input)
def test_getslice(self):
def by(s):
return self.type2test(map(ord, s))
b = by("Hello, world")
self.assertEqual(b[:5], by("Hello"))
self.assertEqual(b[1:5], by("ello"))
self.assertEqual(b[5:7], by(", "))
self.assertEqual(b[7:], by("world"))
self.assertEqual(b[7:12], by("world"))
self.assertEqual(b[7:100], by("world"))
self.assertEqual(b[:-7], by("Hello"))
self.assertEqual(b[-11:-7], by("ello"))
self.assertEqual(b[-7:-5], by(", "))
self.assertEqual(b[-5:], by("world"))
self.assertEqual(b[-5:12], by("world"))
self.assertEqual(b[-5:100], by("world"))
self.assertEqual(b[-100:5], by("Hello"))
def test_extended_getslice(self):
# Test extended slicing by comparing with list slicing.
L = list(range(255))
b = self.type2test(L)
indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100)
for start in indices:
for stop in indices:
# Skip step 0 (invalid)
for step in indices[1:]:
self.assertEqual(b[start:stop:step], self.type2test(L[start:stop:step]))
def test_encoding(self):
sample = "Hello world\n\u1234\u5678\u9abc"
for enc in ("utf-8", "utf-16"):
b = self.type2test(sample, enc)
self.assertEqual(b, self.type2test(sample.encode(enc)))
self.assertRaises(UnicodeEncodeError, self.type2test, sample, "latin-1")
b = self.type2test(sample, "latin-1", "ignore")
self.assertEqual(b, self.type2test(sample[:-3], "utf-8"))
def test_decode(self):
sample = "Hello world\n\u1234\u5678\u9abc"
for enc in ("utf-8", "utf-16"):
b = self.type2test(sample, enc)
self.assertEqual(b.decode(enc), sample)
sample = "Hello world\n\x80\x81\xfe\xff"
b = self.type2test(sample, "latin-1")
self.assertRaises(UnicodeDecodeError, b.decode, "utf-8")
self.assertEqual(b.decode("utf-8", "ignore"), "Hello world\n")
self.assertEqual(b.decode(errors="ignore", encoding="utf-8"),
"Hello world\n")
# Default encoding is utf-8
self.assertEqual(self.type2test(b'\xe2\x98\x83').decode(), '\u2603')
def test_from_int(self):
b = self.type2test(0)
self.assertEqual(b, self.type2test())
b = self.type2test(10)
self.assertEqual(b, self.type2test([0]*10))
b = self.type2test(10000)
self.assertEqual(b, self.type2test([0]*10000))
def test_concat(self):
b1 = self.type2test(b"abc")
b2 = self.type2test(b"def")
self.assertEqual(b1 + b2, b"abcdef")
self.assertEqual(b1 + bytes(b"def"), b"abcdef")
self.assertEqual(bytes(b"def") + b1, b"defabc")
self.assertRaises(TypeError, lambda: b1 + "def")
self.assertRaises(TypeError, lambda: "abc" + b2)
def test_repeat(self):
for b in b"abc", self.type2test(b"abc"):
self.assertEqual(b * 3, b"abcabcabc")
self.assertEqual(b * 0, b"")
self.assertEqual(b * -1, b"")
self.assertRaises(TypeError, lambda: b * 3.14)
self.assertRaises(TypeError, lambda: 3.14 * b)
# XXX Shouldn't bytes and bytearray agree on what to raise?
with self.assertRaises((OverflowError, MemoryError)):
c = b * sys.maxsize
with self.assertRaises((OverflowError, MemoryError)):
b *= sys.maxsize
def test_repeat_1char(self):
self.assertEqual(self.type2test(b'x')*100, self.type2test([ord('x')]*100))
def test_contains(self):
b = self.type2test(b"abc")
self.assertIn(ord('a'), b)
self.assertIn(int(ord('a')), b)
self.assertNotIn(200, b)
self.assertRaises(ValueError, lambda: 300 in b)
self.assertRaises(ValueError, lambda: -1 in b)
self.assertRaises(ValueError, lambda: sys.maxsize+1 in b)
self.assertRaises(TypeError, lambda: None in b)
self.assertRaises(TypeError, lambda: float(ord('a')) in b)
self.assertRaises(TypeError, lambda: "a" in b)
for f in bytes, bytearray:
self.assertIn(f(b""), b)
self.assertIn(f(b"a"), b)
self.assertIn(f(b"b"), b)
self.assertIn(f(b"c"), b)
self.assertIn(f(b"ab"), b)
self.assertIn(f(b"bc"), b)
self.assertIn(f(b"abc"), b)
self.assertNotIn(f(b"ac"), b)
self.assertNotIn(f(b"d"), b)
self.assertNotIn(f(b"dab"), b)
self.assertNotIn(f(b"abd"), b)
def test_fromhex(self):
self.assertRaises(TypeError, self.type2test.fromhex)
self.assertRaises(TypeError, self.type2test.fromhex, 1)
self.assertEqual(self.type2test.fromhex(''), self.type2test())
b = bytearray([0x1a, 0x2b, 0x30])
self.assertEqual(self.type2test.fromhex('1a2B30'), b)
self.assertEqual(self.type2test.fromhex(' 1A 2B 30 '), b)
self.assertEqual(self.type2test.fromhex('0000'), b'\0\0')
self.assertRaises(TypeError, self.type2test.fromhex, b'1B')
self.assertRaises(ValueError, self.type2test.fromhex, 'a')
self.assertRaises(ValueError, self.type2test.fromhex, 'rt')
self.assertRaises(ValueError, self.type2test.fromhex, '1a b cd')
self.assertRaises(ValueError, self.type2test.fromhex, '\x00')
self.assertRaises(ValueError, self.type2test.fromhex, '12 \x00 34')
for data, pos in (
# invalid first hexadecimal character
('12 x4 56', 3),
# invalid second hexadecimal character
('12 3x 56', 4),
# two invalid hexadecimal characters
('12 xy 56', 3),
# test non-ASCII string
('12 3\xff 56', 4),
):
with self.assertRaises(ValueError) as cm:
self.type2test.fromhex(data)
self.assertIn('at position %s' % pos, str(cm.exception))
def test_hex(self):
self.assertRaises(TypeError, self.type2test.hex)
self.assertRaises(TypeError, self.type2test.hex, 1)
self.assertEqual(self.type2test(b"").hex(), "")
self.assertEqual(bytearray([0x1a, 0x2b, 0x30]).hex(), '1a2b30')
self.assertEqual(self.type2test(b"\x1a\x2b\x30").hex(), '1a2b30')
self.assertEqual(memoryview(b"\x1a\x2b\x30").hex(), '1a2b30')
def test_join(self):
self.assertEqual(self.type2test(b"").join([]), b"")
self.assertEqual(self.type2test(b"").join([b""]), b"")
for lst in [[b"abc"], [b"a", b"bc"], [b"ab", b"c"], [b"a", b"b", b"c"]]:
lst = list(map(self.type2test, lst))
self.assertEqual(self.type2test(b"").join(lst), b"abc")
self.assertEqual(self.type2test(b"").join(tuple(lst)), b"abc")
self.assertEqual(self.type2test(b"").join(iter(lst)), b"abc")
dot_join = self.type2test(b".:").join
self.assertEqual(dot_join([b"ab", b"cd"]), b"ab.:cd")
self.assertEqual(dot_join([memoryview(b"ab"), b"cd"]), b"ab.:cd")
self.assertEqual(dot_join([b"ab", memoryview(b"cd")]), b"ab.:cd")
self.assertEqual(dot_join([bytearray(b"ab"), b"cd"]), b"ab.:cd")
self.assertEqual(dot_join([b"ab", bytearray(b"cd")]), b"ab.:cd")
# Stress it with many items
seq = [b"abc"] * 1000
expected = b"abc" + b".:abc" * 999
self.assertEqual(dot_join(seq), expected)
self.assertRaises(TypeError, self.type2test(b" ").join, None)
# Error handling and cleanup when some item in the middle of the
# sequence has the wrong type.
with self.assertRaises(TypeError):
dot_join([bytearray(b"ab"), "cd", b"ef"])
with self.assertRaises(TypeError):
dot_join([memoryview(b"ab"), "cd", b"ef"])
def test_count(self):
b = self.type2test(b'mississippi')
i = 105
p = 112
w = 119
self.assertEqual(b.count(b'i'), 4)
self.assertEqual(b.count(b'ss'), 2)
self.assertEqual(b.count(b'w'), 0)
self.assertEqual(b.count(i), 4)
self.assertEqual(b.count(w), 0)
self.assertEqual(b.count(b'i', 6), 2)
self.assertEqual(b.count(b'p', 6), 2)
self.assertEqual(b.count(b'i', 1, 3), 1)
self.assertEqual(b.count(b'p', 7, 9), 1)
self.assertEqual(b.count(i, 6), 2)
self.assertEqual(b.count(p, 6), 2)
self.assertEqual(b.count(i, 1, 3), 1)
self.assertEqual(b.count(p, 7, 9), 1)
def test_startswith(self):
b = self.type2test(b'hello')
self.assertFalse(self.type2test().startswith(b"anything"))
self.assertTrue(b.startswith(b"hello"))
self.assertTrue(b.startswith(b"hel"))
self.assertTrue(b.startswith(b"h"))
self.assertFalse(b.startswith(b"hellow"))
self.assertFalse(b.startswith(b"ha"))
with self.assertRaises(TypeError) as cm:
b.startswith([b'h'])
exc = str(cm.exception)
self.assertIn('bytes', exc)
self.assertIn('tuple', exc)
def test_endswith(self):
b = self.type2test(b'hello')
self.assertFalse(bytearray().endswith(b"anything"))
self.assertTrue(b.endswith(b"hello"))
self.assertTrue(b.endswith(b"llo"))
self.assertTrue(b.endswith(b"o"))
self.assertFalse(b.endswith(b"whello"))
self.assertFalse(b.endswith(b"no"))
with self.assertRaises(TypeError) as cm:
b.endswith([b'o'])
exc = str(cm.exception)
self.assertIn('bytes', exc)
self.assertIn('tuple', exc)
def test_find(self):
b = self.type2test(b'mississippi')
i = 105
w = 119
self.assertEqual(b.find(b'ss'), 2)
self.assertEqual(b.find(b'w'), -1)
self.assertEqual(b.find(b'mississippian'), -1)
self.assertEqual(b.find(i), 1)
self.assertEqual(b.find(w), -1)
self.assertEqual(b.find(b'ss', 3), 5)
self.assertEqual(b.find(b'ss', 1, 7), 2)
self.assertEqual(b.find(b'ss', 1, 3), -1)
self.assertEqual(b.find(i, 6), 7)
self.assertEqual(b.find(i, 1, 3), 1)
self.assertEqual(b.find(w, 1, 3), -1)
for index in (-1, 256, sys.maxsize + 1):
self.assertRaisesRegex(
ValueError, r'byte must be in range\(0, 256\)',
b.find, index)
def test_rfind(self):
b = self.type2test(b'mississippi')
i = 105
w = 119
self.assertEqual(b.rfind(b'ss'), 5)
self.assertEqual(b.rfind(b'w'), -1)
self.assertEqual(b.rfind(b'mississippian'), -1)
self.assertEqual(b.rfind(i), 10)
self.assertEqual(b.rfind(w), -1)
self.assertEqual(b.rfind(b'ss', 3), 5)
self.assertEqual(b.rfind(b'ss', 0, 6), 2)
self.assertEqual(b.rfind(i, 1, 3), 1)
self.assertEqual(b.rfind(i, 3, 9), 7)
self.assertEqual(b.rfind(w, 1, 3), -1)
def test_index(self):
b = self.type2test(b'mississippi')
i = 105
w = 119
self.assertEqual(b.index(b'ss'), 2)
self.assertRaises(ValueError, b.index, b'w')
self.assertRaises(ValueError, b.index, b'mississippian')
self.assertEqual(b.index(i), 1)
self.assertRaises(ValueError, b.index, w)
self.assertEqual(b.index(b'ss', 3), 5)
self.assertEqual(b.index(b'ss', 1, 7), 2)
self.assertRaises(ValueError, b.index, b'ss', 1, 3)
self.assertEqual(b.index(i, 6), 7)
self.assertEqual(b.index(i, 1, 3), 1)
self.assertRaises(ValueError, b.index, w, 1, 3)
def test_rindex(self):
b = self.type2test(b'mississippi')
i = 105
w = 119
self.assertEqual(b.rindex(b'ss'), 5)
self.assertRaises(ValueError, b.rindex, b'w')
self.assertRaises(ValueError, b.rindex, b'mississippian')
self.assertEqual(b.rindex(i), 10)
self.assertRaises(ValueError, b.rindex, w)
self.assertEqual(b.rindex(b'ss', 3), 5)
self.assertEqual(b.rindex(b'ss', 0, 6), 2)
self.assertEqual(b.rindex(i, 1, 3), 1)
self.assertEqual(b.rindex(i, 3, 9), 7)
self.assertRaises(ValueError, b.rindex, w, 1, 3)
def test_mod(self):
b = self.type2test(b'hello, %b!')
orig = b
b = b % b'world'
self.assertEqual(b, b'hello, world!')
self.assertEqual(orig, b'hello, %b!')
self.assertFalse(b is orig)
b = self.type2test(b'%s / 100 = %d%%')
a = b % (b'seventy-nine', 79)
self.assertEqual(a, b'seventy-nine / 100 = 79%')
self.assertIs(type(a), self.type2test)
# issue 29714
b = self.type2test(b'hello,\x00%b!')
b = b % b'world'
self.assertEqual(b, b'hello,\x00world!')
self.assertIs(type(b), self.type2test)
def test_imod(self):
b = self.type2test(b'hello, %b!')
orig = b
b %= b'world'
self.assertEqual(b, b'hello, world!')
self.assertEqual(orig, b'hello, %b!')
self.assertFalse(b is orig)
b = self.type2test(b'%s / 100 = %d%%')
b %= (b'seventy-nine', 79)
self.assertEqual(b, b'seventy-nine / 100 = 79%')
self.assertIs(type(b), self.type2test)
# issue 29714
b = self.type2test(b'hello,\x00%b!')
b %= b'world'
self.assertEqual(b, b'hello,\x00world!')
self.assertIs(type(b), self.type2test)
def test_rmod(self):
with self.assertRaises(TypeError):
object() % self.type2test(b'abc')
self.assertIs(self.type2test(b'abc').__rmod__('%r'), NotImplemented)
def test_replace(self):
b = self.type2test(b'mississippi')
self.assertEqual(b.replace(b'i', b'a'), b'massassappa')
self.assertEqual(b.replace(b'ss', b'x'), b'mixixippi')
def test_replace_int_error(self):
self.assertRaises(TypeError, self.type2test(b'a b').replace, 32, b'')
def test_split_string_error(self):
self.assertRaises(TypeError, self.type2test(b'a b').split, ' ')
self.assertRaises(TypeError, self.type2test(b'a b').rsplit, ' ')
def test_split_int_error(self):
self.assertRaises(TypeError, self.type2test(b'a b').split, 32)
self.assertRaises(TypeError, self.type2test(b'a b').rsplit, 32)
def test_split_unicodewhitespace(self):
for b in (b'a\x1Cb', b'a\x1Db', b'a\x1Eb', b'a\x1Fb'):
b = self.type2test(b)
self.assertEqual(b.split(), [b])
b = self.type2test(b"\x09\x0A\x0B\x0C\x0D\x1C\x1D\x1E\x1F")
self.assertEqual(b.split(), [b'\x1c\x1d\x1e\x1f'])
def test_rsplit_unicodewhitespace(self):
b = self.type2test(b"\x09\x0A\x0B\x0C\x0D\x1C\x1D\x1E\x1F")
self.assertEqual(b.rsplit(), [b'\x1c\x1d\x1e\x1f'])
def test_partition(self):
b = self.type2test(b'mississippi')
self.assertEqual(b.partition(b'ss'), (b'mi', b'ss', b'issippi'))
self.assertEqual(b.partition(b'w'), (b'mississippi', b'', b''))
def test_rpartition(self):
b = self.type2test(b'mississippi')
self.assertEqual(b.rpartition(b'ss'), (b'missi', b'ss', b'ippi'))
self.assertEqual(b.rpartition(b'i'), (b'mississipp', b'i', b''))
self.assertEqual(b.rpartition(b'w'), (b'', b'', b'mississippi'))
def test_partition_string_error(self):
self.assertRaises(TypeError, self.type2test(b'a b').partition, ' ')
self.assertRaises(TypeError, self.type2test(b'a b').rpartition, ' ')
def test_partition_int_error(self):
self.assertRaises(TypeError, self.type2test(b'a b').partition, 32)
self.assertRaises(TypeError, self.type2test(b'a b').rpartition, 32)
def test_pickling(self):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
for b in b"", b"a", b"abc", b"\xffab\x80", b"\0\0\377\0\0":
b = self.type2test(b)
ps = pickle.dumps(b, proto)
q = pickle.loads(ps)
self.assertEqual(b, q)
def test_iterator_pickling(self):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
for b in b"", b"a", b"abc", b"\xffab\x80", b"\0\0\377\0\0":
it = itorg = iter(self.type2test(b))
data = list(self.type2test(b))
d = pickle.dumps(it, proto)
it = pickle.loads(d)
self.assertEqual(type(itorg), type(it))
self.assertEqual(list(it), data)
it = pickle.loads(d)
if not b:
continue
next(it)
d = pickle.dumps(it, proto)
it = pickle.loads(d)
self.assertEqual(list(it), data[1:])
def test_strip_bytearray(self):
self.assertEqual(self.type2test(b'abc').strip(memoryview(b'ac')), b'b')
self.assertEqual(self.type2test(b'abc').lstrip(memoryview(b'ac')), b'bc')
self.assertEqual(self.type2test(b'abc').rstrip(memoryview(b'ac')), b'ab')
def test_strip_string_error(self):
self.assertRaises(TypeError, self.type2test(b'abc').strip, 'ac')
self.assertRaises(TypeError, self.type2test(b'abc').lstrip, 'ac')
self.assertRaises(TypeError, self.type2test(b'abc').rstrip, 'ac')
def test_strip_int_error(self):
self.assertRaises(TypeError, self.type2test(b' abc ').strip, 32)
self.assertRaises(TypeError, self.type2test(b' abc ').lstrip, 32)
self.assertRaises(TypeError, self.type2test(b' abc ').rstrip, 32)
def test_center(self):
# Fill character can be either bytes or bytearray (issue 12380)
b = self.type2test(b'abc')
for fill_type in (bytes, bytearray):
self.assertEqual(b.center(7, fill_type(b'-')),
self.type2test(b'--abc--'))
def test_ljust(self):
# Fill character can be either bytes or bytearray (issue 12380)
b = self.type2test(b'abc')
for fill_type in (bytes, bytearray):
self.assertEqual(b.ljust(7, fill_type(b'-')),
self.type2test(b'abc----'))
def test_rjust(self):
# Fill character can be either bytes or bytearray (issue 12380)
b = self.type2test(b'abc')
for fill_type in (bytes, bytearray):
self.assertEqual(b.rjust(7, fill_type(b'-')),
self.type2test(b'----abc'))
def test_xjust_int_error(self):
self.assertRaises(TypeError, self.type2test(b'abc').center, 7, 32)
self.assertRaises(TypeError, self.type2test(b'abc').ljust, 7, 32)
self.assertRaises(TypeError, self.type2test(b'abc').rjust, 7, 32)
def test_ord(self):
b = self.type2test(b'\0A\x7f\x80\xff')
self.assertEqual([ord(b[i:i+1]) for i in range(len(b))],
[0, 65, 127, 128, 255])
def test_maketrans(self):
transtable = b'\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377'
self.assertEqual(self.type2test.maketrans(b'abc', b'xyz'), transtable)
transtable = b'\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374xyz'
self.assertEqual(self.type2test.maketrans(b'\375\376\377', b'xyz'), transtable)
self.assertRaises(ValueError, self.type2test.maketrans, b'abc', b'xyzq')
self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 'def')
def test_none_arguments(self):
# issue 11828
b = self.type2test(b'hello')
l = self.type2test(b'l')
h = self.type2test(b'h')
x = self.type2test(b'x')
o = self.type2test(b'o')
self.assertEqual(2, b.find(l, None))
self.assertEqual(3, b.find(l, -2, None))
self.assertEqual(2, b.find(l, None, -2))
self.assertEqual(0, b.find(h, None, None))
self.assertEqual(3, b.rfind(l, None))
self.assertEqual(3, b.rfind(l, -2, None))
self.assertEqual(2, b.rfind(l, None, -2))
self.assertEqual(0, b.rfind(h, None, None))
self.assertEqual(2, b.index(l, None))
self.assertEqual(3, b.index(l, -2, None))
self.assertEqual(2, b.index(l, None, -2))
self.assertEqual(0, b.index(h, None, None))
self.assertEqual(3, b.rindex(l, None))
self.assertEqual(3, b.rindex(l, -2, None))
self.assertEqual(2, b.rindex(l, None, -2))
self.assertEqual(0, b.rindex(h, None, None))
self.assertEqual(2, b.count(l, None))
self.assertEqual(1, b.count(l, -2, None))
self.assertEqual(1, b.count(l, None, -2))
self.assertEqual(0, b.count(x, None, None))
self.assertEqual(True, b.endswith(o, None))
self.assertEqual(True, b.endswith(o, -2, None))
self.assertEqual(True, b.endswith(l, None, -2))
self.assertEqual(False, b.endswith(x, None, None))
self.assertEqual(True, b.startswith(h, None))
self.assertEqual(True, b.startswith(l, -2, None))
self.assertEqual(True, b.startswith(h, None, -2))
self.assertEqual(False, b.startswith(x, None, None))
def test_integer_arguments_out_of_byte_range(self):
b = self.type2test(b'hello')
for method in (b.count, b.find, b.index, b.rfind, b.rindex):
self.assertRaises(ValueError, method, -1)
self.assertRaises(ValueError, method, 256)
self.assertRaises(ValueError, method, 9999)
def test_find_etc_raise_correct_error_messages(self):
# issue 11828
b = self.type2test(b'hello')
x = self.type2test(b'x')
self.assertRaisesRegex(TypeError, r'\bfind\b', b.find,
x, None, None, None)
self.assertRaisesRegex(TypeError, r'\brfind\b', b.rfind,
x, None, None, None)
self.assertRaisesRegex(TypeError, r'\bindex\b', b.index,
x, None, None, None)
self.assertRaisesRegex(TypeError, r'\brindex\b', b.rindex,
x, None, None, None)
self.assertRaisesRegex(TypeError, r'\bcount\b', b.count,
x, None, None, None)
self.assertRaisesRegex(TypeError, r'\bstartswith\b', b.startswith,
x, None, None, None)
self.assertRaisesRegex(TypeError, r'\bendswith\b', b.endswith,
x, None, None, None)
def test_free_after_iterating(self):
test.support.check_free_after_iterating(self, iter, self.type2test)
test.support.check_free_after_iterating(self, reversed, self.type2test)
def test_translate(self):
b = self.type2test(b'hello')
rosetta = bytearray(range(256))
rosetta[ord('o')] = ord('e')
self.assertRaises(TypeError, b.translate)
self.assertRaises(TypeError, b.translate, None, None)
self.assertRaises(ValueError, b.translate, bytes(range(255)))
c = b.translate(rosetta, b'hello')
self.assertEqual(b, b'hello')
self.assertIsInstance(c, self.type2test)
c = b.translate(rosetta)
d = b.translate(rosetta, b'')
self.assertEqual(c, d)
self.assertEqual(c, b'helle')
c = b.translate(rosetta, b'l')
self.assertEqual(c, b'hee')
c = b.translate(None, b'e')
self.assertEqual(c, b'hllo')
# test delete as a keyword argument
c = b.translate(rosetta, delete=b'')
self.assertEqual(c, b'helle')
c = b.translate(rosetta, delete=b'l')
self.assertEqual(c, b'hee')
c = b.translate(None, delete=b'e')
self.assertEqual(c, b'hllo')
class BytesTest(BaseBytesTest, unittest.TestCase):
type2test = bytes
def test_getitem_error(self):
msg = "byte indices must be integers or slices"
with self.assertRaisesRegex(TypeError, msg):
b'python'['a']
@unittest.skipIf(cosmo.MODE in ('tiny', 'rel'),
"fails on missing .py file in rel omed")
def test_buffer_is_readonly(self):
fd = os.open(__file__, os.O_RDONLY)
with open(fd, "rb", buffering=0) as f:
self.assertRaises(TypeError, f.readinto, b"")
def test_custom(self):
class A:
def __bytes__(self):
return b'abc'
self.assertEqual(bytes(A()), b'abc')
class A: pass
self.assertRaises(TypeError, bytes, A())
class A:
def __bytes__(self):
return None
self.assertRaises(TypeError, bytes, A())
class A:
def __bytes__(self):
return b'a'
def __index__(self):
return 42
self.assertEqual(bytes(A()), b'a')
# Issue #25766
class A(str):
def __bytes__(self):
return b'abc'
self.assertEqual(bytes(A('\u20ac')), b'abc')
# self.assertEqual(bytes(A('\u20ac'), 'iso8859-15'), b'\xa4')
# Issue #24731
class A:
def __bytes__(self):
return OtherBytesSubclass(b'abc')
self.assertEqual(bytes(A()), b'abc')
self.assertIs(type(bytes(A())), OtherBytesSubclass)
self.assertEqual(BytesSubclass(A()), b'abc')
self.assertIs(type(BytesSubclass(A())), BytesSubclass)
# Test PyBytes_FromFormat()
def test_from_format(self):
return
ctypes = test.support.import_module('ctypes')
_testcapi = test.support.import_module('_testcapi')
from ctypes import pythonapi, py_object
from ctypes import (
c_int, c_uint,
c_long, c_ulong,
c_size_t, c_ssize_t,
c_char_p)
PyBytes_FromFormat = pythonapi.PyBytes_FromFormat
PyBytes_FromFormat.restype = py_object
# basic tests
self.assertEqual(PyBytes_FromFormat(b'format'),
b'format')
self.assertEqual(PyBytes_FromFormat(b'Hello %s !', b'world'),
b'Hello world !')
# test formatters
self.assertEqual(PyBytes_FromFormat(b'c=%c', c_int(0)),
b'c=\0')
self.assertEqual(PyBytes_FromFormat(b'c=%c', c_int(ord('@'))),
b'c=@')
self.assertEqual(PyBytes_FromFormat(b'c=%c', c_int(255)),
b'c=\xff')
self.assertEqual(PyBytes_FromFormat(b'd=%d ld=%ld zd=%zd',
c_int(1), c_long(2),
c_size_t(3)),
b'd=1 ld=2 zd=3')
self.assertEqual(PyBytes_FromFormat(b'd=%d ld=%ld zd=%zd',
c_int(-1), c_long(-2),
c_size_t(-3)),
b'd=-1 ld=-2 zd=-3')
self.assertEqual(PyBytes_FromFormat(b'u=%u lu=%lu zu=%zu',
c_uint(123), c_ulong(456),
c_size_t(789)),
b'u=123 lu=456 zu=789')
self.assertEqual(PyBytes_FromFormat(b'i=%i', c_int(123)),
b'i=123')
self.assertEqual(PyBytes_FromFormat(b'i=%i', c_int(-123)),
b'i=-123')
self.assertEqual(PyBytes_FromFormat(b'x=%x', c_int(0xabc)),
b'x=abc')
sizeof_ptr = ctypes.sizeof(c_char_p)
if os.name == 'nt':
# Windows (MSCRT)
ptr_format = '0x%0{}X'.format(2 * sizeof_ptr)
def ptr_formatter(ptr):
return (ptr_format % ptr)
else:
# UNIX (glibc)
def ptr_formatter(ptr):
return '%#x' % ptr
ptr = 0xabcdef
self.assertEqual(PyBytes_FromFormat(b'ptr=%p', c_char_p(ptr)),
('ptr=' + ptr_formatter(ptr)).encode('ascii'))
self.assertEqual(PyBytes_FromFormat(b's=%s', c_char_p(b'cstr')),
b's=cstr')
# test minimum and maximum integer values
size_max = c_size_t(-1).value
for formatstr, ctypes_type, value, py_formatter in (
(b'%d', c_int, _testcapi.INT_MIN, str),
(b'%d', c_int, _testcapi.INT_MAX, str),
(b'%ld', c_long, _testcapi.LONG_MIN, str),
(b'%ld', c_long, _testcapi.LONG_MAX, str),
(b'%lu', c_ulong, _testcapi.ULONG_MAX, str),
(b'%zd', c_ssize_t, _testcapi.PY_SSIZE_T_MIN, str),
(b'%zd', c_ssize_t, _testcapi.PY_SSIZE_T_MAX, str),
(b'%zu', c_size_t, size_max, str),
(b'%p', c_char_p, size_max, ptr_formatter),
):
self.assertEqual(PyBytes_FromFormat(formatstr, ctypes_type(value)),
py_formatter(value).encode('ascii')),
# width and precision (width is currently ignored)
self.assertEqual(PyBytes_FromFormat(b'%5s', b'a'),
b'a')
self.assertEqual(PyBytes_FromFormat(b'%.3s', b'abcdef'),
b'abc')
# '%%' formatter
self.assertEqual(PyBytes_FromFormat(b'%%'),
b'%')
self.assertEqual(PyBytes_FromFormat(b'[%%]'),
b'[%]')
self.assertEqual(PyBytes_FromFormat(b'%%%c', c_int(ord('_'))),
b'%_')
self.assertEqual(PyBytes_FromFormat(b'%%s'),
b'%s')
# Invalid formats and partial formatting
self.assertEqual(PyBytes_FromFormat(b'%'), b'%')
self.assertEqual(PyBytes_FromFormat(b'x=%i y=%', c_int(2), c_int(3)),
b'x=2 y=%')
# Issue #19969: %c must raise OverflowError for values
# not in the range [0; 255]
self.assertRaises(OverflowError,
PyBytes_FromFormat, b'%c', c_int(-1))
self.assertRaises(OverflowError,
PyBytes_FromFormat, b'%c', c_int(256))
def test_bytes_blocking(self):
class IterationBlocked(list):
__bytes__ = None
i = [0, 1, 2, 3]
self.assertEqual(bytes(i), b'\x00\x01\x02\x03')
self.assertRaises(TypeError, bytes, IterationBlocked(i))
# At least in CPython, because bytes.__new__ and the C API
# PyBytes_FromObject have different fallback rules, integer
# fallback is handled specially, so test separately.
class IntBlocked(int):
__bytes__ = None
self.assertEqual(bytes(3), b'\0\0\0')
self.assertRaises(TypeError, bytes, IntBlocked(3))
# While there is no separately-defined rule for handling bytes
# subclasses differently from other buffer-interface classes,
# an implementation may well special-case them (as CPython 2.x
# str did), so test them separately.
class BytesSubclassBlocked(bytes):
__bytes__ = None
self.assertEqual(bytes(b'ab'), b'ab')
self.assertRaises(TypeError, bytes, BytesSubclassBlocked(b'ab'))
class BufferBlocked(bytearray):
__bytes__ = None
ba, bb = bytearray(b'ab'), BufferBlocked(b'ab')
self.assertEqual(bytes(ba), b'ab')
self.assertRaises(TypeError, bytes, bb)
class ByteArrayTest(BaseBytesTest, unittest.TestCase):
type2test = bytearray
def test_getitem_error(self):
msg = "bytearray indices must be integers or slices"
with self.assertRaisesRegex(TypeError, msg):
bytearray(b'python')['a']
def test_setitem_error(self):
msg = "bytearray indices must be integers or slices"
with self.assertRaisesRegex(TypeError, msg):
b = bytearray(b'python')
b['a'] = "python"
def test_nohash(self):
self.assertRaises(TypeError, hash, bytearray())
def test_bytearray_api(self):
short_sample = b"Hello world\n"
sample = short_sample + b"\0"*(20 - len(short_sample))
tfn = tempfile.mktemp()
try:
# Prepare
with open(tfn, "wb") as f:
f.write(short_sample)
# Test readinto
with open(tfn, "rb") as f:
b = bytearray(20)
n = f.readinto(b)
self.assertEqual(n, len(short_sample))
self.assertEqual(list(b), list(sample))
# Test writing in binary mode
with open(tfn, "wb") as f:
f.write(b)
with open(tfn, "rb") as f:
self.assertEqual(f.read(), sample)
# Text mode is ambiguous; don't test
finally:
try:
os.remove(tfn)
except OSError:
pass
def test_reverse(self):
b = bytearray(b'hello')
self.assertEqual(b.reverse(), None)
self.assertEqual(b, b'olleh')
b = bytearray(b'hello1') # test even number of items
b.reverse()
self.assertEqual(b, b'1olleh')
b = bytearray()
b.reverse()
self.assertFalse(b)
def test_clear(self):
b = bytearray(b'python')
b.clear()
self.assertEqual(b, b'')
b = bytearray(b'')
b.clear()
self.assertEqual(b, b'')
b = bytearray(b'')
b.append(ord('r'))
b.clear()
b.append(ord('p'))
self.assertEqual(b, b'p')
def test_copy(self):
b = bytearray(b'abc')
bb = b.copy()
self.assertEqual(bb, b'abc')
b = bytearray(b'')
bb = b.copy()
self.assertEqual(bb, b'')
# test that it's indeed a copy and not a reference
b = bytearray(b'abc')
bb = b.copy()
self.assertEqual(b, bb)
self.assertIsNot(b, bb)
bb.append(ord('d'))
self.assertEqual(bb, b'abcd')
self.assertEqual(b, b'abc')
def test_regexps(self):
def by(s):
return bytearray(map(ord, s))
b = by("Hello, world")
self.assertEqual(re.findall(br"\w+", b), [by("Hello"), by("world")])
def test_setitem(self):
b = bytearray([1, 2, 3])
b[1] = 100
self.assertEqual(b, bytearray([1, 100, 3]))
b[-1] = 200
self.assertEqual(b, bytearray([1, 100, 200]))
b[0] = Indexable(10)
self.assertEqual(b, bytearray([10, 100, 200]))
try:
b[3] = 0
self.fail("Didn't raise IndexError")
except IndexError:
pass
try:
b[-10] = 0
self.fail("Didn't raise IndexError")
except IndexError:
pass
try:
b[0] = 256
self.fail("Didn't raise ValueError")
except ValueError:
pass
try:
b[0] = Indexable(-1)
self.fail("Didn't raise ValueError")
except ValueError:
pass
try:
b[0] = None
self.fail("Didn't raise TypeError")
except TypeError:
pass
def test_delitem(self):
b = bytearray(range(10))
del b[0]
self.assertEqual(b, bytearray(range(1, 10)))
del b[-1]
self.assertEqual(b, bytearray(range(1, 9)))
del b[4]
self.assertEqual(b, bytearray([1, 2, 3, 4, 6, 7, 8]))
def test_setslice(self):
b = bytearray(range(10))
self.assertEqual(list(b), list(range(10)))
b[0:5] = bytearray([1, 1, 1, 1, 1])
self.assertEqual(b, bytearray([1, 1, 1, 1, 1, 5, 6, 7, 8, 9]))
del b[0:-5]
self.assertEqual(b, bytearray([5, 6, 7, 8, 9]))
b[0:0] = bytearray([0, 1, 2, 3, 4])
self.assertEqual(b, bytearray(range(10)))
b[-7:-3] = bytearray([100, 101])
self.assertEqual(b, bytearray([0, 1, 2, 100, 101, 7, 8, 9]))
b[3:5] = [3, 4, 5, 6]
self.assertEqual(b, bytearray(range(10)))
b[3:0] = [42, 42, 42]
self.assertEqual(b, bytearray([0, 1, 2, 42, 42, 42, 3, 4, 5, 6, 7, 8, 9]))
b[3:] = b'foo'
self.assertEqual(b, bytearray([0, 1, 2, 102, 111, 111]))
b[:3] = memoryview(b'foo')
self.assertEqual(b, bytearray([102, 111, 111, 102, 111, 111]))
b[3:4] = []
self.assertEqual(b, bytearray([102, 111, 111, 111, 111]))
for elem in [5, -5, 0, int(10e20), 'str', 2.3,
['a', 'b'], [b'a', b'b'], [[]]]:
with self.assertRaises(TypeError):
b[3:4] = elem
for elem in [[254, 255, 256], [-256, 9000]]:
with self.assertRaises(ValueError):
b[3:4] = elem
def test_setslice_extend(self):
# Exercise the resizing logic (see issue #19087)
b = bytearray(range(100))
self.assertEqual(list(b), list(range(100)))
del b[:10]
self.assertEqual(list(b), list(range(10, 100)))
b.extend(range(100, 110))
self.assertEqual(list(b), list(range(10, 110)))
def test_fifo_overrun(self):
# Test for issue #23985, a buffer overrun when implementing a FIFO
# Build Python in pydebug mode for best results.
b = bytearray(10)
b.pop() # Defeat expanding buffer off-by-one quirk
del b[:1] # Advance start pointer without reallocating
b += bytes(2) # Append exactly the number of deleted bytes
del b # Free memory buffer, allowing pydebug verification
def test_del_expand(self):
# Reducing the size should not expand the buffer (issue #23985)
b = bytearray(10)
size = sys.getsizeof(b)
del b[:1]
self.assertLessEqual(sys.getsizeof(b), size)
def test_extended_set_del_slice(self):
indices = (0, None, 1, 3, 19, 300, 1<<333, -1, -2, -31, -300)
for start in indices:
for stop in indices:
# Skip invalid step 0
for step in indices[1:]:
L = list(range(255))
b = bytearray(L)
# Make sure we have a slice of exactly the right length,
# but with different data.
data = L[start:stop:step]
data.reverse()
L[start:stop:step] = data
b[start:stop:step] = data
self.assertEqual(b, bytearray(L))
del L[start:stop:step]
del b[start:stop:step]
self.assertEqual(b, bytearray(L))
def test_setslice_trap(self):
# This test verifies that we correctly handle assigning self
# to a slice of self (the old Lambert Meertens trap).
b = bytearray(range(256))
b[8:] = b
self.assertEqual(b, bytearray(list(range(8)) + list(range(256))))
def test_iconcat(self):
b = bytearray(b"abc")
b1 = b
b += b"def"
self.assertEqual(b, b"abcdef")
self.assertEqual(b, b1)
self.assertTrue(b is b1)
b += b"xyz"
self.assertEqual(b, b"abcdefxyz")
try:
b += ""
except TypeError:
pass
else:
self.fail("bytes += unicode didn't raise TypeError")
def test_irepeat(self):
b = bytearray(b"abc")
b1 = b
b *= 3
self.assertEqual(b, b"abcabcabc")
self.assertEqual(b, b1)
self.assertTrue(b is b1)
def test_irepeat_1char(self):
b = bytearray(b"x")
b1 = b
b *= 100
self.assertEqual(b, b"x"*100)
self.assertEqual(b, b1)
self.assertTrue(b is b1)
def test_alloc(self):
b = bytearray()
alloc = b.__alloc__()
self.assertTrue(alloc >= 0)
seq = [alloc]
for i in range(100):
b += b"x"
alloc = b.__alloc__()
self.assertGreater(alloc, len(b)) # including trailing null byte
if alloc not in seq:
seq.append(alloc)
def test_init_alloc(self):
b = bytearray()
def g():
for i in range(1, 100):
yield i
a = list(b)
self.assertEqual(a, list(range(1, len(a)+1)))
self.assertEqual(len(b), len(a))
self.assertLessEqual(len(b), i)
alloc = b.__alloc__()
self.assertGreater(alloc, len(b)) # including trailing null byte
b.__init__(g())
self.assertEqual(list(b), list(range(1, 100)))
self.assertEqual(len(b), 99)
alloc = b.__alloc__()
self.assertGreater(alloc, len(b))
def test_extend(self):
orig = b'hello'
a = bytearray(orig)
a.extend(a)
self.assertEqual(a, orig + orig)
self.assertEqual(a[5:], orig)
a = bytearray(b'')
# Test iterators that don't have a __length_hint__
a.extend(map(int, orig * 25))
a.extend(int(x) for x in orig * 25)
self.assertEqual(a, orig * 50)
self.assertEqual(a[-5:], orig)
a = bytearray(b'')
a.extend(iter(map(int, orig * 50)))
self.assertEqual(a, orig * 50)
self.assertEqual(a[-5:], orig)
a = bytearray(b'')
a.extend(list(map(int, orig * 50)))
self.assertEqual(a, orig * 50)
self.assertEqual(a[-5:], orig)
a = bytearray(b'')
self.assertRaises(ValueError, a.extend, [0, 1, 2, 256])
self.assertRaises(ValueError, a.extend, [0, 1, 2, -1])
self.assertEqual(len(a), 0)
a = bytearray(b'')
a.extend([Indexable(ord('a'))])
self.assertEqual(a, b'a')
def test_remove(self):
b = bytearray(b'hello')
b.remove(ord('l'))
self.assertEqual(b, b'helo')
b.remove(ord('l'))
self.assertEqual(b, b'heo')
self.assertRaises(ValueError, lambda: b.remove(ord('l')))
self.assertRaises(ValueError, lambda: b.remove(400))
self.assertRaises(TypeError, lambda: b.remove('e'))
# remove first and last
b.remove(ord('o'))
b.remove(ord('h'))
self.assertEqual(b, b'e')
self.assertRaises(TypeError, lambda: b.remove(b'e'))
b.remove(Indexable(ord('e')))
self.assertEqual(b, b'')
# test values outside of the ascii range: (0, 127)
c = bytearray([126, 127, 128, 129])
c.remove(127)
self.assertEqual(c, bytes([126, 128, 129]))
c.remove(129)
self.assertEqual(c, bytes([126, 128]))
def test_pop(self):
b = bytearray(b'world')
self.assertEqual(b.pop(), ord('d'))
self.assertEqual(b.pop(0), ord('w'))
self.assertEqual(b.pop(-2), ord('r'))
self.assertRaises(IndexError, lambda: b.pop(10))
self.assertRaises(IndexError, lambda: bytearray().pop())
# test for issue #6846
self.assertEqual(bytearray(b'\xff').pop(), 0xff)
def test_nosort(self):
self.assertRaises(AttributeError, lambda: bytearray().sort())
def test_append(self):
b = bytearray(b'hell')
b.append(ord('o'))
self.assertEqual(b, b'hello')
self.assertEqual(b.append(100), None)
b = bytearray()
b.append(ord('A'))
self.assertEqual(len(b), 1)
self.assertRaises(TypeError, lambda: b.append(b'o'))
b = bytearray()
b.append(Indexable(ord('A')))
self.assertEqual(b, b'A')
def test_insert(self):
b = bytearray(b'msssspp')
b.insert(1, ord('i'))
b.insert(4, ord('i'))
b.insert(-2, ord('i'))
b.insert(1000, ord('i'))
self.assertEqual(b, b'mississippi')
self.assertRaises(TypeError, lambda: b.insert(0, b'1'))
b = bytearray()
b.insert(0, Indexable(ord('A')))
self.assertEqual(b, b'A')
def test_copied(self):
# Issue 4348. Make sure that operations that don't mutate the array
# copy the bytes.
b = bytearray(b'abc')
self.assertFalse(b is b.replace(b'abc', b'cde', 0))
t = bytearray([i for i in range(256)])
x = bytearray(b'')
self.assertFalse(x is x.translate(t))
def test_partition_bytearray_doesnt_share_nullstring(self):
a, b, c = bytearray(b"x").partition(b"y")
self.assertEqual(b, b"")
self.assertEqual(c, b"")
self.assertTrue(b is not c)
b += b"!"
self.assertEqual(c, b"")
a, b, c = bytearray(b"x").partition(b"y")
self.assertEqual(b, b"")
self.assertEqual(c, b"")
# Same for rpartition
b, c, a = bytearray(b"x").rpartition(b"y")
self.assertEqual(b, b"")
self.assertEqual(c, b"")
self.assertTrue(b is not c)
b += b"!"
self.assertEqual(c, b"")
c, b, a = bytearray(b"x").rpartition(b"y")
self.assertEqual(b, b"")
self.assertEqual(c, b"")
def test_resize_forbidden(self):
# #4509: can't resize a bytearray when there are buffer exports, even
# if it wouldn't reallocate the underlying buffer.
# Furthermore, no destructive changes to the buffer may be applied
# before raising the error.
b = bytearray(range(10))
v = memoryview(b)
def resize(n):
b[1:-1] = range(n + 1, 2*n - 1)
resize(10)
orig = b[:]
self.assertRaises(BufferError, resize, 11)
self.assertEqual(b, orig)
self.assertRaises(BufferError, resize, 9)
self.assertEqual(b, orig)
self.assertRaises(BufferError, resize, 0)
self.assertEqual(b, orig)
# Other operations implying resize
self.assertRaises(BufferError, b.pop, 0)
self.assertEqual(b, orig)
self.assertRaises(BufferError, b.remove, b[1])
self.assertEqual(b, orig)
def delitem():
del b[1]
self.assertRaises(BufferError, delitem)
self.assertEqual(b, orig)
# deleting a non-contiguous slice
def delslice():
b[1:-1:2] = b""
self.assertRaises(BufferError, delslice)
self.assertEqual(b, orig)
@test.support.cpython_only
def test_obsolete_write_lock(self):
from _testcapi import getbuffer_with_null_view
self.assertRaises(BufferError, getbuffer_with_null_view, bytearray())
def test_iterator_pickling2(self):
orig = bytearray(b'abc')
data = list(b'qwerty')
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
# initial iterator
itorig = iter(orig)
d = pickle.dumps((itorig, orig), proto)
it, b = pickle.loads(d)
b[:] = data
self.assertEqual(type(it), type(itorig))
self.assertEqual(list(it), data)
# running iterator
next(itorig)
d = pickle.dumps((itorig, orig), proto)
it, b = pickle.loads(d)
b[:] = 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, b = pickle.loads(d)
b[:] = 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, b = pickle.loads(d)
b[:] = data
self.assertEqual(list(it), [])
test_exhausted_iterator = test.list_tests.CommonTest.test_exhausted_iterator
def test_iterator_length_hint(self):
# Issue 27443: __length_hint__ can return negative integer
ba = bytearray(b'ab')
it = iter(ba)
next(it)
ba.clear()
# Shouldn't raise an error
self.assertEqual(list(it), [])
class AssortedBytesTest(unittest.TestCase):
#
# Test various combinations of bytes and bytearray
#
@check_bytes_warnings
def test_repr_str(self):
for f in str, repr:
self.assertEqual(f(bytearray()), "bytearray(b'')")
self.assertEqual(f(bytearray([0])), "bytearray(b'\\x00')")
self.assertEqual(f(bytearray([0, 1, 254, 255])),
"bytearray(b'\\x00\\x01\\xfe\\xff')")
self.assertEqual(f(b"abc"), "b'abc'")
self.assertEqual(f(b"'"), '''b"'"''') # '''
self.assertEqual(f(b"'\""), r"""b'\'"'""") # '
@check_bytes_warnings
def test_format(self):
for b in b'abc', bytearray(b'abc'):
self.assertEqual(format(b), str(b))
self.assertEqual(format(b, ''), str(b))
with self.assertRaisesRegex(TypeError,
r'\b%s\b' % re.escape(type(b).__name__)):
format(b, 's')
def test_compare_bytes_to_bytearray(self):
self.assertEqual(b"abc" == bytes(b"abc"), True)
self.assertEqual(b"ab" != bytes(b"abc"), True)
self.assertEqual(b"ab" <= bytes(b"abc"), True)
self.assertEqual(b"ab" < bytes(b"abc"), True)
self.assertEqual(b"abc" >= bytes(b"ab"), True)
self.assertEqual(b"abc" > bytes(b"ab"), True)
self.assertEqual(b"abc" != bytes(b"abc"), False)
self.assertEqual(b"ab" == bytes(b"abc"), False)
self.assertEqual(b"ab" > bytes(b"abc"), False)
self.assertEqual(b"ab" >= bytes(b"abc"), False)
self.assertEqual(b"abc" < bytes(b"ab"), False)
self.assertEqual(b"abc" <= bytes(b"ab"), False)
self.assertEqual(bytes(b"abc") == b"abc", True)
self.assertEqual(bytes(b"ab") != b"abc", True)
self.assertEqual(bytes(b"ab") <= b"abc", True)
self.assertEqual(bytes(b"ab") < b"abc", True)
self.assertEqual(bytes(b"abc") >= b"ab", True)
self.assertEqual(bytes(b"abc") > b"ab", True)
self.assertEqual(bytes(b"abc") != b"abc", False)
self.assertEqual(bytes(b"ab") == b"abc", False)
self.assertEqual(bytes(b"ab") > b"abc", False)
self.assertEqual(bytes(b"ab") >= b"abc", False)
self.assertEqual(bytes(b"abc") < b"ab", False)
self.assertEqual(bytes(b"abc") <= b"ab", False)
@test.support.requires_docstrings
def test_doc(self):
self.assertIsNotNone(bytearray.__doc__)
self.assertTrue(bytearray.__doc__.startswith("bytearray("), bytearray.__doc__)
self.assertIsNotNone(bytes.__doc__)
self.assertTrue(bytes.__doc__.startswith("bytes("), bytes.__doc__)
def test_from_bytearray(self):
sample = bytes(b"Hello world\n\x80\x81\xfe\xff")
buf = memoryview(sample)
b = bytearray(buf)
self.assertEqual(b, bytearray(sample))
@check_bytes_warnings
def test_to_str(self):
self.assertEqual(str(b''), "b''")
self.assertEqual(str(b'x'), "b'x'")
self.assertEqual(str(b'\x80'), "b'\\x80'")
self.assertEqual(str(bytearray(b'')), "bytearray(b'')")
self.assertEqual(str(bytearray(b'x')), "bytearray(b'x')")
self.assertEqual(str(bytearray(b'\x80')), "bytearray(b'\\x80')")
def test_literal(self):
tests = [
(b"Wonderful spam", "Wonderful spam"),
(br"Wonderful spam too", "Wonderful spam too"),
(b"\xaa\x00\000\200", "\xaa\x00\000\200"),
(br"\xaa\x00\000\200", r"\xaa\x00\000\200"),
]
for b, s in tests:
self.assertEqual(b, bytearray(s, 'latin-1'))
for c in range(128, 256):
self.assertRaises(SyntaxError, eval,
'b"%s"' % chr(c))
def test_split_bytearray(self):
self.assertEqual(b'a b'.split(memoryview(b' ')), [b'a', b'b'])
def test_rsplit_bytearray(self):
self.assertEqual(b'a b'.rsplit(memoryview(b' ')), [b'a', b'b'])
def test_return_self(self):
# bytearray.replace must always return a new bytearray
b = bytearray()
self.assertFalse(b.replace(b'', b'') is b)
@unittest.skipUnless(sys.flags.bytes_warning,
"BytesWarning is needed for this test: use -bb option")
def test_compare(self):
def bytes_warning():
return test.support.check_warnings(('', BytesWarning))
with bytes_warning():
b'' == ''
with bytes_warning():
'' == b''
with bytes_warning():
b'' != ''
with bytes_warning():
'' != b''
with bytes_warning():
bytearray(b'') == ''
with bytes_warning():
'' == bytearray(b'')
with bytes_warning():
bytearray(b'') != ''
with bytes_warning():
'' != bytearray(b'')
with bytes_warning():
b'\0' == 0
with bytes_warning():
0 == b'\0'
with bytes_warning():
b'\0' != 0
with bytes_warning():
0 != b'\0'
# Optimizations:
# __iter__? (optimization)
# __reversed__? (optimization)
# XXX More string methods? (Those that don't use character properties)
# There are tests in string_tests.py that are more
# comprehensive for things like partition, etc.
# Unfortunately they are all bundled with tests that
# are not appropriate for bytes
# I've started porting some of those into bytearray_tests.py, we should port
# the rest that make sense (the code can be cleaned up to use modern
# unittest methods at the same time).
class BytearrayPEP3137Test(unittest.TestCase):
def marshal(self, x):
return bytearray(x)
def test_returns_new_copy(self):
val = self.marshal(b'1234')
# On immutable types these MAY return a reference to themselves
# but on mutable types like bytearray they MUST return a new copy.
for methname in ('zfill', 'rjust', 'ljust', 'center'):
method = getattr(val, methname)
newval = method(3)
self.assertEqual(val, newval)
self.assertTrue(val is not newval,
methname+' returned self on a mutable object')
for expr in ('val.split()[0]', 'val.rsplit()[0]',
'val.partition(b".")[0]', 'val.rpartition(b".")[2]',
'val.splitlines()[0]', 'val.replace(b"", b"")'):
newval = eval(expr)
self.assertEqual(val, newval)
self.assertTrue(val is not newval,
expr+' returned val on a mutable object')
sep = self.marshal(b'')
newval = sep.join([val])
self.assertEqual(val, newval)
self.assertIsNot(val, newval)
class FixedStringTest(test.string_tests.BaseTest):
def fixtype(self, obj):
if isinstance(obj, str):
return self.type2test(obj.encode("utf-8"))
return super().fixtype(obj)
contains_bytes = True
class ByteArrayAsStringTest(FixedStringTest, unittest.TestCase):
type2test = bytearray
class BytesAsStringTest(FixedStringTest, unittest.TestCase):
type2test = bytes
class SubclassTest:
def test_basic(self):
self.assertTrue(issubclass(self.type2test, self.basetype))
self.assertIsInstance(self.type2test(), self.basetype)
a, b = b"abcd", b"efgh"
_a, _b = self.type2test(a), self.type2test(b)
# test comparison operators with subclass instances
self.assertTrue(_a == _a)
self.assertTrue(_a != _b)
self.assertTrue(_a < _b)
self.assertTrue(_a <= _b)
self.assertTrue(_b >= _a)
self.assertTrue(_b > _a)
self.assertTrue(_a is not a)
# test concat of subclass instances
self.assertEqual(a + b, _a + _b)
self.assertEqual(a + b, a + _b)
self.assertEqual(a + b, _a + b)
# test repeat
self.assertTrue(a*5 == _a*5)
def test_join(self):
# Make sure join returns a NEW object for single item sequences
# involving a subclass.
# Make sure that it is of the appropriate type.
s1 = self.type2test(b"abcd")
s2 = self.basetype().join([s1])
self.assertTrue(s1 is not s2)
self.assertTrue(type(s2) is self.basetype, type(s2))
# Test reverse, calling join on subclass
s3 = s1.join([b"abcd"])
self.assertTrue(type(s3) is self.basetype)
def test_pickle(self):
a = self.type2test(b"abcd")
a.x = 10
a.y = self.type2test(b"efgh")
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
b = pickle.loads(pickle.dumps(a, proto))
self.assertNotEqual(id(a), id(b))
self.assertEqual(a, b)
self.assertEqual(a.x, b.x)
self.assertEqual(a.y, b.y)
self.assertEqual(type(a), type(b))
self.assertEqual(type(a.y), type(b.y))
def test_copy(self):
a = self.type2test(b"abcd")
a.x = 10
a.y = self.type2test(b"efgh")
for copy_method in (copy.copy, copy.deepcopy):
b = copy_method(a)
self.assertNotEqual(id(a), id(b))
self.assertEqual(a, b)
self.assertEqual(a.x, b.x)
self.assertEqual(a.y, b.y)
self.assertEqual(type(a), type(b))
self.assertEqual(type(a.y), type(b.y))
def test_fromhex(self):
b = self.type2test.fromhex('1a2B30')
self.assertEqual(b, b'\x1a\x2b\x30')
self.assertIs(type(b), self.type2test)
class B1(self.basetype):
def __new__(cls, value):
me = self.basetype.__new__(cls, value)
me.foo = 'bar'
return me
b = B1.fromhex('1a2B30')
self.assertEqual(b, b'\x1a\x2b\x30')
self.assertIs(type(b), B1)
self.assertEqual(b.foo, 'bar')
class B2(self.basetype):
def __init__(me, *args, **kwargs):
if self.basetype is not bytes:
self.basetype.__init__(me, *args, **kwargs)
me.foo = 'bar'
b = B2.fromhex('1a2B30')
self.assertEqual(b, b'\x1a\x2b\x30')
self.assertIs(type(b), B2)
self.assertEqual(b.foo, 'bar')
class ByteArraySubclass(bytearray):
pass
class BytesSubclass(bytes):
pass
class OtherBytesSubclass(bytes):
pass
class ByteArraySubclassTest(SubclassTest, unittest.TestCase):
basetype = bytearray
type2test = ByteArraySubclass
def test_init_override(self):
class subclass(bytearray):
def __init__(me, newarg=1, *args, **kwargs):
bytearray.__init__(me, *args, **kwargs)
x = subclass(4, b"abcd")
x = subclass(4, source=b"abcd")
self.assertEqual(x, b"abcd")
x = subclass(newarg=4, source=b"abcd")
self.assertEqual(x, b"abcd")
class BytesSubclassTest(SubclassTest, unittest.TestCase):
basetype = bytes
type2test = BytesSubclass
if __name__ == "__main__":
unittest.main()
| 69,981 | 1,835 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/cmath_testcases.txt | -- Testcases for functions in cmath.
--
-- Each line takes the form:
--
-- <testid> <function> <input_value> -> <output_value> <flags>
--
-- where:
--
-- <testid> is a short name identifying the test,
--
-- <function> is the function to be tested (exp, cos, asinh, ...),
--
-- <input_value> is a pair of floats separated by whitespace
-- representing real and imaginary parts of a complex number, and
--
-- <output_value> is the expected (ideal) output value, again
-- represented as a pair of floats.
--
-- <flags> is a list of the floating-point flags required by C99
--
-- The possible flags are:
--
-- divide-by-zero : raised when a finite input gives a
-- mathematically infinite result.
--
-- overflow : raised when a finite input gives a finite result whose
-- real or imaginary part is too large to fit in the usual range
-- of an IEEE 754 double.
--
-- invalid : raised for invalid inputs.
--
-- ignore-real-sign : indicates that the sign of the real part of
-- the result is unspecified; if the real part of the result is
-- given as inf, then both -inf and inf should be accepted as
-- correct.
--
-- ignore-imag-sign : indicates that the sign of the imaginary part
-- of the result is unspecified.
--
-- Flags may appear in any order.
--
-- Lines beginning with '--' (like this one) start a comment, and are
-- ignored. Blank lines, or lines containing only whitespace, are also
-- ignored.
-- The majority of the values below were computed with the help of
-- version 2.3 of the MPFR library for multiple-precision
-- floating-point computations with correct rounding. All output
-- values in this file are (modulo yet-to-be-discovered bugs)
-- correctly rounded, provided that each input and output decimal
-- floating-point value below is interpreted as a representation of
-- the corresponding nearest IEEE 754 double-precision value. See the
-- MPFR homepage at http://www.mpfr.org for more information about the
-- MPFR project.
-- A minority of the test cases were generated with the help of
-- mpmath 0.19 at 100 bit accuracy (http://mpmath.org) to improve
-- coverage of real functions with real-valued arguments. These are
-- used in test.test_math.MathTests.test_testfile, as well as in
-- test_cmath.
--------------------------
-- acos: Inverse cosine --
--------------------------
-- zeros
acos0000 acos 0.0 0.0 -> 1.5707963267948966 -0.0
acos0001 acos 0.0 -0.0 -> 1.5707963267948966 0.0
acos0002 acos -0.0 0.0 -> 1.5707963267948966 -0.0
acos0003 acos -0.0 -0.0 -> 1.5707963267948966 0.0
-- branch points: +/-1
acos0010 acos 1.0 0.0 -> 0.0 -0.0
acos0011 acos 1.0 -0.0 -> 0.0 0.0
acos0012 acos -1.0 0.0 -> 3.1415926535897931 -0.0
acos0013 acos -1.0 -0.0 -> 3.1415926535897931 0.0
-- values along both sides of real axis
acos0020 acos -9.8813129168249309e-324 0.0 -> 1.5707963267948966 -0.0
acos0021 acos -9.8813129168249309e-324 -0.0 -> 1.5707963267948966 0.0
acos0022 acos -1e-305 0.0 -> 1.5707963267948966 -0.0
acos0023 acos -1e-305 -0.0 -> 1.5707963267948966 0.0
acos0024 acos -1e-150 0.0 -> 1.5707963267948966 -0.0
acos0025 acos -1e-150 -0.0 -> 1.5707963267948966 0.0
acos0026 acos -9.9999999999999998e-17 0.0 -> 1.5707963267948968 -0.0
acos0027 acos -9.9999999999999998e-17 -0.0 -> 1.5707963267948968 0.0
acos0028 acos -0.001 0.0 -> 1.5717963269615634 -0.0
acos0029 acos -0.001 -0.0 -> 1.5717963269615634 0.0
acos0030 acos -0.57899999999999996 0.0 -> 2.1882979816120667 -0.0
acos0031 acos -0.57899999999999996 -0.0 -> 2.1882979816120667 0.0
acos0032 acos -0.99999999999999989 0.0 -> 3.1415926386886319 -0.0
acos0033 acos -0.99999999999999989 -0.0 -> 3.1415926386886319 0.0
acos0034 acos -1.0000000000000002 0.0 -> 3.1415926535897931 -2.1073424255447014e-08
acos0035 acos -1.0000000000000002 -0.0 -> 3.1415926535897931 2.1073424255447014e-08
acos0036 acos -1.0009999999999999 0.0 -> 3.1415926535897931 -0.044717633608306849
acos0037 acos -1.0009999999999999 -0.0 -> 3.1415926535897931 0.044717633608306849
acos0038 acos -2.0 0.0 -> 3.1415926535897931 -1.3169578969248168
acos0039 acos -2.0 -0.0 -> 3.1415926535897931 1.3169578969248168
acos0040 acos -23.0 0.0 -> 3.1415926535897931 -3.8281684713331012
acos0041 acos -23.0 -0.0 -> 3.1415926535897931 3.8281684713331012
acos0042 acos -10000000000000000.0 0.0 -> 3.1415926535897931 -37.534508668464674
acos0043 acos -10000000000000000.0 -0.0 -> 3.1415926535897931 37.534508668464674
acos0044 acos -9.9999999999999998e+149 0.0 -> 3.1415926535897931 -346.08091112966679
acos0045 acos -9.9999999999999998e+149 -0.0 -> 3.1415926535897931 346.08091112966679
acos0046 acos -1.0000000000000001e+299 0.0 -> 3.1415926535897931 -689.16608998577965
acos0047 acos -1.0000000000000001e+299 -0.0 -> 3.1415926535897931 689.16608998577965
acos0048 acos 9.8813129168249309e-324 0.0 -> 1.5707963267948966 -0.0
acos0049 acos 9.8813129168249309e-324 -0.0 -> 1.5707963267948966 0.0
acos0050 acos 1e-305 0.0 -> 1.5707963267948966 -0.0
acos0051 acos 1e-305 -0.0 -> 1.5707963267948966 0.0
acos0052 acos 1e-150 0.0 -> 1.5707963267948966 -0.0
acos0053 acos 1e-150 -0.0 -> 1.5707963267948966 0.0
acos0054 acos 9.9999999999999998e-17 0.0 -> 1.5707963267948966 -0.0
acos0055 acos 9.9999999999999998e-17 -0.0 -> 1.5707963267948966 0.0
acos0056 acos 0.001 0.0 -> 1.56979632662823 -0.0
acos0057 acos 0.001 -0.0 -> 1.56979632662823 0.0
acos0058 acos 0.57899999999999996 0.0 -> 0.95329467197772655 -0.0
acos0059 acos 0.57899999999999996 -0.0 -> 0.95329467197772655 0.0
acos0060 acos 0.99999999999999989 0.0 -> 1.4901161193847656e-08 -0.0
acos0061 acos 0.99999999999999989 -0.0 -> 1.4901161193847656e-08 0.0
acos0062 acos 1.0000000000000002 0.0 -> 0.0 -2.1073424255447014e-08
acos0063 acos 1.0000000000000002 -0.0 -> 0.0 2.1073424255447014e-08
acos0064 acos 1.0009999999999999 0.0 -> 0.0 -0.044717633608306849
acos0065 acos 1.0009999999999999 -0.0 -> 0.0 0.044717633608306849
acos0066 acos 2.0 0.0 -> 0.0 -1.3169578969248168
acos0067 acos 2.0 -0.0 -> 0.0 1.3169578969248168
acos0068 acos 23.0 0.0 -> 0.0 -3.8281684713331012
acos0069 acos 23.0 -0.0 -> 0.0 3.8281684713331012
acos0070 acos 10000000000000000.0 0.0 -> 0.0 -37.534508668464674
acos0071 acos 10000000000000000.0 -0.0 -> 0.0 37.534508668464674
acos0072 acos 9.9999999999999998e+149 0.0 -> 0.0 -346.08091112966679
acos0073 acos 9.9999999999999998e+149 -0.0 -> 0.0 346.08091112966679
acos0074 acos 1.0000000000000001e+299 0.0 -> 0.0 -689.16608998577965
acos0075 acos 1.0000000000000001e+299 -0.0 -> 0.0 689.16608998577965
-- random inputs
acos0100 acos -3.3307113324596682 -10.732007530863266 -> 1.8706085694482339 3.113986806554613
acos0101 acos -2863.952991743291 -2681013315.2571239 -> 1.5707973950301699 22.402607843274758
acos0102 acos -0.33072639793220088 -0.85055464658253055 -> 1.8219426895922601 0.79250166729311966
acos0103 acos -2.5722325842097802 -12.703940809821574 -> 1.7699942413107408 3.2565170156527325
acos0104 acos -42.495233785459583 -0.54039320751337161 -> 3.1288732573153304 4.4424815519735601
acos0105 acos -1.1363818625856401 9641.1325498630376 -> 1.5709141948820049 -9.8669410553254284
acos0106 acos -2.4398426824157866e-11 0.33002051890266165 -> 1.570796326818066 -0.32430578041578667
acos0107 acos -1.3521340428186552 2.9369737912076772 -> 1.9849059192339338 -1.8822893674117942
acos0108 acos -1.827364706477915 1.0355459232147557 -> 2.5732246307960032 -1.4090688267854969
acos0109 acos -0.25978373706403546 10.09712669185833 -> 1.5963940386378306 -3.0081673050196063
acos0110 acos 0.33561778471072551 -4587350.6823999118 -> 1.5707962536333251 16.031960402579539
acos0111 acos 0.49133444610998445 -0.8071422362990015 -> 1.1908761712801788 0.78573345813187867
acos0112 acos 0.42196734507823974 -2.4812965431745115 -> 1.414091186100692 1.651707260988172
acos0113 acos 2.961426210100655 -219.03295695248664 -> 1.5572768319822778 6.0824659885827304
acos0114 acos 2.886209063652641 -20.38011207220606 -> 1.4302765252297889 3.718201853147642
acos0115 acos 0.4180568075276509 1.4833433990823484 -> 1.3393834558303042 -1.2079847758301576
acos0116 acos 52.376111405924718 0.013930429001941001 -> 0.00026601761804024188 -4.6515066691204714
acos0117 acos 41637948387.625969 1.563418292894041 -> 3.7547918507883548e-11 -25.145424989809381
acos0118 acos 0.061226659122249526 0.8447234394615154 -> 1.5240280306367315 -0.76791798971140812
acos0119 acos 2.4480466420442959e+26 0.18002339201384662 -> 7.353756620564798e-28 -61.455650015996376
-- values near infinity
acos0200 acos 1.6206860518683021e+308 1.0308426226285283e+308 -> 0.56650826093826223 -710.54206874241561
acos0201 acos 1.2067735875070062e+308 -1.3429173724390276e+308 -> 0.83874369390864889 710.48017794027498
acos0202 acos -7.4130145132549047e+307 1.1759130543927645e+308 -> 2.1332729346478536 -710.21871115698752
acos0203 acos -8.6329426442257249e+307 -1.2316282952184133e+308 -> 2.1821511032444838 710.29752145697148
acos0204 acos 0.0 1.4289713855849746e+308 -> 1.5707963267948966 -710.24631069738996
acos0205 acos -0.0 1.3153524545987432e+308 -> 1.5707963267948966 -710.1634604787539
acos0206 acos 0.0 -9.6229037669269321e+307 -> 1.5707963267948966 709.85091679573691
acos0207 acos -0.0 -4.9783616421107088e+307 -> 1.5707963267948966 709.19187157911233
acos0208 acos 1.3937541925739389e+308 0.0 -> 0.0 -710.22135678707264
acos0209 acos 9.1362388967371536e+307 -0.0 -> 0.0 709.79901953124613
acos0210 acos -1.3457361220697436e+308 0.0 -> 3.1415926535897931 -710.18629698871848
acos0211 acos -5.4699090056144284e+307 -0.0 -> 3.1415926535897931 709.28603271085649
acos0212 acos 1.5880716932358901e+308 5.5638401252339929 -> 3.503519487773873e-308 -710.35187633140583
acos0213 acos 1.2497211663463164e+308 -3.0456477717911024 -> 2.4370618453197486e-308 710.11227628223412
acos0214 acos -9.9016224006029528e+307 4.9570427340789056 -> 3.1415926535897931 -709.87946935229468
acos0215 acos -1.5854071066874139e+308 -4.4233577741497783 -> 3.1415926535897931 710.35019704672004
acos0216 acos 9.3674623083647628 1.5209559051877979e+308 -> 1.5707963267948966 -710.30869484491086
acos0217 acos 8.1773832021784383 -6.6093445795000056e+307 -> 1.5707963267948966 709.4752552227792
acos0218 acos -3.1845935000665104 1.5768856396650893e+308 -> 1.5707963267948966 -710.34480761042687
acos0219 acos -1.0577303880953903 -6.4574626815735613e+307 -> 1.5707963267948966 709.45200719662046
-- values near 0
acos0220 acos 1.8566986970714045e-320 3.1867234156760402e-321 -> 1.5707963267948966 -3.1867234156760402e-321
acos0221 acos 7.9050503334599447e-323 -8.8931816251424378e-323 -> 1.5707963267948966 8.8931816251424378e-323
acos0222 acos -4.4465908125712189e-323 2.4654065097222727e-311 -> 1.5707963267948966 -2.4654065097222727e-311
acos0223 acos -6.1016916408192619e-311 -2.4703282292062327e-323 -> 1.5707963267948966 2.4703282292062327e-323
acos0224 acos 0.0 3.4305783621842729e-311 -> 1.5707963267948966 -3.4305783621842729e-311
acos0225 acos -0.0 1.6117409498633145e-319 -> 1.5707963267948966 -1.6117409498633145e-319
acos0226 acos 0.0 -4.9900630229965901e-322 -> 1.5707963267948966 4.9900630229965901e-322
acos0227 acos -0.0 -4.4889279210592818e-311 -> 1.5707963267948966 4.4889279210592818e-311
acos0228 acos 5.3297678681477214e-312 0.0 -> 1.5707963267948966 -0.0
acos0229 acos 6.2073425897211614e-313 -0.0 -> 1.5707963267948966 0.0
acos0230 acos -4.9406564584124654e-324 0.0 -> 1.5707963267948966 -0.0
acos0231 acos -1.7107517052899003e-318 -0.0 -> 1.5707963267948966 0.0
-- special values
acos1000 acos 0.0 0.0 -> 1.5707963267948966 -0.0
acos1001 acos 0.0 -0.0 -> 1.5707963267948966 0.0
acos1002 acos -0.0 0.0 -> 1.5707963267948966 -0.0
acos1003 acos -0.0 -0.0 -> 1.5707963267948966 0.0
acos1004 acos 0.0 nan -> 1.5707963267948966 nan
acos1005 acos -0.0 nan -> 1.5707963267948966 nan
acos1006 acos -2.3 inf -> 1.5707963267948966 -inf
acos1007 acos -0.0 inf -> 1.5707963267948966 -inf
acos1008 acos 0.0 inf -> 1.5707963267948966 -inf
acos1009 acos 2.3 inf -> 1.5707963267948966 -inf
acos1010 acos -2.3 nan -> nan nan
acos1011 acos 2.3 nan -> nan nan
acos1012 acos -inf 2.3 -> 3.1415926535897931 -inf
acos1013 acos -inf 0.0 -> 3.1415926535897931 -inf
acos1014 acos inf 2.3 -> 0.0 -inf
acos1015 acos inf 0.0 -> 0.0 -inf
acos1016 acos -inf inf -> 2.3561944901923448 -inf
acos1017 acos inf inf -> 0.78539816339744828 -inf
acos1018 acos inf nan -> nan inf ignore-imag-sign
acos1019 acos -inf nan -> nan inf ignore-imag-sign
acos1020 acos nan 0.0 -> nan nan
acos1021 acos nan 2.3 -> nan nan
acos1022 acos nan inf -> nan -inf
acos1023 acos nan nan -> nan nan
acos1024 acos -2.3 -inf -> 1.5707963267948966 inf
acos1025 acos -0.0 -inf -> 1.5707963267948966 inf
acos1026 acos 0.0 -inf -> 1.5707963267948966 inf
acos1027 acos 2.3 -inf -> 1.5707963267948966 inf
acos1028 acos -inf -2.3 -> 3.1415926535897931 inf
acos1029 acos -inf -0.0 -> 3.1415926535897931 inf
acos1030 acos inf -2.3 -> 0.0 inf
acos1031 acos inf -0.0 -> 0.0 inf
acos1032 acos -inf -inf -> 2.3561944901923448 inf
acos1033 acos inf -inf -> 0.78539816339744828 inf
acos1034 acos nan -0.0 -> nan nan
acos1035 acos nan -2.3 -> nan nan
acos1036 acos nan -inf -> nan inf
--------------------------------------
-- acosh: Inverse hyperbolic cosine --
--------------------------------------
-- zeros
acosh0000 acosh 0.0 0.0 -> 0.0 1.5707963267948966
acosh0001 acosh 0.0 -0.0 -> 0.0 -1.5707963267948966
acosh0002 acosh -0.0 0.0 -> 0.0 1.5707963267948966
acosh0003 acosh -0.0 -0.0 -> 0.0 -1.5707963267948966
-- branch points: +/-1
acosh0010 acosh 1.0 0.0 -> 0.0 0.0
acosh0011 acosh 1.0 -0.0 -> 0.0 -0.0
acosh0012 acosh -1.0 0.0 -> 0.0 3.1415926535897931
acosh0013 acosh -1.0 -0.0 -> 0.0 -3.1415926535897931
-- values along both sides of real axis
acosh0020 acosh -9.8813129168249309e-324 0.0 -> 0.0 1.5707963267948966
acosh0021 acosh -9.8813129168249309e-324 -0.0 -> 0.0 -1.5707963267948966
acosh0022 acosh -1e-305 0.0 -> 0.0 1.5707963267948966
acosh0023 acosh -1e-305 -0.0 -> 0.0 -1.5707963267948966
acosh0024 acosh -1e-150 0.0 -> 0.0 1.5707963267948966
acosh0025 acosh -1e-150 -0.0 -> 0.0 -1.5707963267948966
acosh0026 acosh -9.9999999999999998e-17 0.0 -> 0.0 1.5707963267948968
acosh0027 acosh -9.9999999999999998e-17 -0.0 -> 0.0 -1.5707963267948968
acosh0028 acosh -0.001 0.0 -> 0.0 1.5717963269615634
acosh0029 acosh -0.001 -0.0 -> 0.0 -1.5717963269615634
acosh0030 acosh -0.57899999999999996 0.0 -> 0.0 2.1882979816120667
acosh0031 acosh -0.57899999999999996 -0.0 -> 0.0 -2.1882979816120667
acosh0032 acosh -0.99999999999999989 0.0 -> 0.0 3.1415926386886319
acosh0033 acosh -0.99999999999999989 -0.0 -> 0.0 -3.1415926386886319
acosh0034 acosh -1.0000000000000002 0.0 -> 2.1073424255447014e-08 3.1415926535897931
acosh0035 acosh -1.0000000000000002 -0.0 -> 2.1073424255447014e-08 -3.1415926535897931
acosh0036 acosh -1.0009999999999999 0.0 -> 0.044717633608306849 3.1415926535897931
acosh0037 acosh -1.0009999999999999 -0.0 -> 0.044717633608306849 -3.1415926535897931
acosh0038 acosh -2.0 0.0 -> 1.3169578969248168 3.1415926535897931
acosh0039 acosh -2.0 -0.0 -> 1.3169578969248168 -3.1415926535897931
acosh0040 acosh -23.0 0.0 -> 3.8281684713331012 3.1415926535897931
acosh0041 acosh -23.0 -0.0 -> 3.8281684713331012 -3.1415926535897931
acosh0042 acosh -10000000000000000.0 0.0 -> 37.534508668464674 3.1415926535897931
acosh0043 acosh -10000000000000000.0 -0.0 -> 37.534508668464674 -3.1415926535897931
acosh0044 acosh -9.9999999999999998e+149 0.0 -> 346.08091112966679 3.1415926535897931
acosh0045 acosh -9.9999999999999998e+149 -0.0 -> 346.08091112966679 -3.1415926535897931
acosh0046 acosh -1.0000000000000001e+299 0.0 -> 689.16608998577965 3.1415926535897931
acosh0047 acosh -1.0000000000000001e+299 -0.0 -> 689.16608998577965 -3.1415926535897931
acosh0048 acosh 9.8813129168249309e-324 0.0 -> 0.0 1.5707963267948966
acosh0049 acosh 9.8813129168249309e-324 -0.0 -> 0.0 -1.5707963267948966
acosh0050 acosh 1e-305 0.0 -> 0.0 1.5707963267948966
acosh0051 acosh 1e-305 -0.0 -> 0.0 -1.5707963267948966
acosh0052 acosh 1e-150 0.0 -> 0.0 1.5707963267948966
acosh0053 acosh 1e-150 -0.0 -> 0.0 -1.5707963267948966
acosh0054 acosh 9.9999999999999998e-17 0.0 -> 0.0 1.5707963267948966
acosh0055 acosh 9.9999999999999998e-17 -0.0 -> 0.0 -1.5707963267948966
acosh0056 acosh 0.001 0.0 -> 0.0 1.56979632662823
acosh0057 acosh 0.001 -0.0 -> 0.0 -1.56979632662823
acosh0058 acosh 0.57899999999999996 0.0 -> 0.0 0.95329467197772655
acosh0059 acosh 0.57899999999999996 -0.0 -> 0.0 -0.95329467197772655
acosh0060 acosh 0.99999999999999989 0.0 -> 0.0 1.4901161193847656e-08
acosh0061 acosh 0.99999999999999989 -0.0 -> 0.0 -1.4901161193847656e-08
acosh0062 acosh 1.0000000000000002 0.0 -> 2.1073424255447014e-08 0.0
acosh0063 acosh 1.0000000000000002 -0.0 -> 2.1073424255447014e-08 -0.0
acosh0064 acosh 1.0009999999999999 0.0 -> 0.044717633608306849 0.0
acosh0065 acosh 1.0009999999999999 -0.0 -> 0.044717633608306849 -0.0
acosh0066 acosh 2.0 0.0 -> 1.3169578969248168 0.0
acosh0067 acosh 2.0 -0.0 -> 1.3169578969248168 -0.0
acosh0068 acosh 23.0 0.0 -> 3.8281684713331012 0.0
acosh0069 acosh 23.0 -0.0 -> 3.8281684713331012 -0.0
acosh0070 acosh 10000000000000000.0 0.0 -> 37.534508668464674 0.0
acosh0071 acosh 10000000000000000.0 -0.0 -> 37.534508668464674 -0.0
acosh0072 acosh 9.9999999999999998e+149 0.0 -> 346.08091112966679 0.0
acosh0073 acosh 9.9999999999999998e+149 -0.0 -> 346.08091112966679 -0.0
acosh0074 acosh 1.0000000000000001e+299 0.0 -> 689.16608998577965 0.0
acosh0075 acosh 1.0000000000000001e+299 -0.0 -> 689.16608998577965 -0.0
-- random inputs
acosh0100 acosh -1.4328589581250843 -1.8370347775558309 -> 1.5526962646549587 -2.190250168435786
acosh0101 acosh -0.31075819156220957 -1.0772555786839297 -> 0.95139168286193709 -1.7812228089636479
acosh0102 acosh -1.9044776578070453 -20.485370158932124 -> 3.7177411088932359 -1.6633888745861227
acosh0103 acosh -0.075642506000858742 -21965976320.873051 -> 24.505907742881991 -1.5707963267983402
acosh0104 acosh -1.6162271181056307 -3.0369343458696099 -> 1.9407057262861227 -2.0429549461750209
acosh0105 acosh -0.3103780280298063 0.00018054880018078987 -> 0.00018992877058761416 1.886386995096728
acosh0106 acosh -9159468751.5897655 5.8014747664273649 -> 23.631201197959193 3.1415926529564078
acosh0107 acosh -0.037739157550933884 0.21841357493510705 -> 0.21685844960602488 1.6076735133449402
acosh0108 acosh -8225991.0508394297 0.28318543008913644 -> 16.615956520420287 3.1415926191641019
acosh0109 acosh -35.620070502302639 0.31303237005015 -> 4.2658980006943965 3.1328013255541873
acosh0110 acosh 96.729939906820917 -0.029345228372365334 -> 5.2650434775863548 -0.00030338895866972843
acosh0111 acosh 0.59656024007966491 -2.0412294654163978 -> 1.4923002024287835 -1.312568421900338
acosh0112 acosh 109.29384112677828 -0.00015454863061533812 -> 5.3871662961545477 -1.4141245154061214e-06
acosh0113 acosh 8.6705651969361597 -3.6723631649787465 -> 2.9336180958363545 -0.40267362031872861
acosh0114 acosh 1.8101646445052686 -0.012345132721855478 -> 1.1997148566285769 -0.0081813912760150265
acosh0115 acosh 52.56897195025288 0.001113916065985443 -> 4.6551827622264135 2.1193445872040307e-05
acosh0116 acosh 0.28336786164214739 355643992457.40485 -> 27.290343226816528 1.5707963267940999
acosh0117 acosh 0.73876621291911437 2.8828594541104322e-20 -> 4.2774820978159067e-20 0.73955845836827927
acosh0118 acosh 0.025865471781718878 37125746064318.492 -> 31.938478989418012 1.5707963267948959
acosh0119 acosh 2.2047353511780132 0.074712248143489271 -> 1.4286403248698021 0.037997904971626598
-- values near infinity
acosh0200 acosh 8.1548592876467785e+307 9.0943779335951128e+307 -> 710.08944620800605 0.83981165425478954
acosh0201 acosh 1.4237229680972531e+308 -1.0336966617874858e+308 -> 710.4543331094759 -0.6279972876348755
acosh0202 acosh -1.5014526899738939e+308 1.5670700378448792e+308 -> 710.66420706795464 2.3348137299106697
acosh0203 acosh -1.0939040375213928e+308 -1.0416960351127978e+308 -> 710.30182863115886 -2.380636147787027
acosh0204 acosh 0.0 1.476062433559588e+308 -> 710.27873384716929 1.5707963267948966
acosh0205 acosh -0.0 6.2077210326221094e+307 -> 709.41256457484769 1.5707963267948966
acosh0206 acosh 0.0 -1.5621899909968308e+308 -> 710.33544449990734 -1.5707963267948966
acosh0207 acosh -0.0 -8.3556624833839122e+307 -> 709.70971018048317 -1.5707963267948966
acosh0208 acosh 1.3067079752499342e+308 0.0 -> 710.15686680107228 0.0
acosh0209 acosh 1.5653640340214026e+308 -0.0 -> 710.33747422926706 -0.0
acosh0210 acosh -6.9011375992290636e+307 0.0 -> 709.51845699719922 3.1415926535897931
acosh0211 acosh -9.9539576809926973e+307 -0.0 -> 709.88474095870185 -3.1415926535897931
acosh0212 acosh 7.6449598518914925e+307 9.5706540768268358 -> 709.62081731754802 1.2518906916769345e-307
acosh0213 acosh 5.4325410972602197e+307 -7.8064807816522706 -> 709.279177727925 -1.4369851312471974e-307
acosh0214 acosh -1.1523626112360465e+308 7.0617510038869336 -> 710.03117010216909 3.1415926535897931
acosh0215 acosh -1.1685027786862599e+308 -5.1568558357925625 -> 710.04507907571417 -3.1415926535897931
acosh0216 acosh 3.0236370339788721 1.7503248720096417e+308 -> 710.44915723458064 1.5707963267948966
acosh0217 acosh 6.6108007926031149 -9.1469968225806149e+307 -> 709.80019633903328 -1.5707963267948966
acosh0218 acosh -5.1096262905623959 6.4484926785412395e+307 -> 709.45061713997973 1.5707963267948966
acosh0219 acosh -2.8080920608735846 -1.7716118836519368e+308 -> 710.46124562363445 -1.5707963267948966
-- values near 0
acosh0220 acosh 4.5560530326699304e-317 7.3048989121436657e-318 -> 7.3048989121436657e-318 1.5707963267948966
acosh0221 acosh 4.8754274133585331e-314 -9.8469794897684199e-315 -> 9.8469794897684199e-315 -1.5707963267948966
acosh0222 acosh -4.6748876009960097e-312 9.7900342887557606e-318 -> 9.7900342887557606e-318 1.5707963267948966
acosh0223 acosh -4.3136871538399236e-320 -4.9406564584124654e-323 -> 4.9406564584124654e-323 -1.5707963267948966
acosh0224 acosh 0.0 4.3431013866496774e-314 -> 4.3431013866496774e-314 1.5707963267948966
acosh0225 acosh -0.0 6.0147334335829184e-317 -> 6.0147334335829184e-317 1.5707963267948966
acosh0226 acosh 0.0 -1.2880291387081297e-320 -> 1.2880291387081297e-320 -1.5707963267948966
acosh0227 acosh -0.0 -1.4401563976534621e-317 -> 1.4401563976534621e-317 -1.5707963267948966
acosh0228 acosh 1.3689680570863091e-313 0.0 -> 0.0 1.5707963267948966
acosh0229 acosh 1.5304346893494371e-312 -0.0 -> 0.0 -1.5707963267948966
acosh0230 acosh -3.7450175954766488e-320 0.0 -> 0.0 1.5707963267948966
acosh0231 acosh -8.4250563080885801e-311 -0.0 -> 0.0 -1.5707963267948966
-- special values
acosh1000 acosh 0.0 0.0 -> 0.0 1.5707963267948966
acosh1001 acosh -0.0 0.0 -> 0.0 1.5707963267948966
acosh1002 acosh 0.0 inf -> inf 1.5707963267948966
acosh1003 acosh 2.3 inf -> inf 1.5707963267948966
acosh1004 acosh -0.0 inf -> inf 1.5707963267948966
acosh1005 acosh -2.3 inf -> inf 1.5707963267948966
acosh1006 acosh 0.0 nan -> nan nan
acosh1007 acosh 2.3 nan -> nan nan
acosh1008 acosh -0.0 nan -> nan nan
acosh1009 acosh -2.3 nan -> nan nan
acosh1010 acosh -inf 0.0 -> inf 3.1415926535897931
acosh1011 acosh -inf 2.3 -> inf 3.1415926535897931
acosh1012 acosh inf 0.0 -> inf 0.0
acosh1013 acosh inf 2.3 -> inf 0.0
acosh1014 acosh -inf inf -> inf 2.3561944901923448
acosh1015 acosh inf inf -> inf 0.78539816339744828
acosh1016 acosh inf nan -> inf nan
acosh1017 acosh -inf nan -> inf nan
acosh1018 acosh nan 0.0 -> nan nan
acosh1019 acosh nan 2.3 -> nan nan
acosh1020 acosh nan inf -> inf nan
acosh1021 acosh nan nan -> nan nan
acosh1022 acosh 0.0 -0.0 -> 0.0 -1.5707963267948966
acosh1023 acosh -0.0 -0.0 -> 0.0 -1.5707963267948966
acosh1024 acosh 0.0 -inf -> inf -1.5707963267948966
acosh1025 acosh 2.3 -inf -> inf -1.5707963267948966
acosh1026 acosh -0.0 -inf -> inf -1.5707963267948966
acosh1027 acosh -2.3 -inf -> inf -1.5707963267948966
acosh1028 acosh -inf -0.0 -> inf -3.1415926535897931
acosh1029 acosh -inf -2.3 -> inf -3.1415926535897931
acosh1030 acosh inf -0.0 -> inf -0.0
acosh1031 acosh inf -2.3 -> inf -0.0
acosh1032 acosh -inf -inf -> inf -2.3561944901923448
acosh1033 acosh inf -inf -> inf -0.78539816339744828
acosh1034 acosh nan -0.0 -> nan nan
acosh1035 acosh nan -2.3 -> nan nan
acosh1036 acosh nan -inf -> inf nan
------------------------
-- asin: Inverse sine --
------------------------
-- zeros
asin0000 asin 0.0 0.0 -> 0.0 0.0
asin0001 asin 0.0 -0.0 -> 0.0 -0.0
asin0002 asin -0.0 0.0 -> -0.0 0.0
asin0003 asin -0.0 -0.0 -> -0.0 -0.0
-- branch points: +/-1
asin0010 asin 1.0 0.0 -> 1.5707963267948966 0.0
asin0011 asin 1.0 -0.0 -> 1.5707963267948966 -0.0
asin0012 asin -1.0 0.0 -> -1.5707963267948966 0.0
asin0013 asin -1.0 -0.0 -> -1.5707963267948966 -0.0
-- values along both sides of real axis
asin0020 asin -9.8813129168249309e-324 0.0 -> -9.8813129168249309e-324 0.0
asin0021 asin -9.8813129168249309e-324 -0.0 -> -9.8813129168249309e-324 -0.0
asin0022 asin -1e-305 0.0 -> -1e-305 0.0
asin0023 asin -1e-305 -0.0 -> -1e-305 -0.0
asin0024 asin -1e-150 0.0 -> -1e-150 0.0
asin0025 asin -1e-150 -0.0 -> -1e-150 -0.0
asin0026 asin -9.9999999999999998e-17 0.0 -> -9.9999999999999998e-17 0.0
asin0027 asin -9.9999999999999998e-17 -0.0 -> -9.9999999999999998e-17 -0.0
asin0028 asin -0.001 0.0 -> -0.0010000001666667416 0.0
asin0029 asin -0.001 -0.0 -> -0.0010000001666667416 -0.0
asin0030 asin -0.57899999999999996 0.0 -> -0.61750165481717001 0.0
asin0031 asin -0.57899999999999996 -0.0 -> -0.61750165481717001 -0.0
asin0032 asin -0.99999999999999989 0.0 -> -1.5707963118937354 0.0
asin0033 asin -0.99999999999999989 -0.0 -> -1.5707963118937354 -0.0
asin0034 asin -1.0000000000000002 0.0 -> -1.5707963267948966 2.1073424255447014e-08
asin0035 asin -1.0000000000000002 -0.0 -> -1.5707963267948966 -2.1073424255447014e-08
asin0036 asin -1.0009999999999999 0.0 -> -1.5707963267948966 0.044717633608306849
asin0037 asin -1.0009999999999999 -0.0 -> -1.5707963267948966 -0.044717633608306849
asin0038 asin -2.0 0.0 -> -1.5707963267948966 1.3169578969248168
asin0039 asin -2.0 -0.0 -> -1.5707963267948966 -1.3169578969248168
asin0040 asin -23.0 0.0 -> -1.5707963267948966 3.8281684713331012
asin0041 asin -23.0 -0.0 -> -1.5707963267948966 -3.8281684713331012
asin0042 asin -10000000000000000.0 0.0 -> -1.5707963267948966 37.534508668464674
asin0043 asin -10000000000000000.0 -0.0 -> -1.5707963267948966 -37.534508668464674
asin0044 asin -9.9999999999999998e+149 0.0 -> -1.5707963267948966 346.08091112966679
asin0045 asin -9.9999999999999998e+149 -0.0 -> -1.5707963267948966 -346.08091112966679
asin0046 asin -1.0000000000000001e+299 0.0 -> -1.5707963267948966 689.16608998577965
asin0047 asin -1.0000000000000001e+299 -0.0 -> -1.5707963267948966 -689.16608998577965
asin0048 asin 9.8813129168249309e-324 0.0 -> 9.8813129168249309e-324 0.0
asin0049 asin 9.8813129168249309e-324 -0.0 -> 9.8813129168249309e-324 -0.0
asin0050 asin 1e-305 0.0 -> 1e-305 0.0
asin0051 asin 1e-305 -0.0 -> 1e-305 -0.0
asin0052 asin 1e-150 0.0 -> 1e-150 0.0
asin0053 asin 1e-150 -0.0 -> 1e-150 -0.0
asin0054 asin 9.9999999999999998e-17 0.0 -> 9.9999999999999998e-17 0.0
asin0055 asin 9.9999999999999998e-17 -0.0 -> 9.9999999999999998e-17 -0.0
asin0056 asin 0.001 0.0 -> 0.0010000001666667416 0.0
asin0057 asin 0.001 -0.0 -> 0.0010000001666667416 -0.0
asin0058 asin 0.57899999999999996 0.0 -> 0.61750165481717001 0.0
asin0059 asin 0.57899999999999996 -0.0 -> 0.61750165481717001 -0.0
asin0060 asin 0.99999999999999989 0.0 -> 1.5707963118937354 0.0
asin0061 asin 0.99999999999999989 -0.0 -> 1.5707963118937354 -0.0
asin0062 asin 1.0000000000000002 0.0 -> 1.5707963267948966 2.1073424255447014e-08
asin0063 asin 1.0000000000000002 -0.0 -> 1.5707963267948966 -2.1073424255447014e-08
asin0064 asin 1.0009999999999999 0.0 -> 1.5707963267948966 0.044717633608306849
asin0065 asin 1.0009999999999999 -0.0 -> 1.5707963267948966 -0.044717633608306849
asin0066 asin 2.0 0.0 -> 1.5707963267948966 1.3169578969248168
asin0067 asin 2.0 -0.0 -> 1.5707963267948966 -1.3169578969248168
asin0068 asin 23.0 0.0 -> 1.5707963267948966 3.8281684713331012
asin0069 asin 23.0 -0.0 -> 1.5707963267948966 -3.8281684713331012
asin0070 asin 10000000000000000.0 0.0 -> 1.5707963267948966 37.534508668464674
asin0071 asin 10000000000000000.0 -0.0 -> 1.5707963267948966 -37.534508668464674
asin0072 asin 9.9999999999999998e+149 0.0 -> 1.5707963267948966 346.08091112966679
asin0073 asin 9.9999999999999998e+149 -0.0 -> 1.5707963267948966 -346.08091112966679
asin0074 asin 1.0000000000000001e+299 0.0 -> 1.5707963267948966 689.16608998577965
asin0075 asin 1.0000000000000001e+299 -0.0 -> 1.5707963267948966 -689.16608998577965
-- random inputs
asin0100 asin -1.5979555835086083 -0.15003009814595247 -> -1.4515369557405788 -1.0544476399790823
asin0101 asin -0.57488225895317679 -9.6080397838952743e-13 -> -0.61246024460412851 -1.174238005400403e-12
asin0102 asin -3.6508087930516249 -0.36027527093220152 -> -1.4685890605305874 -1.9742273007152038
asin0103 asin -1.5238659792326819 -1.1360813516996364 -> -0.86080051691147275 -1.3223742205689195
asin0104 asin -1592.0639045555306 -0.72362427935018236 -> -1.5703418071175179 -8.0659336918729228
asin0105 asin -0.19835471371312019 4.2131508416697709 -> -0.045777831019935149 2.1461732751933171
asin0106 asin -1.918471054430213 0.40603305079779234 -> -1.3301396585791556 1.30263642314981
asin0107 asin -254495.01623373642 0.71084414434470822 -> -1.5707935336394359 13.140183712762321
asin0108 asin -0.31315882715691157 3.9647994288429866 -> -0.076450403840916004 2.0889762138713457
asin0109 asin -0.90017064284720816 1.2530659485907105 -> -0.53466509741943447 1.1702811557577
asin0110 asin 2.1615181696571075 -0.14058647488229523 -> 1.4976166323896871 -1.4085811039334604
asin0111 asin 1.2104749210707795 -0.85732484485298999 -> 0.83913071588343924 -1.0681719250525901
asin0112 asin 1.7059733185128891 -0.84032966373156581 -> 1.0510900815816229 -1.2967979791361652
asin0113 asin 9.9137085017290687 -1.4608383970250893 -> 1.4237704820128891 -2.995414677560686
asin0114 asin 117.12344751041495 -5453908091.5334015 -> 2.1475141411392012e-08 -23.112745450217066
asin0115 asin 0.081041187798029227 0.067054349860173196 -> 0.080946786856771813 0.067223991060639698
asin0116 asin 46.635472322049949 2.3835190718056678 -> 1.5197194940010779 4.5366989600972083
asin0117 asin 3907.0687961127105 19.144021886390181 -> 1.5658965233083235 8.9637018715924217
asin0118 asin 1.0889312322308273 509.01577883554768 -> 0.0021392803817829316 6.9256294494524706
asin0119 asin 0.10851518277509224 1.5612510908217476 -> 0.058491014243902621 1.2297075725621327
-- values near infinity
asin0200 asin 1.5230241998821499e+308 5.5707228994084525e+307 -> 1.2201446370892068 710.37283486535966
asin0201 asin 8.1334317698672204e+307 -9.2249425197872451e+307 -> 0.72259991284020042 -710.0962453049026
asin0202 asin -9.9138506659241768e+307 6.701544526434995e+307 -> -0.97637511742194594 710.06887486671371
asin0203 asin -1.4141298868173842e+308 -5.401505134514191e+307 -> -1.2059319055160587 -710.30396478954628
asin0204 asin 0.0 9.1618092977897431e+307 -> 0.0 709.80181441050593
asin0205 asin -0.0 6.8064342551939755e+307 -> -0.0 709.50463910853489
asin0206 asin 0.0 -6.4997516454798215e+307 -> 0.0 -709.45853469751592
asin0207 asin -0.0 -1.6767449053345242e+308 -> -0.0 -710.4062101803022
asin0208 asin 5.4242749957378916e+307 0.0 -> 1.5707963267948966 709.27765497888902
asin0209 asin 9.5342145121164749e+307 -0.0 -> 1.5707963267948966 -709.84165758595907
asin0210 asin -7.0445698006201847e+307 0.0 -> -1.5707963267948966 709.53902780872136
asin0211 asin -1.0016025569769706e+308 -0.0 -> -1.5707963267948966 -709.89095709697881
asin0212 asin 1.6552203778877204e+308 0.48761543336249491 -> 1.5707963267948966 710.39328998153474
asin0213 asin 1.2485712830384869e+308 -4.3489311161278899 -> 1.5707963267948966 -710.1113557467786
asin0214 asin -1.5117842813353125e+308 5.123452666102434 -> -1.5707963267948966 710.30264641923031
asin0215 asin -1.3167634313008016e+308 -0.52939679793528982 -> -1.5707963267948966 -710.16453260239768
asin0216 asin 0.80843929176985907 1.0150851827767876e+308 -> 7.9642507396113875e-309 709.90432835561637
asin0217 asin 8.2544809829680901 -1.7423548140539474e+308 -> 4.7375430746865733e-308 -710.44459336242164
asin0218 asin -5.2499000118824295 4.6655578977512214e+307 -> -1.1252459249113292e-307 709.1269781491103
asin0219 asin -5.9904782760833433 -4.7315689314781163e+307 -> -1.2660659419394637e-307 -709.14102757522312
-- special values
asin1000 asin -0.0 0.0 -> -0.0 0.0
asin1001 asin 0.0 0.0 -> 0.0 0.0
asin1002 asin -0.0 -0.0 -> -0.0 -0.0
asin1003 asin 0.0 -0.0 -> 0.0 -0.0
asin1004 asin -inf 0.0 -> -1.5707963267948966 inf
asin1005 asin -inf 2.2999999999999998 -> -1.5707963267948966 inf
asin1006 asin nan 0.0 -> nan nan
asin1007 asin nan 2.2999999999999998 -> nan nan
asin1008 asin -0.0 inf -> -0.0 inf
asin1009 asin -2.2999999999999998 inf -> -0.0 inf
asin1010 asin -inf inf -> -0.78539816339744828 inf
asin1011 asin nan inf -> nan inf
asin1012 asin -0.0 nan -> -0.0 nan
asin1013 asin -2.2999999999999998 nan -> nan nan
asin1014 asin -inf nan -> nan inf ignore-imag-sign
asin1015 asin nan nan -> nan nan
asin1016 asin inf 0.0 -> 1.5707963267948966 inf
asin1017 asin inf 2.2999999999999998 -> 1.5707963267948966 inf
asin1018 asin 0.0 inf -> 0.0 inf
asin1019 asin 2.2999999999999998 inf -> 0.0 inf
asin1020 asin inf inf -> 0.78539816339744828 inf
asin1021 asin 0.0 nan -> 0.0 nan
asin1022 asin 2.2999999999999998 nan -> nan nan
asin1023 asin inf nan -> nan inf ignore-imag-sign
asin1024 asin inf -0.0 -> 1.5707963267948966 -inf
asin1025 asin inf -2.2999999999999998 -> 1.5707963267948966 -inf
asin1026 asin nan -0.0 -> nan nan
asin1027 asin nan -2.2999999999999998 -> nan nan
asin1028 asin 0.0 -inf -> 0.0 -inf
asin1029 asin 2.2999999999999998 -inf -> 0.0 -inf
asin1030 asin inf -inf -> 0.78539816339744828 -inf
asin1031 asin nan -inf -> nan -inf
asin1032 asin -inf -0.0 -> -1.5707963267948966 -inf
asin1033 asin -inf -2.2999999999999998 -> -1.5707963267948966 -inf
asin1034 asin -0.0 -inf -> -0.0 -inf
asin1035 asin -2.2999999999999998 -inf -> -0.0 -inf
asin1036 asin -inf -inf -> -0.78539816339744828 -inf
------------------------------------
-- asinh: Inverse hyperbolic sine --
------------------------------------
-- zeros
asinh0000 asinh 0.0 0.0 -> 0.0 0.0
asinh0001 asinh 0.0 -0.0 -> 0.0 -0.0
asinh0002 asinh -0.0 0.0 -> -0.0 0.0
asinh0003 asinh -0.0 -0.0 -> -0.0 -0.0
-- branch points: +/-i
asinh0010 asinh 0.0 1.0 -> 0.0 1.5707963267948966
asinh0011 asinh 0.0 -1.0 -> 0.0 -1.5707963267948966
asinh0012 asinh -0.0 1.0 -> -0.0 1.5707963267948966
asinh0013 asinh -0.0 -1.0 -> -0.0 -1.5707963267948966
-- values along both sides of imaginary axis
asinh0020 asinh 0.0 -9.8813129168249309e-324 -> 0.0 -9.8813129168249309e-324
asinh0021 asinh -0.0 -9.8813129168249309e-324 -> -0.0 -9.8813129168249309e-324
asinh0022 asinh 0.0 -1e-305 -> 0.0 -1e-305
asinh0023 asinh -0.0 -1e-305 -> -0.0 -1e-305
asinh0024 asinh 0.0 -1e-150 -> 0.0 -1e-150
asinh0025 asinh -0.0 -1e-150 -> -0.0 -1e-150
asinh0026 asinh 0.0 -9.9999999999999998e-17 -> 0.0 -9.9999999999999998e-17
asinh0027 asinh -0.0 -9.9999999999999998e-17 -> -0.0 -9.9999999999999998e-17
asinh0028 asinh 0.0 -0.001 -> 0.0 -0.0010000001666667416
asinh0029 asinh -0.0 -0.001 -> -0.0 -0.0010000001666667416
asinh0030 asinh 0.0 -0.57899999999999996 -> 0.0 -0.61750165481717001
asinh0031 asinh -0.0 -0.57899999999999996 -> -0.0 -0.61750165481717001
asinh0032 asinh 0.0 -0.99999999999999989 -> 0.0 -1.5707963118937354
asinh0033 asinh -0.0 -0.99999999999999989 -> -0.0 -1.5707963118937354
asinh0034 asinh 0.0 -1.0000000000000002 -> 2.1073424255447014e-08 -1.5707963267948966
asinh0035 asinh -0.0 -1.0000000000000002 -> -2.1073424255447014e-08 -1.5707963267948966
asinh0036 asinh 0.0 -1.0009999999999999 -> 0.044717633608306849 -1.5707963267948966
asinh0037 asinh -0.0 -1.0009999999999999 -> -0.044717633608306849 -1.5707963267948966
asinh0038 asinh 0.0 -2.0 -> 1.3169578969248168 -1.5707963267948966
asinh0039 asinh -0.0 -2.0 -> -1.3169578969248168 -1.5707963267948966
asinh0040 asinh 0.0 -20.0 -> 3.6882538673612966 -1.5707963267948966
asinh0041 asinh -0.0 -20.0 -> -3.6882538673612966 -1.5707963267948966
asinh0042 asinh 0.0 -10000000000000000.0 -> 37.534508668464674 -1.5707963267948966
asinh0043 asinh -0.0 -10000000000000000.0 -> -37.534508668464674 -1.5707963267948966
asinh0044 asinh 0.0 -9.9999999999999998e+149 -> 346.08091112966679 -1.5707963267948966
asinh0045 asinh -0.0 -9.9999999999999998e+149 -> -346.08091112966679 -1.5707963267948966
asinh0046 asinh 0.0 -1.0000000000000001e+299 -> 689.16608998577965 -1.5707963267948966
asinh0047 asinh -0.0 -1.0000000000000001e+299 -> -689.16608998577965 -1.5707963267948966
asinh0048 asinh 0.0 9.8813129168249309e-324 -> 0.0 9.8813129168249309e-324
asinh0049 asinh -0.0 9.8813129168249309e-324 -> -0.0 9.8813129168249309e-324
asinh0050 asinh 0.0 1e-305 -> 0.0 1e-305
asinh0051 asinh -0.0 1e-305 -> -0.0 1e-305
asinh0052 asinh 0.0 1e-150 -> 0.0 1e-150
asinh0053 asinh -0.0 1e-150 -> -0.0 1e-150
asinh0054 asinh 0.0 9.9999999999999998e-17 -> 0.0 9.9999999999999998e-17
asinh0055 asinh -0.0 9.9999999999999998e-17 -> -0.0 9.9999999999999998e-17
asinh0056 asinh 0.0 0.001 -> 0.0 0.0010000001666667416
asinh0057 asinh -0.0 0.001 -> -0.0 0.0010000001666667416
asinh0058 asinh 0.0 0.57899999999999996 -> 0.0 0.61750165481717001
asinh0059 asinh -0.0 0.57899999999999996 -> -0.0 0.61750165481717001
asinh0060 asinh 0.0 0.99999999999999989 -> 0.0 1.5707963118937354
asinh0061 asinh -0.0 0.99999999999999989 -> -0.0 1.5707963118937354
asinh0062 asinh 0.0 1.0000000000000002 -> 2.1073424255447014e-08 1.5707963267948966
asinh0063 asinh -0.0 1.0000000000000002 -> -2.1073424255447014e-08 1.5707963267948966
asinh0064 asinh 0.0 1.0009999999999999 -> 0.044717633608306849 1.5707963267948966
asinh0065 asinh -0.0 1.0009999999999999 -> -0.044717633608306849 1.5707963267948966
asinh0066 asinh 0.0 2.0 -> 1.3169578969248168 1.5707963267948966
asinh0067 asinh -0.0 2.0 -> -1.3169578969248168 1.5707963267948966
asinh0068 asinh 0.0 20.0 -> 3.6882538673612966 1.5707963267948966
asinh0069 asinh -0.0 20.0 -> -3.6882538673612966 1.5707963267948966
asinh0070 asinh 0.0 10000000000000000.0 -> 37.534508668464674 1.5707963267948966
asinh0071 asinh -0.0 10000000000000000.0 -> -37.534508668464674 1.5707963267948966
asinh0072 asinh 0.0 9.9999999999999998e+149 -> 346.08091112966679 1.5707963267948966
asinh0073 asinh -0.0 9.9999999999999998e+149 -> -346.08091112966679 1.5707963267948966
asinh0074 asinh 0.0 1.0000000000000001e+299 -> 689.16608998577965 1.5707963267948966
asinh0075 asinh -0.0 1.0000000000000001e+299 -> -689.16608998577965 1.5707963267948966
-- random inputs
asinh0100 asinh -0.5946402853710423 -0.044506548910000145 -> -0.56459775392653022 -0.038256221441536356
asinh0101 asinh -0.19353958046180916 -0.017489624793193454 -> -0.19237926804196651 -0.017171741895336792
asinh0102 asinh -0.033117585138955893 -8.5256414015933757 -> -2.8327758348650969 -1.5668848791092411
asinh0103 asinh -1.5184043184035716 -0.73491245339073275 -> -1.2715891419764005 -0.39204624408542355
asinh0104 asinh -0.60716120271208818 -0.28900743958436542 -> -0.59119299421187232 -0.24745931678118135
asinh0105 asinh -0.0237177865112429 2.8832601052166313 -> -1.7205820772413236 1.5620261702963094
asinh0106 asinh -2.3906812342743979 2.6349216848574013 -> -1.9609636249445124 0.8142142660574706
asinh0107 asinh -0.0027605019787620517 183.85588476550555 -> -5.9072920005445066 1.5707813120847871
asinh0108 asinh -0.99083661164404713 0.028006797051617648 -> -0.8750185251283995 0.019894099615994653
asinh0109 asinh -3.0362951937986393 0.86377266758504867 -> -1.8636030714685221 0.26475058859950168
asinh0110 asinh 0.34438464536152769 -0.71603790174885029 -> 0.43985415690734164 -0.71015037409294324
asinh0111 asinh 4.4925124413876256 -60604595352.871613 -> 25.520783738612078 -1.5707963267207683
asinh0112 asinh 2.3213991428170337 -7.5459667007307258 -> 2.7560464993451643 -1.270073210856117
asinh0113 asinh 0.21291939741682028 -1.2720428814784408 -> 0.77275088137338266 -1.3182099250896895
asinh0114 asinh 6.6447359379455957 -0.97196191666946996 -> 2.602830695139672 -0.14368247412319965
asinh0115 asinh 7.1326256655083746 2.1516360452706857 -> 2.7051146374367212 0.29051701669727581
asinh0116 asinh 0.18846550905063442 3.4705348585339832 -> 1.917697875799296 1.514155593347924
asinh0117 asinh 0.19065075303281598 0.26216814548222012 -> 0.19603050785932474 0.26013422809614117
asinh0118 asinh 2.0242004665739719 0.70510281647495787 -> 1.4970366212896002 0.30526007200481453
asinh0119 asinh 37.336596461576057 717.29157391678234 -> 7.269981997945294 1.5187910219576033
-- values near infinity
asinh0200 asinh 1.0760517500874541e+308 1.1497786241240167e+308 -> 710.34346055651815 0.81850936961793475
asinh0201 asinh 1.1784839328845529e+308 -1.6478429586716638e+308 -> 710.59536255783678 -0.94996311735607697
asinh0202 asinh -4.8777682248909193e+307 1.4103736217538474e+308 -> -710.28970147376992 1.2378239519096443
asinh0203 asinh -1.2832478903233108e+308 -1.5732392613155698e+308 -> -710.59750164290745 -0.88657181439322452
asinh0204 asinh 0.0 6.8431383856345372e+307 -> 709.51001718444604 1.5707963267948966
asinh0205 asinh -0.0 8.601822432238051e+307 -> -709.73874482126689 1.5707963267948966
asinh0206 asinh 0.0 -5.5698396067303782e+307 -> 709.30413698733742 -1.5707963267948966
asinh0207 asinh -0.0 -7.1507777734621804e+307 -> -709.55399186002705 -1.5707963267948966
asinh0208 asinh 1.6025136110019349e+308 0.0 -> 710.3609292261076 0.0
asinh0209 asinh 1.3927819858239114e+308 -0.0 -> 710.22065899832899 -0.0
asinh0210 asinh -6.0442994056210995e+307 0.0 -> -709.38588631057621 0.0
asinh0211 asinh -1.2775271979042634e+308 -0.0 -> -710.13428215553972 -0.0
asinh0212 asinh 1.0687496260268489e+308 1.0255615699476961 -> 709.95584521407841 9.5959010882679093e-309
asinh0213 asinh 1.0050967333370962e+308 -0.87668970117333433 -> 709.89443961168183 -8.7224410556242882e-309
asinh0214 asinh -5.7161452814862392e+307 8.2377808413450122 -> -709.33006540611166 1.4411426644501116e-307
asinh0215 asinh -8.2009040727653315e+307 -6.407409526654976 -> -709.69101513070109 -7.8130526461510088e-308
asinh0216 asinh 6.4239368496483982 1.6365990821551427e+308 -> 710.38197618101287 1.5707963267948966
asinh0217 asinh 5.4729111423315882 -1.1227237438144211e+308 -> 710.00511346983546 -1.5707963267948966
asinh0218 asinh -8.3455818297412723 1.443172020182019e+308 -> -710.25619930551818 1.5707963267948966
asinh0219 asinh -2.6049726230372441 -1.7952291144022702e+308 -> -710.47448847685644 -1.5707963267948966
-- values near 0
asinh0220 asinh 1.2940113339664088e-314 6.9169190417774516e-323 -> 1.2940113339664088e-314 6.9169190417774516e-323
asinh0221 asinh 2.3848478863874649e-315 -3.1907655025717717e-310 -> 2.3848478863874649e-315 -3.1907655025717717e-310
asinh0222 asinh -3.0097643679641622e-316 4.6936236354918422e-322 -> -3.0097643679641622e-316 4.6936236354918422e-322
asinh0223 asinh -1.787997087755751e-308 -8.5619622834902341e-310 -> -1.787997087755751e-308 -8.5619622834902341e-310
asinh0224 asinh 0.0 1.2491433448427325e-314 -> 0.0 1.2491433448427325e-314
asinh0225 asinh -0.0 2.5024072154538062e-308 -> -0.0 2.5024072154538062e-308
asinh0226 asinh 0.0 -2.9643938750474793e-323 -> 0.0 -2.9643938750474793e-323
asinh0227 asinh -0.0 -2.9396905927554169e-320 -> -0.0 -2.9396905927554169e-320
asinh0228 asinh 5.64042930029359e-317 0.0 -> 5.64042930029359e-317 0.0
asinh0229 asinh 3.3833911866596068e-318 -0.0 -> 3.3833911866596068e-318 -0.0
asinh0230 asinh -4.9406564584124654e-324 0.0 -> -4.9406564584124654e-324 0.0
asinh0231 asinh -2.2211379227994845e-308 -0.0 -> -2.2211379227994845e-308 -0.0
-- special values
asinh1000 asinh 0.0 0.0 -> 0.0 0.0
asinh1001 asinh 0.0 -0.0 -> 0.0 -0.0
asinh1002 asinh -0.0 0.0 -> -0.0 0.0
asinh1003 asinh -0.0 -0.0 -> -0.0 -0.0
asinh1004 asinh 0.0 inf -> inf 1.5707963267948966
asinh1005 asinh 2.3 inf -> inf 1.5707963267948966
asinh1006 asinh 0.0 nan -> nan nan
asinh1007 asinh 2.3 nan -> nan nan
asinh1008 asinh inf 0.0 -> inf 0.0
asinh1009 asinh inf 2.3 -> inf 0.0
asinh1010 asinh inf inf -> inf 0.78539816339744828
asinh1011 asinh inf nan -> inf nan
asinh1012 asinh nan 0.0 -> nan 0.0
asinh1013 asinh nan 2.3 -> nan nan
asinh1014 asinh nan inf -> inf nan ignore-real-sign
asinh1015 asinh nan nan -> nan nan
asinh1016 asinh 0.0 -inf -> inf -1.5707963267948966
asinh1017 asinh 2.3 -inf -> inf -1.5707963267948966
asinh1018 asinh inf -0.0 -> inf -0.0
asinh1019 asinh inf -2.3 -> inf -0.0
asinh1020 asinh inf -inf -> inf -0.78539816339744828
asinh1021 asinh nan -0.0 -> nan -0.0
asinh1022 asinh nan -2.3 -> nan nan
asinh1023 asinh nan -inf -> inf nan ignore-real-sign
asinh1024 asinh -0.0 -inf -> -inf -1.5707963267948966
asinh1025 asinh -2.3 -inf -> -inf -1.5707963267948966
asinh1026 asinh -0.0 nan -> nan nan
asinh1027 asinh -2.3 nan -> nan nan
asinh1028 asinh -inf -0.0 -> -inf -0.0
asinh1029 asinh -inf -2.3 -> -inf -0.0
asinh1030 asinh -inf -inf -> -inf -0.78539816339744828
asinh1031 asinh -inf nan -> -inf nan
asinh1032 asinh -0.0 inf -> -inf 1.5707963267948966
asinh1033 asinh -2.3 inf -> -inf 1.5707963267948966
asinh1034 asinh -inf 0.0 -> -inf 0.0
asinh1035 asinh -inf 2.3 -> -inf 0.0
asinh1036 asinh -inf inf -> -inf 0.78539816339744828
---------------------------
-- atan: Inverse tangent --
---------------------------
-- zeros
-- These are tested in testAtanSign in test_cmath.py
-- atan0000 atan 0.0 0.0 -> 0.0 0.0
-- atan0001 atan 0.0 -0.0 -> 0.0 -0.0
-- atan0002 atan -0.0 0.0 -> -0.0 0.0
-- atan0003 atan -0.0 -0.0 -> -0.0 -0.0
-- values along both sides of imaginary axis
atan0010 atan 0.0 -9.8813129168249309e-324 -> 0.0 -9.8813129168249309e-324
atan0011 atan -0.0 -9.8813129168249309e-324 -> -0.0 -9.8813129168249309e-324
atan0012 atan 0.0 -1e-305 -> 0.0 -1e-305
atan0013 atan -0.0 -1e-305 -> -0.0 -1e-305
atan0014 atan 0.0 -1e-150 -> 0.0 -1e-150
atan0015 atan -0.0 -1e-150 -> -0.0 -1e-150
atan0016 atan 0.0 -9.9999999999999998e-17 -> 0.0 -9.9999999999999998e-17
atan0017 atan -0.0 -9.9999999999999998e-17 -> -0.0 -9.9999999999999998e-17
atan0018 atan 0.0 -0.001 -> 0.0 -0.0010000003333335333
atan0019 atan -0.0 -0.001 -> -0.0 -0.0010000003333335333
atan0020 atan 0.0 -0.57899999999999996 -> 0.0 -0.6609570902866303
atan0021 atan -0.0 -0.57899999999999996 -> -0.0 -0.6609570902866303
atan0022 atan 0.0 -0.99999999999999989 -> 0.0 -18.714973875118524
atan0023 atan -0.0 -0.99999999999999989 -> -0.0 -18.714973875118524
atan0024 atan 0.0 -1.0000000000000002 -> 1.5707963267948966 -18.36840028483855
atan0025 atan -0.0 -1.0000000000000002 -> -1.5707963267948966 -18.36840028483855
atan0026 atan 0.0 -1.0009999999999999 -> 1.5707963267948966 -3.8007011672919218
atan0027 atan -0.0 -1.0009999999999999 -> -1.5707963267948966 -3.8007011672919218
atan0028 atan 0.0 -2.0 -> 1.5707963267948966 -0.54930614433405489
atan0029 atan -0.0 -2.0 -> -1.5707963267948966 -0.54930614433405489
atan0030 atan 0.0 -20.0 -> 1.5707963267948966 -0.050041729278491265
atan0031 atan -0.0 -20.0 -> -1.5707963267948966 -0.050041729278491265
atan0032 atan 0.0 -10000000000000000.0 -> 1.5707963267948966 -9.9999999999999998e-17
atan0033 atan -0.0 -10000000000000000.0 -> -1.5707963267948966 -9.9999999999999998e-17
atan0034 atan 0.0 -9.9999999999999998e+149 -> 1.5707963267948966 -1e-150
atan0035 atan -0.0 -9.9999999999999998e+149 -> -1.5707963267948966 -1e-150
atan0036 atan 0.0 -1.0000000000000001e+299 -> 1.5707963267948966 -9.9999999999999999e-300
atan0037 atan -0.0 -1.0000000000000001e+299 -> -1.5707963267948966 -9.9999999999999999e-300
atan0038 atan 0.0 9.8813129168249309e-324 -> 0.0 9.8813129168249309e-324
atan0039 atan -0.0 9.8813129168249309e-324 -> -0.0 9.8813129168249309e-324
atan0040 atan 0.0 1e-305 -> 0.0 1e-305
atan0041 atan -0.0 1e-305 -> -0.0 1e-305
atan0042 atan 0.0 1e-150 -> 0.0 1e-150
atan0043 atan -0.0 1e-150 -> -0.0 1e-150
atan0044 atan 0.0 9.9999999999999998e-17 -> 0.0 9.9999999999999998e-17
atan0045 atan -0.0 9.9999999999999998e-17 -> -0.0 9.9999999999999998e-17
atan0046 atan 0.0 0.001 -> 0.0 0.0010000003333335333
atan0047 atan -0.0 0.001 -> -0.0 0.0010000003333335333
atan0048 atan 0.0 0.57899999999999996 -> 0.0 0.6609570902866303
atan0049 atan -0.0 0.57899999999999996 -> -0.0 0.6609570902866303
atan0050 atan 0.0 0.99999999999999989 -> 0.0 18.714973875118524
atan0051 atan -0.0 0.99999999999999989 -> -0.0 18.714973875118524
atan0052 atan 0.0 1.0000000000000002 -> 1.5707963267948966 18.36840028483855
atan0053 atan -0.0 1.0000000000000002 -> -1.5707963267948966 18.36840028483855
atan0054 atan 0.0 1.0009999999999999 -> 1.5707963267948966 3.8007011672919218
atan0055 atan -0.0 1.0009999999999999 -> -1.5707963267948966 3.8007011672919218
atan0056 atan 0.0 2.0 -> 1.5707963267948966 0.54930614433405489
atan0057 atan -0.0 2.0 -> -1.5707963267948966 0.54930614433405489
atan0058 atan 0.0 20.0 -> 1.5707963267948966 0.050041729278491265
atan0059 atan -0.0 20.0 -> -1.5707963267948966 0.050041729278491265
atan0060 atan 0.0 10000000000000000.0 -> 1.5707963267948966 9.9999999999999998e-17
atan0061 atan -0.0 10000000000000000.0 -> -1.5707963267948966 9.9999999999999998e-17
atan0062 atan 0.0 9.9999999999999998e+149 -> 1.5707963267948966 1e-150
atan0063 atan -0.0 9.9999999999999998e+149 -> -1.5707963267948966 1e-150
atan0064 atan 0.0 1.0000000000000001e+299 -> 1.5707963267948966 9.9999999999999999e-300
atan0065 atan -0.0 1.0000000000000001e+299 -> -1.5707963267948966 9.9999999999999999e-300
-- random inputs
atan0100 atan -0.32538873661060214 -1.5530461550412578 -> -1.3682728427554227 -0.69451401598762041
atan0101 atan -0.45863393495197929 -4799.1747094903594 -> -1.5707963068820623 -0.00020836916050636145
atan0102 atan -8.3006999685976162 -2.6788890251790938 -> -1.4619862771810199 -0.034811669653327826
atan0103 atan -1.8836307682985314 -1.1441976638861771 -> -1.1839984370871612 -0.20630956157312796
atan0104 atan -0.00063230482407491669 -4.9312520961829485 -> -1.5707692093223147 -0.20563867743008304
atan0105 atan -0.84278137150065946 179012.37493146997 -> -1.5707963267685969 5.5862059836425272e-06
atan0106 atan -0.95487853984049287 14.311334539886177 -> -1.5661322859434561 0.069676024526232005
atan0107 atan -1.3513252539663239 6.0500727021632198e-08 -> -0.93371676315220975 2.140800269742656e-08
atan0108 atan -0.20566254458595795 0.11933771944159823 -> -0.20556463711174916 0.11493405387141732
atan0109 atan -0.58563718795408559 0.64438965423212868 -> -0.68361089300233124 0.46759762751800249
atan0110 atan 48.479267751948292 -78.386382460112543 -> 1.5650888770910523 -0.0092276811373297584
atan0111 atan 1.0575373914056061 -0.75988012377296987 -> 0.94430886722043594 -0.31915698126703118
atan0112 atan 4444810.4314677203 -0.56553404593942558 -> 1.5707961018134231 -2.8625446437701909e-14
atan0113 atan 0.010101405082520009 -0.032932668550282478 -> 0.01011202676646334 -0.032941214776834996
atan0114 atan 1.5353585300154911 -2.1947099346796519 -> 1.3400310739206394 -0.29996003607449045
atan0115 atan 0.21869457055670882 9.9915684254007093 -> 1.5685846078876444 0.1003716881759439
atan0116 atan 0.17783290150246836 0.064334689863650957 -> 0.17668728064286277 0.062435808728873846
atan0117 atan 15.757474087615918 383.57262142534 -> 1.5706894060369621 0.0026026817278826603
atan0118 atan 10.587017408533317 0.21720238081843438 -> 1.4766594681336236 0.0019199097383010061
atan0119 atan 0.86026078678781204 0.1230148609359502 -> 0.7147259322534929 0.070551221954286605
-- values near infinity
atan0200 atan 7.8764397011195798e+307 8.1647921137746308e+307 -> 1.5707963267948966 6.3439446939604493e-309
atan0201 atan 1.5873698696131487e+308 -1.0780367422960641e+308 -> 1.5707963267948966 -2.9279309368530781e-309
atan0202 atan -1.5844551864825834e+308 1.0290657809098675e+308 -> -1.5707963267948966 2.8829614736961417e-309
atan0203 atan -1.3168792562524032e+308 -9.088432341614825e+307 -> -1.5707963267948966 -3.5499373057390056e-309
atan0204 atan 0.0 1.0360465742258337e+308 -> 1.5707963267948966 9.6520757355646018e-309
atan0205 atan -0.0 1.0045063210373196e+308 -> -1.5707963267948966 9.955138947929503e-309
atan0206 atan 0.0 -9.5155296715763696e+307 -> 1.5707963267948966 -1.050913648020118e-308
atan0207 atan -0.0 -1.5565700490496501e+308 -> -1.5707963267948966 -6.4243816114189071e-309
atan0208 atan 1.2956339389525244e+308 0.0 -> 1.5707963267948966 0.0
atan0209 atan 1.4408126243772151e+308 -0.0 -> 1.5707963267948966 -0.0
atan0210 atan -1.0631786461936417e+308 0.0 -> -1.5707963267948966 0.0
atan0211 atan -1.0516056964171069e+308 -0.0 -> -1.5707963267948966 -0.0
atan0212 atan 1.236162319603838e+308 4.6827953496242936 -> 1.5707963267948966 0.0
atan0213 atan 7.000516472897218e+307 -5.8631608017844163 -> 1.5707963267948966 -0.0
atan0214 atan -1.5053444003338508e+308 5.1199197268420313 -> -1.5707963267948966 0.0
atan0215 atan -1.399172518147259e+308 -3.5687766472913673 -> -1.5707963267948966 -0.0
atan0216 atan 8.1252833070803021 6.2782953917343822e+307 -> 1.5707963267948966 1.5927890256908564e-308
atan0217 atan 2.8034285947515167 -1.3378049775753878e+308 -> 1.5707963267948966 -7.4749310756219562e-309
atan0218 atan -1.4073509988974953 1.6776381785968355e+308 -> -1.5707963267948966 5.9607608646364569e-309
atan0219 atan -2.7135551527592119 -1.281567445525738e+308 -> -1.5707963267948966 -7.8029447727565326e-309
-- imaginary part = +/-1, real part tiny
atan0300 atan -1e-150 -1.0 -> -0.78539816339744828 -173.04045556483339
atan0301 atan 1e-155 1.0 -> 0.78539816339744828 178.79691829731851
atan0302 atan 9.9999999999999999e-161 -1.0 -> 0.78539816339744828 -184.55338102980363
atan0303 atan -1e-165 1.0 -> -0.78539816339744828 190.30984376228875
atan0304 atan -9.9998886718268301e-321 -1.0 -> -0.78539816339744828 -368.76019403576692
-- Additional real values (mpmath)
atan0400 atan 1.7976931348623157e+308 0.0 -> 1.5707963267948966192 0.0
atan0401 atan -1.7976931348623157e+308 0.0 -> -1.5707963267948966192 0.0
atan0402 atan 1e-17 0.0 -> 1.0000000000000000715e-17 0.0
atan0403 atan -1e-17 0.0 -> -1.0000000000000000715e-17 0.0
atan0404 atan 0.0001 0.0 -> 0.000099999999666666673459 0.0
atan0405 atan -0.0001 0.0 -> -0.000099999999666666673459 0.0
atan0406 atan 0.999999999999999 0.0 -> 0.78539816339744781002 0.0
atan0407 atan 1.000000000000001 0.0 -> 0.78539816339744886473 0.0
atan0408 atan 14.101419947171719 0.0 -> 1.4999999999999999969 0.0
atan0409 atan 1255.7655915007897 0.0 -> 1.5700000000000000622 0.0
-- special values
atan1000 atan -0.0 0.0 -> -0.0 0.0
atan1001 atan nan 0.0 -> nan 0.0
atan1002 atan -0.0 1.0 -> -0.0 inf divide-by-zero
atan1003 atan -inf 0.0 -> -1.5707963267948966 0.0
atan1004 atan -inf 2.2999999999999998 -> -1.5707963267948966 0.0
atan1005 atan nan 2.2999999999999998 -> nan nan
atan1006 atan -0.0 inf -> -1.5707963267948966 0.0
atan1007 atan -2.2999999999999998 inf -> -1.5707963267948966 0.0
atan1008 atan -inf inf -> -1.5707963267948966 0.0
atan1009 atan nan inf -> nan 0.0
atan1010 atan -0.0 nan -> nan nan
atan1011 atan -2.2999999999999998 nan -> nan nan
atan1012 atan -inf nan -> -1.5707963267948966 0.0 ignore-imag-sign
atan1013 atan nan nan -> nan nan
atan1014 atan 0.0 0.0 -> 0.0 0.0
atan1015 atan 0.0 1.0 -> 0.0 inf divide-by-zero
atan1016 atan inf 0.0 -> 1.5707963267948966 0.0
atan1017 atan inf 2.2999999999999998 -> 1.5707963267948966 0.0
atan1018 atan 0.0 inf -> 1.5707963267948966 0.0
atan1019 atan 2.2999999999999998 inf -> 1.5707963267948966 0.0
atan1020 atan inf inf -> 1.5707963267948966 0.0
atan1021 atan 0.0 nan -> nan nan
atan1022 atan 2.2999999999999998 nan -> nan nan
atan1023 atan inf nan -> 1.5707963267948966 0.0 ignore-imag-sign
atan1024 atan 0.0 -0.0 -> 0.0 -0.0
atan1025 atan nan -0.0 -> nan -0.0
atan1026 atan 0.0 -1.0 -> 0.0 -inf divide-by-zero
atan1027 atan inf -0.0 -> 1.5707963267948966 -0.0
atan1028 atan inf -2.2999999999999998 -> 1.5707963267948966 -0.0
atan1029 atan nan -2.2999999999999998 -> nan nan
atan1030 atan 0.0 -inf -> 1.5707963267948966 -0.0
atan1031 atan 2.2999999999999998 -inf -> 1.5707963267948966 -0.0
atan1032 atan inf -inf -> 1.5707963267948966 -0.0
atan1033 atan nan -inf -> nan -0.0
atan1034 atan -0.0 -0.0 -> -0.0 -0.0
atan1035 atan -0.0 -1.0 -> -0.0 -inf divide-by-zero
atan1036 atan -inf -0.0 -> -1.5707963267948966 -0.0
atan1037 atan -inf -2.2999999999999998 -> -1.5707963267948966 -0.0
atan1038 atan -0.0 -inf -> -1.5707963267948966 -0.0
atan1039 atan -2.2999999999999998 -inf -> -1.5707963267948966 -0.0
atan1040 atan -inf -inf -> -1.5707963267948966 -0.0
---------------------------------------
-- atanh: Inverse hyperbolic tangent --
---------------------------------------
-- zeros
-- These are tested in testAtanhSign in test_cmath.py
-- atanh0000 atanh 0.0 0.0 -> 0.0 0.0
-- atanh0001 atanh 0.0 -0.0 -> 0.0 -0.0
-- atanh0002 atanh -0.0 0.0 -> -0.0 0.0
-- atanh0003 atanh -0.0 -0.0 -> -0.0 -0.0
-- values along both sides of real axis
atanh0010 atanh -9.8813129168249309e-324 0.0 -> -9.8813129168249309e-324 0.0
atanh0011 atanh -9.8813129168249309e-324 -0.0 -> -9.8813129168249309e-324 -0.0
atanh0012 atanh -1e-305 0.0 -> -1e-305 0.0
atanh0013 atanh -1e-305 -0.0 -> -1e-305 -0.0
atanh0014 atanh -1e-150 0.0 -> -1e-150 0.0
atanh0015 atanh -1e-150 -0.0 -> -1e-150 -0.0
atanh0016 atanh -9.9999999999999998e-17 0.0 -> -9.9999999999999998e-17 0.0
atanh0017 atanh -9.9999999999999998e-17 -0.0 -> -9.9999999999999998e-17 -0.0
atanh0018 atanh -0.001 0.0 -> -0.0010000003333335333 0.0
atanh0019 atanh -0.001 -0.0 -> -0.0010000003333335333 -0.0
atanh0020 atanh -0.57899999999999996 0.0 -> -0.6609570902866303 0.0
atanh0021 atanh -0.57899999999999996 -0.0 -> -0.6609570902866303 -0.0
atanh0022 atanh -0.99999999999999989 0.0 -> -18.714973875118524 0.0
atanh0023 atanh -0.99999999999999989 -0.0 -> -18.714973875118524 -0.0
atanh0024 atanh -1.0000000000000002 0.0 -> -18.36840028483855 1.5707963267948966
atanh0025 atanh -1.0000000000000002 -0.0 -> -18.36840028483855 -1.5707963267948966
atanh0026 atanh -1.0009999999999999 0.0 -> -3.8007011672919218 1.5707963267948966
atanh0027 atanh -1.0009999999999999 -0.0 -> -3.8007011672919218 -1.5707963267948966
atanh0028 atanh -2.0 0.0 -> -0.54930614433405489 1.5707963267948966
atanh0029 atanh -2.0 -0.0 -> -0.54930614433405489 -1.5707963267948966
atanh0030 atanh -23.0 0.0 -> -0.043505688494814884 1.5707963267948966
atanh0031 atanh -23.0 -0.0 -> -0.043505688494814884 -1.5707963267948966
atanh0032 atanh -10000000000000000.0 0.0 -> -9.9999999999999998e-17 1.5707963267948966
atanh0033 atanh -10000000000000000.0 -0.0 -> -9.9999999999999998e-17 -1.5707963267948966
atanh0034 atanh -9.9999999999999998e+149 0.0 -> -1e-150 1.5707963267948966
atanh0035 atanh -9.9999999999999998e+149 -0.0 -> -1e-150 -1.5707963267948966
atanh0036 atanh -1.0000000000000001e+299 0.0 -> -9.9999999999999999e-300 1.5707963267948966
atanh0037 atanh -1.0000000000000001e+299 -0.0 -> -9.9999999999999999e-300 -1.5707963267948966
atanh0038 atanh 9.8813129168249309e-324 0.0 -> 9.8813129168249309e-324 0.0
atanh0039 atanh 9.8813129168249309e-324 -0.0 -> 9.8813129168249309e-324 -0.0
atanh0040 atanh 1e-305 0.0 -> 1e-305 0.0
atanh0041 atanh 1e-305 -0.0 -> 1e-305 -0.0
atanh0042 atanh 1e-150 0.0 -> 1e-150 0.0
atanh0043 atanh 1e-150 -0.0 -> 1e-150 -0.0
atanh0044 atanh 9.9999999999999998e-17 0.0 -> 9.9999999999999998e-17 0.0
atanh0045 atanh 9.9999999999999998e-17 -0.0 -> 9.9999999999999998e-17 -0.0
atanh0046 atanh 0.001 0.0 -> 0.0010000003333335333 0.0
atanh0047 atanh 0.001 -0.0 -> 0.0010000003333335333 -0.0
atanh0048 atanh 0.57899999999999996 0.0 -> 0.6609570902866303 0.0
atanh0049 atanh 0.57899999999999996 -0.0 -> 0.6609570902866303 -0.0
atanh0050 atanh 0.99999999999999989 0.0 -> 18.714973875118524 0.0
atanh0051 atanh 0.99999999999999989 -0.0 -> 18.714973875118524 -0.0
atanh0052 atanh 1.0000000000000002 0.0 -> 18.36840028483855 1.5707963267948966
atanh0053 atanh 1.0000000000000002 -0.0 -> 18.36840028483855 -1.5707963267948966
atanh0054 atanh 1.0009999999999999 0.0 -> 3.8007011672919218 1.5707963267948966
atanh0055 atanh 1.0009999999999999 -0.0 -> 3.8007011672919218 -1.5707963267948966
atanh0056 atanh 2.0 0.0 -> 0.54930614433405489 1.5707963267948966
atanh0057 atanh 2.0 -0.0 -> 0.54930614433405489 -1.5707963267948966
atanh0058 atanh 23.0 0.0 -> 0.043505688494814884 1.5707963267948966
atanh0059 atanh 23.0 -0.0 -> 0.043505688494814884 -1.5707963267948966
atanh0060 atanh 10000000000000000.0 0.0 -> 9.9999999999999998e-17 1.5707963267948966
atanh0061 atanh 10000000000000000.0 -0.0 -> 9.9999999999999998e-17 -1.5707963267948966
atanh0062 atanh 9.9999999999999998e+149 0.0 -> 1e-150 1.5707963267948966
atanh0063 atanh 9.9999999999999998e+149 -0.0 -> 1e-150 -1.5707963267948966
atanh0064 atanh 1.0000000000000001e+299 0.0 -> 9.9999999999999999e-300 1.5707963267948966
atanh0065 atanh 1.0000000000000001e+299 -0.0 -> 9.9999999999999999e-300 -1.5707963267948966
-- random inputs
atanh0100 atanh -0.54460925980633501 -0.54038050126721027 -> -0.41984265808446974 -0.60354153938352828
atanh0101 atanh -1.6934614269829051 -0.48807386108113621 -> -0.58592769102243281 -1.3537837470975898
atanh0102 atanh -1.3467293985501207 -0.47868354895395876 -> -0.69961624370709985 -1.1994450156570076
atanh0103 atanh -5.6142232418984888 -544551613.39307702 -> -1.8932657550925744e-17 -1.5707963249585235
atanh0104 atanh -0.011841460381263651 -3.259978899823385 -> -0.0010183936547405188 -1.2731614020743838
atanh0105 atanh -0.0073345736950029532 0.35821949670922248 -> -0.0065004869024682466 0.34399359971920895
atanh0106 atanh -13.866782244320014 0.9541129545860273 -> -0.071896852055058899 1.5658322704631409
atanh0107 atanh -708.59964982780775 21.984802159266675 -> -0.0014098779074189741 1.5707525842838959
atanh0108 atanh -30.916832076030602 1.3691897138829843 -> -0.032292682045743676 1.5693652094847115
atanh0109 atanh -0.57461806339861754 0.29534797443913063 -> -0.56467464472482765 0.39615612824172625
atanh0110 atanh 0.40089246737415685 -1.632285984300659 -> 0.1063832707890608 -1.0402821335326482
atanh0111 atanh 2119.6167688262176 -1.5383653437377242e+17 -> 8.9565008518382049e-32 -1.5707963267948966
atanh0112 atanh 756.86017850941641 -6.6064087133223817 -> 0.0013211481136820046 -1.5707847948702234
atanh0113 atanh 4.0490617718041602 -2.5784456791040652e-12 -> 0.25218425538553618 -1.5707963267947291
atanh0114 atanh 10.589254957173523 -0.13956391149624509 -> 0.094700890282197664 -1.5695407140217623
atanh0115 atanh 1.0171187553160499 0.70766113465354019 -> 0.55260251975367791 0.96619711116641682
atanh0116 atanh 0.031645502527750849 0.067319983726544394 -> 0.031513018344086742 0.067285437670549036
atanh0117 atanh 0.13670177624994517 0.43240089361857947 -> 0.11538933151017253 0.41392008145336212
atanh0118 atanh 0.64173899243596688 2.9008577686695256 -> 0.065680142424134405 1.2518535724053921
atanh0119 atanh 0.19313813528025942 38.799619150741869 -> 0.00012820765917366644 1.5450292202823612
-- values near infinity
atanh0200 atanh 5.3242646831347954e+307 1.3740396080084153e+308 -> 2.4519253616695576e-309 1.5707963267948966
atanh0201 atanh 1.158701641241358e+308 -6.5579268873375853e+307 -> 6.5365375267795098e-309 -1.5707963267948966
atanh0202 atanh -1.3435325735762247e+308 9.8947369259601547e+307 -> -4.8256680906589956e-309 1.5707963267948966
atanh0203 atanh -1.4359857522598942e+308 -9.4701204702391004e+307 -> -4.8531282262872645e-309 -1.5707963267948966
atanh0204 atanh 0.0 5.6614181068098497e+307 -> 0.0 1.5707963267948966
atanh0205 atanh -0.0 6.9813212721450139e+307 -> -0.0 1.5707963267948966
atanh0206 atanh 0.0 -7.4970613060311453e+307 -> 0.0 -1.5707963267948966
atanh0207 atanh -0.0 -1.5280601880314068e+308 -> -0.0 -1.5707963267948966
atanh0208 atanh 8.2219472336000745e+307 0.0 -> 1.2162568933954813e-308 1.5707963267948966
atanh0209 atanh 1.4811519617280899e+308 -0.0 -> 6.7515017083951325e-309 -1.5707963267948966
atanh0210 atanh -1.2282016263598785e+308 0.0 -> -8.1419856360537615e-309 1.5707963267948966
atanh0211 atanh -1.0616427760154426e+308 -0.0 -> -9.4193642399489563e-309 -1.5707963267948966
atanh0212 atanh 1.2971536510180682e+308 5.2847948452333293 -> 7.7091869510998328e-309 1.5707963267948966
atanh0213 atanh 1.1849860977411851e+308 -7.9781906447459949 -> 8.4389175696339014e-309 -1.5707963267948966
atanh0214 atanh -1.4029969422586635e+308 0.93891986543663375 -> -7.127599283218073e-309 1.5707963267948966
atanh0215 atanh -4.7508098912248211e+307 -8.2702421247039908 -> -2.1049042645278043e-308 -1.5707963267948966
atanh0216 atanh 8.2680742115769998 8.1153898410918065e+307 -> 0.0 1.5707963267948966
atanh0217 atanh 1.2575325146218885 -1.4746679147661649e+308 -> 0.0 -1.5707963267948966
atanh0218 atanh -2.4618803682310899 1.3781522717005568e+308 -> -0.0 1.5707963267948966
atanh0219 atanh -4.0952386694788112 -1.231083376353703e+308 -> -0.0 -1.5707963267948966
-- values near 0
atanh0220 atanh 3.8017563659811628e-314 2.6635484239074319e-312 -> 3.8017563659811628e-314 2.6635484239074319e-312
atanh0221 atanh 1.7391110733611878e-321 -4.3547800672541419e-313 -> 1.7391110733611878e-321 -4.3547800672541419e-313
atanh0222 atanh -5.9656816081325078e-317 9.9692253555416263e-313 -> -5.9656816081325078e-317 9.9692253555416263e-313
atanh0223 atanh -6.5606671178400239e-313 -2.1680936406357335e-309 -> -6.5606671178400239e-313 -2.1680936406357335e-309
atanh0224 atanh 0.0 2.5230944401820779e-319 -> 0.0 2.5230944401820779e-319
atanh0225 atanh -0.0 5.6066569490064658e-320 -> -0.0 5.6066569490064658e-320
atanh0226 atanh 0.0 -2.4222487249468377e-317 -> 0.0 -2.4222487249468377e-317
atanh0227 atanh -0.0 -3.0861101089206037e-316 -> -0.0 -3.0861101089206037e-316
atanh0228 atanh 3.1219222884393986e-310 0.0 -> 3.1219222884393986e-310 0.0
atanh0229 atanh 9.8926337564976196e-309 -0.0 -> 9.8926337564976196e-309 -0.0
atanh0230 atanh -1.5462535092918154e-312 0.0 -> -1.5462535092918154e-312 0.0
atanh0231 atanh -9.8813129168249309e-324 -0.0 -> -9.8813129168249309e-324 -0.0
-- real part = +/-1, imaginary part tiny
atanh0300 atanh 1.0 1e-153 -> 176.49433320432448 0.78539816339744828
atanh0301 atanh 1.0 9.9999999999999997e-155 -> 177.64562575082149 0.78539816339744828
atanh0302 atanh -1.0 1e-161 -> -185.70467357630065 0.78539816339744828
atanh0303 atanh 1.0 -1e-165 -> 190.30984376228875 -0.78539816339744828
atanh0304 atanh -1.0 -9.8813129168249309e-324 -> -372.22003596069061 -0.78539816339744828
-- special values
atanh1000 atanh 0.0 0.0 -> 0.0 0.0
atanh1001 atanh 0.0 nan -> 0.0 nan
atanh1002 atanh 1.0 0.0 -> inf 0.0 divide-by-zero
atanh1003 atanh 0.0 inf -> 0.0 1.5707963267948966
atanh1004 atanh 2.3 inf -> 0.0 1.5707963267948966
atanh1005 atanh 2.3 nan -> nan nan
atanh1006 atanh inf 0.0 -> 0.0 1.5707963267948966
atanh1007 atanh inf 2.3 -> 0.0 1.5707963267948966
atanh1008 atanh inf inf -> 0.0 1.5707963267948966
atanh1009 atanh inf nan -> 0.0 nan
atanh1010 atanh nan 0.0 -> nan nan
atanh1011 atanh nan 2.3 -> nan nan
atanh1012 atanh nan inf -> 0.0 1.5707963267948966 ignore-real-sign
atanh1013 atanh nan nan -> nan nan
atanh1014 atanh 0.0 -0.0 -> 0.0 -0.0
atanh1015 atanh 1.0 -0.0 -> inf -0.0 divide-by-zero
atanh1016 atanh 0.0 -inf -> 0.0 -1.5707963267948966
atanh1017 atanh 2.3 -inf -> 0.0 -1.5707963267948966
atanh1018 atanh inf -0.0 -> 0.0 -1.5707963267948966
atanh1019 atanh inf -2.3 -> 0.0 -1.5707963267948966
atanh1020 atanh inf -inf -> 0.0 -1.5707963267948966
atanh1021 atanh nan -0.0 -> nan nan
atanh1022 atanh nan -2.3 -> nan nan
atanh1023 atanh nan -inf -> 0.0 -1.5707963267948966 ignore-real-sign
atanh1024 atanh -0.0 -0.0 -> -0.0 -0.0
atanh1025 atanh -0.0 nan -> -0.0 nan
atanh1026 atanh -1.0 -0.0 -> -inf -0.0 divide-by-zero
atanh1027 atanh -0.0 -inf -> -0.0 -1.5707963267948966
atanh1028 atanh -2.3 -inf -> -0.0 -1.5707963267948966
atanh1029 atanh -2.3 nan -> nan nan
atanh1030 atanh -inf -0.0 -> -0.0 -1.5707963267948966
atanh1031 atanh -inf -2.3 -> -0.0 -1.5707963267948966
atanh1032 atanh -inf -inf -> -0.0 -1.5707963267948966
atanh1033 atanh -inf nan -> -0.0 nan
atanh1034 atanh -0.0 0.0 -> -0.0 0.0
atanh1035 atanh -1.0 0.0 -> -inf 0.0 divide-by-zero
atanh1036 atanh -0.0 inf -> -0.0 1.5707963267948966
atanh1037 atanh -2.3 inf -> -0.0 1.5707963267948966
atanh1038 atanh -inf 0.0 -> -0.0 1.5707963267948966
atanh1039 atanh -inf 2.3 -> -0.0 1.5707963267948966
atanh1040 atanh -inf inf -> -0.0 1.5707963267948966
----------------------------
-- log: Natural logarithm --
----------------------------
log0000 log 1.0 0.0 -> 0.0 0.0
log0001 log 1.0 -0.0 -> 0.0 -0.0
log0002 log -1.0 0.0 -> 0.0 3.1415926535897931
log0003 log -1.0 -0.0 -> 0.0 -3.1415926535897931
-- values along both sides of real axis
log0010 log -9.8813129168249309e-324 0.0 -> -743.74692474082133 3.1415926535897931
log0011 log -9.8813129168249309e-324 -0.0 -> -743.74692474082133 -3.1415926535897931
log0012 log -1e-305 0.0 -> -702.28845336318398 3.1415926535897931
log0013 log -1e-305 -0.0 -> -702.28845336318398 -3.1415926535897931
log0014 log -1e-150 0.0 -> -345.38776394910684 3.1415926535897931
log0015 log -1e-150 -0.0 -> -345.38776394910684 -3.1415926535897931
log0016 log -9.9999999999999998e-17 0.0 -> -36.841361487904734 3.1415926535897931
log0017 log -9.9999999999999998e-17 -0.0 -> -36.841361487904734 -3.1415926535897931
log0018 log -0.001 0.0 -> -6.9077552789821368 3.1415926535897931
log0019 log -0.001 -0.0 -> -6.9077552789821368 -3.1415926535897931
log0020 log -0.57899999999999996 0.0 -> -0.54645280140914188 3.1415926535897931
log0021 log -0.57899999999999996 -0.0 -> -0.54645280140914188 -3.1415926535897931
log0022 log -0.99999999999999989 0.0 -> -1.1102230246251565e-16 3.1415926535897931
log0023 log -0.99999999999999989 -0.0 -> -1.1102230246251565e-16 -3.1415926535897931
log0024 log -1.0000000000000002 0.0 -> 2.2204460492503128e-16 3.1415926535897931
log0025 log -1.0000000000000002 -0.0 -> 2.2204460492503128e-16 -3.1415926535897931
log0026 log -1.0009999999999999 0.0 -> 0.00099950033308342321 3.1415926535897931
log0027 log -1.0009999999999999 -0.0 -> 0.00099950033308342321 -3.1415926535897931
log0028 log -2.0 0.0 -> 0.69314718055994529 3.1415926535897931
log0029 log -2.0 -0.0 -> 0.69314718055994529 -3.1415926535897931
log0030 log -23.0 0.0 -> 3.1354942159291497 3.1415926535897931
log0031 log -23.0 -0.0 -> 3.1354942159291497 -3.1415926535897931
log0032 log -10000000000000000.0 0.0 -> 36.841361487904734 3.1415926535897931
log0033 log -10000000000000000.0 -0.0 -> 36.841361487904734 -3.1415926535897931
log0034 log -9.9999999999999998e+149 0.0 -> 345.38776394910684 3.1415926535897931
log0035 log -9.9999999999999998e+149 -0.0 -> 345.38776394910684 -3.1415926535897931
log0036 log -1.0000000000000001e+299 0.0 -> 688.47294280521965 3.1415926535897931
log0037 log -1.0000000000000001e+299 -0.0 -> 688.47294280521965 -3.1415926535897931
log0038 log 9.8813129168249309e-324 0.0 -> -743.74692474082133 0.0
log0039 log 9.8813129168249309e-324 -0.0 -> -743.74692474082133 -0.0
log0040 log 1e-305 0.0 -> -702.28845336318398 0.0
log0041 log 1e-305 -0.0 -> -702.28845336318398 -0.0
log0042 log 1e-150 0.0 -> -345.38776394910684 0.0
log0043 log 1e-150 -0.0 -> -345.38776394910684 -0.0
log0044 log 9.9999999999999998e-17 0.0 -> -36.841361487904734 0.0
log0045 log 9.9999999999999998e-17 -0.0 -> -36.841361487904734 -0.0
log0046 log 0.001 0.0 -> -6.9077552789821368 0.0
log0047 log 0.001 -0.0 -> -6.9077552789821368 -0.0
log0048 log 0.57899999999999996 0.0 -> -0.54645280140914188 0.0
log0049 log 0.57899999999999996 -0.0 -> -0.54645280140914188 -0.0
log0050 log 0.99999999999999989 0.0 -> -1.1102230246251565e-16 0.0
log0051 log 0.99999999999999989 -0.0 -> -1.1102230246251565e-16 -0.0
log0052 log 1.0000000000000002 0.0 -> 2.2204460492503128e-16 0.0
log0053 log 1.0000000000000002 -0.0 -> 2.2204460492503128e-16 -0.0
log0054 log 1.0009999999999999 0.0 -> 0.00099950033308342321 0.0
log0055 log 1.0009999999999999 -0.0 -> 0.00099950033308342321 -0.0
log0056 log 2.0 0.0 -> 0.69314718055994529 0.0
log0057 log 2.0 -0.0 -> 0.69314718055994529 -0.0
log0058 log 23.0 0.0 -> 3.1354942159291497 0.0
log0059 log 23.0 -0.0 -> 3.1354942159291497 -0.0
log0060 log 10000000000000000.0 0.0 -> 36.841361487904734 0.0
log0061 log 10000000000000000.0 -0.0 -> 36.841361487904734 -0.0
log0062 log 9.9999999999999998e+149 0.0 -> 345.38776394910684 0.0
log0063 log 9.9999999999999998e+149 -0.0 -> 345.38776394910684 -0.0
log0064 log 1.0000000000000001e+299 0.0 -> 688.47294280521965 0.0
log0065 log 1.0000000000000001e+299 -0.0 -> 688.47294280521965 -0.0
-- random inputs
log0066 log -1.9830454945186191e-16 -2.0334448025673346 -> 0.70973130194329803 -1.5707963267948968
log0067 log -0.96745853024741857 -0.84995816228299692 -> 0.25292811398722387 -2.4207570438536905
log0068 log -0.1603644313948418 -0.2929942111041835 -> -1.0965857872427374 -2.0715870859971419
log0069 log -0.15917913168438699 -0.25238799251132177 -> -1.2093477313249901 -2.1334784232033863
log0070 log -0.68907818535078802 -3.0693105853476346 -> 1.1460398629184565 -1.7916403813913211
log0071 log -17.268133447565589 6.8165120014604756 -> 2.9212694465974836 2.7656245081603164
log0072 log -1.7153894479690328 26.434055372802636 -> 3.2767542953718003 1.6355986276341734
log0073 log -8.0456794648936578e-06 0.19722758057570208 -> -1.6233969848296075 1.5708371206810101
log0074 log -2.4306442691323173 0.6846919750700996 -> 0.92633592001969589 2.8670160576718331
log0075 log -3.5488049250888194 0.45324040643185254 -> 1.2747008374256426 3.0145640007885111
log0076 log 0.18418516851510189 -0.26062518836212617 -> -1.1421287121940344 -0.95558440841183434
log0077 log 2.7124837795638399 -13.148769067133387 -> 2.5971659975706802 -1.3673583045209439
log0078 log 3.6521275476169149e-13 -3.7820543023170673e-05 -> -10.182658136741569 -1.5707963171384316
log0079 log 5.0877545813862239 -1.2834978326786852 -> 1.6576856213076328 -0.24711583497738485
log0080 log 0.26477986808461512 -0.67659001194187429 -> -0.31944085207999973 -1.197773671987121
log0081 log 0.0014754261398071962 5.3514691608205442 -> 1.6773711707153829 1.5705206219261802
log0082 log 0.29667334462157885 0.00020056045042584795 -> -1.2151233667079588 0.00067603114168689204
log0083 log 0.82104233671099425 3.9005387130133102 -> 1.3827918965299593 1.3633304701848363
log0084 log 0.27268135358180667 124.42088110945804 -> 4.8236724223559229 1.5686047258789015
log0085 log 0.0026286959168267485 0.47795808180573013 -> -0.73821712137809126 1.5652965360960087
-- values near infinity
log0100 log 1.0512025744003172e+308 7.2621669750664611e+307 -> 709.44123967814494 0.60455434048332968
log0101 log 5.5344249034372126e+307 -1.2155859158431275e+308 -> 709.48562300345679 -1.143553056717973
log0102 log -1.3155575403469408e+308 1.1610793541663864e+308 -> 709.75847809546428 2.41848796504974
log0103 log -1.632366720973235e+308 -1.54299446211448e+308 -> 710.00545236515586 -2.3843326028455087
log0104 log 0.0 5.9449276692327712e+307 -> 708.67616191258526 1.5707963267948966
log0105 log -0.0 1.1201850459025692e+308 -> 709.30970253338171 1.5707963267948966
log0106 log 0.0 -1.6214225933466528e+308 -> 709.6795125501086 -1.5707963267948966
log0107 log -0.0 -1.7453269791591058e+308 -> 709.75315056087379 -1.5707963267948966
log0108 log 1.440860577601428e+308 0.0 -> 709.56144920058262 0.0
log0109 log 1.391515176148282e+308 -0.0 -> 709.52660185041327 -0.0
log0110 log -1.201354401295296e+308 0.0 -> 709.37965823023956 3.1415926535897931
log0111 log -1.6704337825976804e+308 -0.0 -> 709.70929198492399 -3.1415926535897931
log0112 log 7.2276974655190223e+307 7.94879711369164 -> 708.87154406512104 1.0997689307850458e-307
log0113 log 1.1207859593716076e+308 -6.1956200868221147 -> 709.31023883080104 -5.5279244310803286e-308
log0114 log -4.6678933874471045e+307 9.947107893220382 -> 708.43433142431388 3.1415926535897931
log0115 log -1.5108012453950142e+308 -5.3117197179375619 -> 709.60884877835008 -3.1415926535897931
log0116 log 7.4903750871504435 1.5320703776626352e+308 -> 709.62282865085137 1.5707963267948966
log0117 log 5.9760325525654778 -8.0149473997349123e+307 -> 708.97493177248396 -1.5707963267948966
log0118 log -7.880194206386629 1.7861845814767441e+308 -> 709.77629046837137 1.5707963267948966
log0119 log -9.886438993852865 -6.19235781080747e+307 -> 708.71693946977302 -1.5707963267948966
-- values near 0
log0120 log 2.2996867579227779e-308 6.7861840770939125e-312 -> -708.36343567717392 0.00029509166223339815
log0121 log 6.9169190417774516e-323 -9.0414013188948118e-322 -> -739.22766796468386 -1.4944423210001669
log0122 log -1.5378064962914011e-316 1.8243628389354635e-310 -> -713.20014803142965 1.5707971697228842
log0123 log -2.3319898483706837e-321 -2.2358763941866371e-313 -> -719.9045008332522 -1.570796337224766
log0124 log 0.0 3.872770101081121e-315 -> -723.96033425374401 1.5707963267948966
log0125 log -0.0 9.6342800939043076e-322 -> -739.16707236281752 1.5707963267948966
log0126 log 0.0 -2.266099393427834e-308 -> -708.37814861757965 -1.5707963267948966
log0127 log -0.0 -2.1184695673766626e-315 -> -724.56361036731812 -1.5707963267948966
log0128 log 1.1363509854348671e-322 0.0 -> -741.30457770545206 0.0
log0129 log 3.5572726500569751e-322 -0.0 -> -740.16340580236522 -0.0
log0130 log -2.3696071074040593e-310 0.0 -> -712.93865466421641 3.1415926535897931
log0131 log -2.813283897266934e-317 -0.0 -> -728.88512203138862 -3.1415926535897931
-- values near the unit circle
log0200 log -0.59999999999999998 0.80000000000000004 -> 2.2204460492503132e-17 2.2142974355881808
log0201 log 0.79999999999999993 0.60000000000000009 -> 6.1629758220391547e-33 0.64350110879328448
-- special values
log1000 log -0.0 0.0 -> -inf 3.1415926535897931 divide-by-zero
log1001 log 0.0 0.0 -> -inf 0.0 divide-by-zero
log1002 log 0.0 inf -> inf 1.5707963267948966
log1003 log 2.3 inf -> inf 1.5707963267948966
log1004 log -0.0 inf -> inf 1.5707963267948966
log1005 log -2.3 inf -> inf 1.5707963267948966
log1006 log 0.0 nan -> nan nan
log1007 log 2.3 nan -> nan nan
log1008 log -0.0 nan -> nan nan
log1009 log -2.3 nan -> nan nan
log1010 log -inf 0.0 -> inf 3.1415926535897931
log1011 log -inf 2.3 -> inf 3.1415926535897931
log1012 log inf 0.0 -> inf 0.0
log1013 log inf 2.3 -> inf 0.0
log1014 log -inf inf -> inf 2.3561944901923448
log1015 log inf inf -> inf 0.78539816339744828
log1016 log inf nan -> inf nan
log1017 log -inf nan -> inf nan
log1018 log nan 0.0 -> nan nan
log1019 log nan 2.3 -> nan nan
log1020 log nan inf -> inf nan
log1021 log nan nan -> nan nan
log1022 log -0.0 -0.0 -> -inf -3.1415926535897931 divide-by-zero
log1023 log 0.0 -0.0 -> -inf -0.0 divide-by-zero
log1024 log 0.0 -inf -> inf -1.5707963267948966
log1025 log 2.3 -inf -> inf -1.5707963267948966
log1026 log -0.0 -inf -> inf -1.5707963267948966
log1027 log -2.3 -inf -> inf -1.5707963267948966
log1028 log -inf -0.0 -> inf -3.1415926535897931
log1029 log -inf -2.3 -> inf -3.1415926535897931
log1030 log inf -0.0 -> inf -0.0
log1031 log inf -2.3 -> inf -0.0
log1032 log -inf -inf -> inf -2.3561944901923448
log1033 log inf -inf -> inf -0.78539816339744828
log1034 log nan -0.0 -> nan nan
log1035 log nan -2.3 -> nan nan
log1036 log nan -inf -> inf nan
------------------------------
-- log10: Logarithm base 10 --
------------------------------
logt0000 log10 1.0 0.0 -> 0.0 0.0
logt0001 log10 1.0 -0.0 -> 0.0 -0.0
logt0002 log10 -1.0 0.0 -> 0.0 1.3643763538418414
logt0003 log10 -1.0 -0.0 -> 0.0 -1.3643763538418414
-- values along both sides of real axis
logt0010 log10 -9.8813129168249309e-324 0.0 -> -323.0051853474518 1.3643763538418414
logt0011 log10 -9.8813129168249309e-324 -0.0 -> -323.0051853474518 -1.3643763538418414
logt0012 log10 -1e-305 0.0 -> -305.0 1.3643763538418414
logt0013 log10 -1e-305 -0.0 -> -305.0 -1.3643763538418414
logt0014 log10 -1e-150 0.0 -> -150.0 1.3643763538418414
logt0015 log10 -1e-150 -0.0 -> -150.0 -1.3643763538418414
logt0016 log10 -9.9999999999999998e-17 0.0 -> -16.0 1.3643763538418414
logt0017 log10 -9.9999999999999998e-17 -0.0 -> -16.0 -1.3643763538418414
logt0018 log10 -0.001 0.0 -> -3.0 1.3643763538418414
logt0019 log10 -0.001 -0.0 -> -3.0 -1.3643763538418414
logt0020 log10 -0.57899999999999996 0.0 -> -0.23732143627256383 1.3643763538418414
logt0021 log10 -0.57899999999999996 -0.0 -> -0.23732143627256383 -1.3643763538418414
logt0022 log10 -0.99999999999999989 0.0 -> -4.821637332766436e-17 1.3643763538418414
logt0023 log10 -0.99999999999999989 -0.0 -> -4.821637332766436e-17 -1.3643763538418414
logt0024 log10 -1.0000000000000002 0.0 -> 9.6432746655328696e-17 1.3643763538418414
logt0025 log10 -1.0000000000000002 -0.0 -> 9.6432746655328696e-17 -1.3643763538418414
logt0026 log10 -1.0009999999999999 0.0 -> 0.0004340774793185929 1.3643763538418414
logt0027 log10 -1.0009999999999999 -0.0 -> 0.0004340774793185929 -1.3643763538418414
logt0028 log10 -2.0 0.0 -> 0.3010299956639812 1.3643763538418414
logt0029 log10 -2.0 -0.0 -> 0.3010299956639812 -1.3643763538418414
logt0030 log10 -23.0 0.0 -> 1.3617278360175928 1.3643763538418414
logt0031 log10 -23.0 -0.0 -> 1.3617278360175928 -1.3643763538418414
logt0032 log10 -10000000000000000.0 0.0 -> 16.0 1.3643763538418414
logt0033 log10 -10000000000000000.0 -0.0 -> 16.0 -1.3643763538418414
logt0034 log10 -9.9999999999999998e+149 0.0 -> 150.0 1.3643763538418414
logt0035 log10 -9.9999999999999998e+149 -0.0 -> 150.0 -1.3643763538418414
logt0036 log10 -1.0000000000000001e+299 0.0 -> 299.0 1.3643763538418414
logt0037 log10 -1.0000000000000001e+299 -0.0 -> 299.0 -1.3643763538418414
logt0038 log10 9.8813129168249309e-324 0.0 -> -323.0051853474518 0.0
logt0039 log10 9.8813129168249309e-324 -0.0 -> -323.0051853474518 -0.0
logt0040 log10 1e-305 0.0 -> -305.0 0.0
logt0041 log10 1e-305 -0.0 -> -305.0 -0.0
logt0042 log10 1e-150 0.0 -> -150.0 0.0
logt0043 log10 1e-150 -0.0 -> -150.0 -0.0
logt0044 log10 9.9999999999999998e-17 0.0 -> -16.0 0.0
logt0045 log10 9.9999999999999998e-17 -0.0 -> -16.0 -0.0
logt0046 log10 0.001 0.0 -> -3.0 0.0
logt0047 log10 0.001 -0.0 -> -3.0 -0.0
logt0048 log10 0.57899999999999996 0.0 -> -0.23732143627256383 0.0
logt0049 log10 0.57899999999999996 -0.0 -> -0.23732143627256383 -0.0
logt0050 log10 0.99999999999999989 0.0 -> -4.821637332766436e-17 0.0
logt0051 log10 0.99999999999999989 -0.0 -> -4.821637332766436e-17 -0.0
logt0052 log10 1.0000000000000002 0.0 -> 9.6432746655328696e-17 0.0
logt0053 log10 1.0000000000000002 -0.0 -> 9.6432746655328696e-17 -0.0
logt0054 log10 1.0009999999999999 0.0 -> 0.0004340774793185929 0.0
logt0055 log10 1.0009999999999999 -0.0 -> 0.0004340774793185929 -0.0
logt0056 log10 2.0 0.0 -> 0.3010299956639812 0.0
logt0057 log10 2.0 -0.0 -> 0.3010299956639812 -0.0
logt0058 log10 23.0 0.0 -> 1.3617278360175928 0.0
logt0059 log10 23.0 -0.0 -> 1.3617278360175928 -0.0
logt0060 log10 10000000000000000.0 0.0 -> 16.0 0.0
logt0061 log10 10000000000000000.0 -0.0 -> 16.0 -0.0
logt0062 log10 9.9999999999999998e+149 0.0 -> 150.0 0.0
logt0063 log10 9.9999999999999998e+149 -0.0 -> 150.0 -0.0
logt0064 log10 1.0000000000000001e+299 0.0 -> 299.0 0.0
logt0065 log10 1.0000000000000001e+299 -0.0 -> 299.0 -0.0
-- random inputs
logt0066 log10 -1.9830454945186191e-16 -2.0334448025673346 -> 0.30823238806798503 -0.68218817692092071
logt0067 log10 -0.96745853024741857 -0.84995816228299692 -> 0.10984528422284802 -1.051321426174086
logt0068 log10 -0.1603644313948418 -0.2929942111041835 -> -0.47624115633305419 -0.89967884023059597
logt0069 log10 -0.15917913168438699 -0.25238799251132177 -> -0.52521304641665956 -0.92655790645688119
logt0070 log10 -0.68907818535078802 -3.0693105853476346 -> 0.4977187885066448 -0.77809953119328823
logt0071 log10 -17.268133447565589 6.8165120014604756 -> 1.2686912008098534 1.2010954629104202
logt0072 log10 -1.7153894479690328 26.434055372802636 -> 1.423076309032751 0.71033145859005309
logt0073 log10 -8.0456794648936578e-06 0.19722758057570208 -> -0.70503235244987561 0.68220589348055516
logt0074 log10 -2.4306442691323173 0.6846919750700996 -> 0.40230257845332595 1.2451292533748923
logt0075 log10 -3.5488049250888194 0.45324040643185254 -> 0.55359553977141063 1.3092085108866405
logt0076 log10 0.18418516851510189 -0.26062518836212617 -> -0.49602019732913638 -0.41500503556604301
logt0077 log10 2.7124837795638399 -13.148769067133387 -> 1.1279348613317008 -0.59383616643803216
logt0078 log10 3.6521275476169149e-13 -3.7820543023170673e-05 -> -4.4222722398941112 -0.68218817272717114
logt0079 log10 5.0877545813862239 -1.2834978326786852 -> 0.71992371806426847 -0.10732104352159283
logt0080 log10 0.26477986808461512 -0.67659001194187429 -> -0.13873139935281681 -0.52018649631300229
logt0081 log10 0.0014754261398071962 5.3514691608205442 -> 0.72847304354528819 0.6820684398178033
logt0082 log10 0.29667334462157885 0.00020056045042584795 -> -0.52772137299296806 0.00029359659442937261
logt0083 log10 0.82104233671099425 3.9005387130133102 -> 0.60053889028349361 0.59208690021184018
logt0084 log10 0.27268135358180667 124.42088110945804 -> 2.094894315538069 0.68123637673656989
logt0085 log10 0.0026286959168267485 0.47795808180573013 -> -0.32060362226100814 0.67979964816877081
-- values near infinity
logt0100 log10 1.0512025744003172e+308 7.2621669750664611e+307 -> 308.10641562682065 0.26255461408256975
logt0101 log10 5.5344249034372126e+307 -1.2155859158431275e+308 -> 308.12569106009209 -0.496638782296212
logt0102 log10 -1.3155575403469408e+308 1.1610793541663864e+308 -> 308.24419052091019 1.0503359777705266
logt0103 log10 -1.632366720973235e+308 -1.54299446211448e+308 -> 308.3514500834093 -1.0355024924378222
logt0104 log10 0.0 5.9449276692327712e+307 -> 307.77414657501117 0.68218817692092071
logt0105 log10 -0.0 1.1201850459025692e+308 -> 308.04928977068465 0.68218817692092071
logt0106 log10 0.0 -1.6214225933466528e+308 -> 308.20989622030174 -0.68218817692092071
logt0107 log10 -0.0 -1.7453269791591058e+308 -> 308.24187680203539 -0.68218817692092071
logt0108 log10 1.440860577601428e+308 0.0 -> 308.15862195908755 0.0
logt0109 log10 1.391515176148282e+308 -0.0 -> 308.14348794720007 -0.0
logt0110 log10 -1.201354401295296e+308 0.0 -> 308.07967114380773 1.3643763538418414
logt0111 log10 -1.6704337825976804e+308 -0.0 -> 308.22282926451624 -1.3643763538418414
logt0112 log10 7.2276974655190223e+307 7.94879711369164 -> 307.85899996571993 4.7762357800858463e-308
logt0113 log10 1.1207859593716076e+308 -6.1956200868221147 -> 308.04952268169455 -2.4007470767963597e-308
logt0114 log10 -4.6678933874471045e+307 9.947107893220382 -> 307.66912092839902 1.3643763538418414
logt0115 log10 -1.5108012453950142e+308 -5.3117197179375619 -> 308.1792073341565 -1.3643763538418414
logt0116 log10 7.4903750871504435 1.5320703776626352e+308 -> 308.18527871564157 0.68218817692092071
logt0117 log10 5.9760325525654778 -8.0149473997349123e+307 -> 307.90390067652424 -0.68218817692092071
logt0118 log10 -7.880194206386629 1.7861845814767441e+308 -> 308.25192633617331 0.68218817692092071
logt0119 log10 -9.886438993852865 -6.19235781080747e+307 -> 307.79185604308338 -0.68218817692092071
-- values near 0
logt0120 log10 2.2996867579227779e-308 6.7861840770939125e-312 -> -307.63833129662572 0.00012815668056362305
logt0121 log10 6.9169190417774516e-323 -9.0414013188948118e-322 -> -321.04249706727148 -0.64902805353306059
logt0122 log10 -1.5378064962914011e-316 1.8243628389354635e-310 -> -309.73888878263222 0.68218854299989429
logt0123 log10 -2.3319898483706837e-321 -2.2358763941866371e-313 -> -312.65055220919641 -0.68218818145055538
logt0124 log10 0.0 3.872770101081121e-315 -> -314.41197828323476 0.68218817692092071
logt0125 log10 -0.0 9.6342800939043076e-322 -> -321.01618073175331 0.68218817692092071
logt0126 log10 0.0 -2.266099393427834e-308 -> -307.64472104545649 -0.68218817692092071
logt0127 log10 -0.0 -2.1184695673766626e-315 -> -314.67397777042407 -0.68218817692092071
logt0128 log10 1.1363509854348671e-322 0.0 -> -321.94448750709819 0.0
logt0129 log10 3.5572726500569751e-322 -0.0 -> -321.44888284668451 -0.0
logt0130 log10 -2.3696071074040593e-310 0.0 -> -309.62532365619722 1.3643763538418414
logt0131 log10 -2.813283897266934e-317 -0.0 -> -316.55078643961042 -1.3643763538418414
-- values near the unit circle
logt0200 log10 -0.59999999999999998 0.80000000000000004 -> 9.6432746655328709e-18 0.96165715756846815
logt0201 log10 0.79999999999999993 0.60000000000000009 -> 2.6765463916147622e-33 0.2794689806475476
-- special values
logt1000 log10 -0.0 0.0 -> -inf 1.3643763538418414 divide-by-zero
logt1001 log10 0.0 0.0 -> -inf 0.0 divide-by-zero
logt1002 log10 0.0 inf -> inf 0.68218817692092071
logt1003 log10 2.3 inf -> inf 0.68218817692092071
logt1004 log10 -0.0 inf -> inf 0.68218817692092071
logt1005 log10 -2.3 inf -> inf 0.68218817692092071
logt1006 log10 0.0 nan -> nan nan
logt1007 log10 2.3 nan -> nan nan
logt1008 log10 -0.0 nan -> nan nan
logt1009 log10 -2.3 nan -> nan nan
logt1010 log10 -inf 0.0 -> inf 1.3643763538418414
logt1011 log10 -inf 2.3 -> inf 1.3643763538418414
logt1012 log10 inf 0.0 -> inf 0.0
logt1013 log10 inf 2.3 -> inf 0.0
logt1014 log10 -inf inf -> inf 1.0232822653813811
logt1015 log10 inf inf -> inf 0.34109408846046035
logt1016 log10 inf nan -> inf nan
logt1017 log10 -inf nan -> inf nan
logt1018 log10 nan 0.0 -> nan nan
logt1019 log10 nan 2.3 -> nan nan
logt1020 log10 nan inf -> inf nan
logt1021 log10 nan nan -> nan nan
logt1022 log10 -0.0 -0.0 -> -inf -1.3643763538418414 divide-by-zero
logt1023 log10 0.0 -0.0 -> -inf -0.0 divide-by-zero
logt1024 log10 0.0 -inf -> inf -0.68218817692092071
logt1025 log10 2.3 -inf -> inf -0.68218817692092071
logt1026 log10 -0.0 -inf -> inf -0.68218817692092071
logt1027 log10 -2.3 -inf -> inf -0.68218817692092071
logt1028 log10 -inf -0.0 -> inf -1.3643763538418414
logt1029 log10 -inf -2.3 -> inf -1.3643763538418414
logt1030 log10 inf -0.0 -> inf -0.0
logt1031 log10 inf -2.3 -> inf -0.0
logt1032 log10 -inf -inf -> inf -1.0232822653813811
logt1033 log10 inf -inf -> inf -0.34109408846046035
logt1034 log10 nan -0.0 -> nan nan
logt1035 log10 nan -2.3 -> nan nan
logt1036 log10 nan -inf -> inf nan
-----------------------
-- sqrt: Square root --
-----------------------
-- zeros
sqrt0000 sqrt 0.0 0.0 -> 0.0 0.0
sqrt0001 sqrt 0.0 -0.0 -> 0.0 -0.0
sqrt0002 sqrt -0.0 0.0 -> 0.0 0.0
sqrt0003 sqrt -0.0 -0.0 -> 0.0 -0.0
-- values along both sides of real axis
sqrt0010 sqrt -9.8813129168249309e-324 0.0 -> 0.0 3.1434555694052576e-162
sqrt0011 sqrt -9.8813129168249309e-324 -0.0 -> 0.0 -3.1434555694052576e-162
sqrt0012 sqrt -1e-305 0.0 -> 0.0 3.1622776601683791e-153
sqrt0013 sqrt -1e-305 -0.0 -> 0.0 -3.1622776601683791e-153
sqrt0014 sqrt -1e-150 0.0 -> 0.0 9.9999999999999996e-76
sqrt0015 sqrt -1e-150 -0.0 -> 0.0 -9.9999999999999996e-76
sqrt0016 sqrt -9.9999999999999998e-17 0.0 -> 0.0 1e-08
sqrt0017 sqrt -9.9999999999999998e-17 -0.0 -> 0.0 -1e-08
sqrt0018 sqrt -0.001 0.0 -> 0.0 0.031622776601683791
sqrt0019 sqrt -0.001 -0.0 -> 0.0 -0.031622776601683791
sqrt0020 sqrt -0.57899999999999996 0.0 -> 0.0 0.76092049518987193
sqrt0021 sqrt -0.57899999999999996 -0.0 -> 0.0 -0.76092049518987193
sqrt0022 sqrt -0.99999999999999989 0.0 -> 0.0 0.99999999999999989
sqrt0023 sqrt -0.99999999999999989 -0.0 -> 0.0 -0.99999999999999989
sqrt0024 sqrt -1.0000000000000002 0.0 -> 0.0 1.0
sqrt0025 sqrt -1.0000000000000002 -0.0 -> 0.0 -1.0
sqrt0026 sqrt -1.0009999999999999 0.0 -> 0.0 1.000499875062461
sqrt0027 sqrt -1.0009999999999999 -0.0 -> 0.0 -1.000499875062461
sqrt0028 sqrt -2.0 0.0 -> 0.0 1.4142135623730951
sqrt0029 sqrt -2.0 -0.0 -> 0.0 -1.4142135623730951
sqrt0030 sqrt -23.0 0.0 -> 0.0 4.7958315233127191
sqrt0031 sqrt -23.0 -0.0 -> 0.0 -4.7958315233127191
sqrt0032 sqrt -10000000000000000.0 0.0 -> 0.0 100000000.0
sqrt0033 sqrt -10000000000000000.0 -0.0 -> 0.0 -100000000.0
sqrt0034 sqrt -9.9999999999999998e+149 0.0 -> 0.0 9.9999999999999993e+74
sqrt0035 sqrt -9.9999999999999998e+149 -0.0 -> 0.0 -9.9999999999999993e+74
sqrt0036 sqrt -1.0000000000000001e+299 0.0 -> 0.0 3.1622776601683796e+149
sqrt0037 sqrt -1.0000000000000001e+299 -0.0 -> 0.0 -3.1622776601683796e+149
sqrt0038 sqrt 9.8813129168249309e-324 0.0 -> 3.1434555694052576e-162 0.0
sqrt0039 sqrt 9.8813129168249309e-324 -0.0 -> 3.1434555694052576e-162 -0.0
sqrt0040 sqrt 1e-305 0.0 -> 3.1622776601683791e-153 0.0
sqrt0041 sqrt 1e-305 -0.0 -> 3.1622776601683791e-153 -0.0
sqrt0042 sqrt 1e-150 0.0 -> 9.9999999999999996e-76 0.0
sqrt0043 sqrt 1e-150 -0.0 -> 9.9999999999999996e-76 -0.0
sqrt0044 sqrt 9.9999999999999998e-17 0.0 -> 1e-08 0.0
sqrt0045 sqrt 9.9999999999999998e-17 -0.0 -> 1e-08 -0.0
sqrt0046 sqrt 0.001 0.0 -> 0.031622776601683791 0.0
sqrt0047 sqrt 0.001 -0.0 -> 0.031622776601683791 -0.0
sqrt0048 sqrt 0.57899999999999996 0.0 -> 0.76092049518987193 0.0
sqrt0049 sqrt 0.57899999999999996 -0.0 -> 0.76092049518987193 -0.0
sqrt0050 sqrt 0.99999999999999989 0.0 -> 0.99999999999999989 0.0
sqrt0051 sqrt 0.99999999999999989 -0.0 -> 0.99999999999999989 -0.0
sqrt0052 sqrt 1.0000000000000002 0.0 -> 1.0 0.0
sqrt0053 sqrt 1.0000000000000002 -0.0 -> 1.0 -0.0
sqrt0054 sqrt 1.0009999999999999 0.0 -> 1.000499875062461 0.0
sqrt0055 sqrt 1.0009999999999999 -0.0 -> 1.000499875062461 -0.0
sqrt0056 sqrt 2.0 0.0 -> 1.4142135623730951 0.0
sqrt0057 sqrt 2.0 -0.0 -> 1.4142135623730951 -0.0
sqrt0058 sqrt 23.0 0.0 -> 4.7958315233127191 0.0
sqrt0059 sqrt 23.0 -0.0 -> 4.7958315233127191 -0.0
sqrt0060 sqrt 10000000000000000.0 0.0 -> 100000000.0 0.0
sqrt0061 sqrt 10000000000000000.0 -0.0 -> 100000000.0 -0.0
sqrt0062 sqrt 9.9999999999999998e+149 0.0 -> 9.9999999999999993e+74 0.0
sqrt0063 sqrt 9.9999999999999998e+149 -0.0 -> 9.9999999999999993e+74 -0.0
sqrt0064 sqrt 1.0000000000000001e+299 0.0 -> 3.1622776601683796e+149 0.0
sqrt0065 sqrt 1.0000000000000001e+299 -0.0 -> 3.1622776601683796e+149 -0.0
-- random inputs
sqrt0100 sqrt -0.34252542541549913 -223039880.15076211 -> 10560.300180587592 -10560.300196805192
sqrt0101 sqrt -0.88790791393018909 -5.3307751730827402 -> 1.5027154613689004 -1.7737140896343291
sqrt0102 sqrt -113916.89291310767 -0.018143374626153858 -> 2.6877817875351178e-05 -337.51576691038952
sqrt0103 sqrt -0.63187172386197121 -0.26293913366617694 -> 0.16205707495266153 -0.81125471918761971
sqrt0104 sqrt -0.058185169308906215 -2.3548312990430991 -> 1.0717660342420072 -1.0985752598086966
sqrt0105 sqrt -1.0580584765935896 0.14400319259151736 -> 0.069837489270111242 1.030987755262468
sqrt0106 sqrt -1.1667595947504932 0.11159711473953678 -> 0.051598531319315251 1.0813981705111229
sqrt0107 sqrt -0.5123728411449906 0.026175433648339085 -> 0.018278026262418718 0.71603556293597614
sqrt0108 sqrt -3.7453400060067228 1.0946500314809635 -> 0.27990088541692498 1.9554243814742367
sqrt0109 sqrt -0.0027736121575097673 1.0367943000839817 -> 0.71903560338719175 0.72096172651250545
sqrt0110 sqrt 1501.2559699453188 -1.1997325207283589 -> 38.746047664730959 -0.015481998720355024
sqrt0111 sqrt 1.4830075326850578 -0.64100878436755349 -> 1.244712815741096 -0.25749264258434584
sqrt0112 sqrt 0.095395618499734602 -0.48226565701639595 -> 0.54175904053472879 -0.44509239434231551
sqrt0113 sqrt 0.50109185681863277 -0.54054037379892561 -> 0.7868179858332387 -0.34349772344520979
sqrt0114 sqrt 0.98779807595367897 -0.00019848758437225191 -> 0.99388031770665153 -9.9854872279921968e-05
sqrt0115 sqrt 11.845472380792259 0.0010051104581506761 -> 3.4417252072345397 0.00014601840612346451
sqrt0116 sqrt 2.3558249686735975 0.25605157371744403 -> 1.5371278477386647 0.083288964575761404
sqrt0117 sqrt 0.77584894123159098 1.0496420627016076 -> 1.0200744386390885 0.51449287568756552
sqrt0118 sqrt 1.8961715669604893 0.34940793467158854 -> 1.3827991781411615 0.12634080935066902
sqrt0119 sqrt 0.96025378316565801 0.69573224860140515 -> 1.0358710342209998 0.33581991658093457
-- values near 0
sqrt0120 sqrt 7.3577938365086866e-313 8.1181408465112743e-319 -> 8.5777583531543516e-157 4.732087634251168e-163
sqrt0121 sqrt 1.2406883874892108e-310 -5.1210133324269776e-312 -> 1.1140990057468052e-155 -2.2982756945349973e-157
sqrt0122 sqrt -7.1145453001139502e-322 2.9561379244703735e-314 -> 1.2157585807480286e-157 1.2157586100077242e-157
sqrt0123 sqrt -4.9963244206801218e-314 -8.4718424423690227e-319 -> 1.8950582312540437e-162 -2.2352459419578971e-157
sqrt0124 sqrt 0.0 7.699553609385195e-318 -> 1.9620848107797476e-159 1.9620848107797476e-159
sqrt0125 sqrt -0.0 3.3900826606499415e-309 -> 4.1170879639922327e-155 4.1170879639922327e-155
sqrt0126 sqrt 0.0 -9.8907989772250828e-319 -> 7.032353438652342e-160 -7.032353438652342e-160
sqrt0127 sqrt -0.0 -1.3722939367590908e-315 -> 2.6194407196566702e-158 -2.6194407196566702e-158
sqrt0128 sqrt 7.9050503334599447e-323 0.0 -> 8.8910349979403099e-162 0.0
sqrt0129 sqrt 1.8623241768349486e-309 -0.0 -> 4.3154654173506579e-155 -0.0
sqrt0130 sqrt -2.665971134499887e-308 0.0 -> 0.0 1.6327801856036491e-154
sqrt0131 sqrt -1.5477066694467245e-310 -0.0 -> 0.0 -1.2440685951533077e-155
-- inputs whose absolute value overflows
sqrt0140 sqrt 1.6999999999999999e+308 -1.6999999999999999e+308 -> 1.4325088230154573e+154 -5.9336458271212207e+153
sqrt0141 sqrt -1.797e+308 -9.9999999999999999e+306 -> 3.7284476432057307e+152 -1.3410406899802901e+154
-- Additional real values (mpmath)
sqrt0150 sqrt 1.7976931348623157e+308 0.0 -> 1.3407807929942596355e+154 0.0
sqrt0151 sqrt 2.2250738585072014e-308 0.0 -> 1.4916681462400413487e-154 0.0
sqrt0152 sqrt 5e-324 0.0 -> 2.2227587494850774834e-162 0.0
-- special values
sqrt1000 sqrt 0.0 0.0 -> 0.0 0.0
sqrt1001 sqrt -0.0 0.0 -> 0.0 0.0
sqrt1002 sqrt 0.0 inf -> inf inf
sqrt1003 sqrt 2.3 inf -> inf inf
sqrt1004 sqrt inf inf -> inf inf
sqrt1005 sqrt -0.0 inf -> inf inf
sqrt1006 sqrt -2.3 inf -> inf inf
sqrt1007 sqrt -inf inf -> inf inf
sqrt1008 sqrt nan inf -> inf inf
sqrt1009 sqrt 0.0 nan -> nan nan
sqrt1010 sqrt 2.3 nan -> nan nan
sqrt1011 sqrt -0.0 nan -> nan nan
sqrt1012 sqrt -2.3 nan -> nan nan
sqrt1013 sqrt -inf 0.0 -> 0.0 inf
sqrt1014 sqrt -inf 2.3 -> 0.0 inf
sqrt1015 sqrt inf 0.0 -> inf 0.0
sqrt1016 sqrt inf 2.3 -> inf 0.0
sqrt1017 sqrt -inf nan -> nan inf ignore-imag-sign
sqrt1018 sqrt inf nan -> inf nan
sqrt1019 sqrt nan 0.0 -> nan nan
sqrt1020 sqrt nan 2.3 -> nan nan
sqrt1021 sqrt nan nan -> nan nan
sqrt1022 sqrt 0.0 -0.0 -> 0.0 -0.0
sqrt1023 sqrt -0.0 -0.0 -> 0.0 -0.0
sqrt1024 sqrt 0.0 -inf -> inf -inf
sqrt1025 sqrt 2.3 -inf -> inf -inf
sqrt1026 sqrt inf -inf -> inf -inf
sqrt1027 sqrt -0.0 -inf -> inf -inf
sqrt1028 sqrt -2.3 -inf -> inf -inf
sqrt1029 sqrt -inf -inf -> inf -inf
sqrt1030 sqrt nan -inf -> inf -inf
sqrt1031 sqrt -inf -0.0 -> 0.0 -inf
sqrt1032 sqrt -inf -2.3 -> 0.0 -inf
sqrt1033 sqrt inf -0.0 -> inf -0.0
sqrt1034 sqrt inf -2.3 -> inf -0.0
sqrt1035 sqrt nan -0.0 -> nan nan
sqrt1036 sqrt nan -2.3 -> nan nan
-- For exp, cosh, sinh, tanh we limit tests to arguments whose
-- imaginary part is less than 10 in absolute value: most math
-- libraries have poor accuracy for (real) sine and cosine for
-- large arguments, and the accuracy of these complex functions
-- suffer correspondingly.
--
-- Similarly, for cos, sin and tan we limit tests to arguments
-- with relatively small real part.
-------------------------------
-- exp: Exponential function --
-------------------------------
-- zeros
exp0000 exp 0.0 0.0 -> 1.0 0.0
exp0001 exp 0.0 -0.0 -> 1.0 -0.0
exp0002 exp -0.0 0.0 -> 1.0 0.0
exp0003 exp -0.0 -0.0 -> 1.0 -0.0
-- random inputs
exp0004 exp -17.957359009564684 -1.108613895795274 -> 7.0869292576226611e-09 -1.4225929202377833e-08
exp0005 exp -1.4456149663368642e-15 -0.75359817331772239 -> 0.72923148323917997 -0.68426708517419033
exp0006 exp -0.76008654883512661 -0.46657235480105019 -> 0.41764393109928666 -0.21035108396792854
exp0007 exp -5.7071614697735731 -2.3744161818115816e-11 -> 0.0033220890242068356 -7.8880219364953578e-14
exp0008 exp -0.4653981327927097 -5.2236706667445587e-21 -> 0.62788507378216663 -3.2798648420026468e-21
exp0009 exp -3.2444565242295518 1.1535625304243959 -> 0.015799936931457641 0.035644950380024749
exp0010 exp -3.0651456337977727 0.87765086532391878 -> 0.029805595629855953 0.035882775180855669
exp0011 exp -0.11080823753233926 0.96486386300873106 -> 0.50979112534376314 0.73575512419561562
exp0012 exp -2.5629722598928648 0.019636235754708079 -> 0.077060452853917397 0.0015133717341137684
exp0013 exp -3.3201709957983357e-10 1.2684017344487268 -> 0.29780699855434889 0.95462610007689186
exp0014 exp 0.88767276057993272 -0.18953422986895557 -> 2.3859624049858095 -0.45771559132044426
exp0015 exp 1.5738333486794742 -2.2576803075544328e-11 -> 4.8251091132458654 -1.0893553826776623e-10
exp0016 exp 1.6408702341813795 -1.438879484380837 -> 0.6786733590689048 -5.1148284173168825
exp0017 exp 1.820279424202033 -0.020812040370785722 -> 6.1722462896420902 -0.1284755888435051
exp0018 exp 1.7273965735945873 -0.61140621328954947 -> 4.6067931898799976 -3.2294267694441308
exp0019 exp 2.5606034306862995 0.098153136008435504 -> 12.881325889966629 1.2684184812864494
exp0020 exp 10.280368619483029 3.4564622559748535 -> -27721.283321551502 -9028.9663215568835
exp0021 exp 1.104007405129741e-155 0.21258803067317278 -> 0.97748813933531764 0.21099037290544478
exp0022 exp 0.027364777809295172 0.00059226603500623363 -> 1.0277424518451876 0.0006086970181346579
exp0023 exp 0.94356313429255245 3.418530463518592 -> -2.4712285695346194 -0.70242654900218349
-- cases where exp(z) representable, exp(z.real) not
exp0030 exp 710.0 0.78500000000000003 -> 1.5803016909637158e+308 1.5790437551806911e+308
exp0031 exp 710.0 -0.78500000000000003 -> 1.5803016909637158e+308 -1.5790437551806911e+308
-- values for which exp(x) is subnormal, or underflows to 0
exp0040 exp -735.0 0.78500000000000003 -> 4.3976783136329355e-320 4.3942198541120468e-320
exp0041 exp -735.0 -2.3559999999999999 -> -4.3952079854037293e-320 -4.396690182341253e-320
exp0042 exp -745.0 0.0 -> 4.9406564584124654e-324 0.0
exp0043 exp -745.0 0.7 -> 0.0 0.0
exp0044 exp -745.0 2.1 -> -0.0 0.0
exp0045 exp -745.0 3.7 -> -0.0 -0.0
exp0046 exp -745.0 5.3 -> 0.0 -0.0
-- values for which exp(z) overflows
exp0050 exp 710.0 0.0 -> inf 0.0 overflow
exp0051 exp 711.0 0.7 -> inf inf overflow
exp0052 exp 710.0 1.5 -> 1.5802653829857376e+307 inf overflow
exp0053 exp 710.0 1.6 -> -6.5231579995501372e+306 inf overflow
exp0054 exp 710.0 2.8 -> -inf 7.4836177417448528e+307 overflow
-- Additional real values (mpmath)
exp0070 exp 1e-08 0.0 -> 1.00000001000000005 0.0
exp0071 exp 0.0003 0.0 -> 1.0003000450045003375 0.0
exp0072 exp 0.2 0.0 -> 1.2214027581601698475 0.0
exp0073 exp 1.0 0.0 -> 2.7182818284590452354 0.0
exp0074 exp -1e-08 0.0 -> 0.99999999000000005 0.0
exp0075 exp -0.0003 0.0 -> 0.99970004499550033751 0.0
exp0076 exp -1.0 0.0 -> 0.3678794411714423216 0.0
exp0077 exp 2.220446049250313e-16 0.0 -> 1.000000000000000222 0.0
exp0078 exp -1.1102230246251565e-16 0.0 -> 0.99999999999999988898 0.0
exp0079 exp 2.302585092994046 0.0 -> 10.000000000000002171 0.0
exp0080 exp -2.302585092994046 0.0 -> 0.099999999999999978292 0.0
exp0081 exp 709.7827 0.0 -> 1.7976699566638014654e+308 0.0
-- special values
exp1000 exp 0.0 0.0 -> 1.0 0.0
exp1001 exp -0.0 0.0 -> 1.0 0.0
exp1002 exp 0.0 inf -> nan nan invalid
exp1003 exp 2.3 inf -> nan nan invalid
exp1004 exp -0.0 inf -> nan nan invalid
exp1005 exp -2.3 inf -> nan nan invalid
exp1006 exp 0.0 nan -> nan nan
exp1007 exp 2.3 nan -> nan nan
exp1008 exp -0.0 nan -> nan nan
exp1009 exp -2.3 nan -> nan nan
exp1010 exp -inf 0.0 -> 0.0 0.0
exp1011 exp -inf 1.4 -> 0.0 0.0
exp1012 exp -inf 2.8 -> -0.0 0.0
exp1013 exp -inf 4.2 -> -0.0 -0.0
exp1014 exp -inf 5.6 -> 0.0 -0.0
exp1015 exp -inf 7.0 -> 0.0 0.0
exp1016 exp inf 0.0 -> inf 0.0
exp1017 exp inf 1.4 -> inf inf
exp1018 exp inf 2.8 -> -inf inf
exp1019 exp inf 4.2 -> -inf -inf
exp1020 exp inf 5.6 -> inf -inf
exp1021 exp inf 7.0 -> inf inf
exp1022 exp -inf inf -> 0.0 0.0 ignore-real-sign ignore-imag-sign
exp1023 exp inf inf -> inf nan invalid ignore-real-sign
exp1024 exp -inf nan -> 0.0 0.0 ignore-real-sign ignore-imag-sign
exp1025 exp inf nan -> inf nan ignore-real-sign
exp1026 exp nan 0.0 -> nan 0.0
exp1027 exp nan 2.3 -> nan nan
exp1028 exp nan inf -> nan nan
exp1029 exp nan nan -> nan nan
exp1030 exp 0.0 -0.0 -> 1.0 -0.0
exp1031 exp -0.0 -0.0 -> 1.0 -0.0
exp1032 exp 0.0 -inf -> nan nan invalid
exp1033 exp 2.3 -inf -> nan nan invalid
exp1034 exp -0.0 -inf -> nan nan invalid
exp1035 exp -2.3 -inf -> nan nan invalid
exp1036 exp -inf -0.0 -> 0.0 -0.0
exp1037 exp -inf -1.4 -> 0.0 -0.0
exp1038 exp -inf -2.8 -> -0.0 -0.0
exp1039 exp -inf -4.2 -> -0.0 0.0
exp1040 exp -inf -5.6 -> 0.0 0.0
exp1041 exp -inf -7.0 -> 0.0 -0.0
exp1042 exp inf -0.0 -> inf -0.0
exp1043 exp inf -1.4 -> inf -inf
exp1044 exp inf -2.8 -> -inf -inf
exp1045 exp inf -4.2 -> -inf inf
exp1046 exp inf -5.6 -> inf inf
exp1047 exp inf -7.0 -> inf -inf
exp1048 exp -inf -inf -> 0.0 0.0 ignore-real-sign ignore-imag-sign
exp1049 exp inf -inf -> inf nan invalid ignore-real-sign
exp1050 exp nan -0.0 -> nan -0.0
exp1051 exp nan -2.3 -> nan nan
exp1052 exp nan -inf -> nan nan
-----------------------------
-- cosh: Hyperbolic Cosine --
-----------------------------
-- zeros
cosh0000 cosh 0.0 0.0 -> 1.0 0.0
cosh0001 cosh 0.0 -0.0 -> 1.0 -0.0
cosh0002 cosh -0.0 0.0 -> 1.0 -0.0
cosh0003 cosh -0.0 -0.0 -> 1.0 0.0
-- random inputs
cosh0004 cosh -0.85395264297414253 -8.8553756148671958 -> -1.1684340348021185 0.51842195359787435
cosh0005 cosh -19.584904237211223 -0.066582627994906177 -> 159816812.23336992 10656776.050406246
cosh0006 cosh -0.11072618401130772 -1.484820215073247 -> 0.086397164744949503 0.11054275637717284
cosh0007 cosh -3.4764840250681752 -0.48440348288275276 -> 14.325931955190844 7.5242053548737955
cosh0008 cosh -0.52047063604524602 -0.3603805382775585 -> 1.0653940354683802 0.19193293606252473
cosh0009 cosh -1.39518962975995 0.0074738604700702906 -> 2.1417031027235969 -0.01415518712296308
cosh0010 cosh -0.37107064757653541 0.14728085307856609 -> 1.0580601496776991 -0.055712531964568587
cosh0011 cosh -5.8470200958739653 4.0021722388336292 -> -112.86220667618285 131.24734033545013
cosh0012 cosh -0.1700261444851883 0.97167540135354513 -> 0.57208748253577946 -0.1410904820240203
cosh0013 cosh -0.44042397902648783 1.0904791964139742 -> 0.50760322393058133 -0.40333966652010816
cosh0014 cosh 0.052267552491867299 -3.8889011430644174 -> -0.73452303414639297 0.035540704833537134
cosh0015 cosh 0.98000764177127453 -1.2548829247784097 -> 0.47220747341416142 -1.0879421432180316
cosh0016 cosh 0.083594701222644008 -0.88847899930181284 -> 0.63279782419312613 -0.064954566816002285
cosh0017 cosh 1.38173531783776 -0.43185040816732229 -> 1.9221663374671647 -0.78073830858849347
cosh0018 cosh 0.57315681120148465 -0.22255760951027942 -> 1.1399733125173004 -0.1335512343605956
cosh0019 cosh 1.8882512333062347 4.5024932182383797 -> -0.7041602065362691 -3.1573822131964615
cosh0020 cosh 0.5618219206858317 0.92620452129575348 -> 0.69822380405378381 0.47309067471054522
cosh0021 cosh 0.54361442847062591 0.64176483583018462 -> 0.92234462074193491 0.34167906495845501
cosh0022 cosh 0.0014777403107920331 1.3682028122677661 -> 0.2012106963899549 0.001447518137863219
cosh0023 cosh 2.218885944363501 2.0015727395883687 -> -1.94294321081968 4.1290269176083196
-- large real part
cosh0030 cosh 710.5 2.3519999999999999 -> -1.2967465239355998e+308 1.3076707908857333e+308
cosh0031 cosh -710.5 0.69999999999999996 -> 1.4085466381392499e+308 -1.1864024666450239e+308
-- Additional real values (mpmath)
cosh0050 cosh 1e-150 0.0 -> 1.0 0.0
cosh0051 cosh 1e-18 0.0 -> 1.0 0.0
cosh0052 cosh 1e-09 0.0 -> 1.0000000000000000005 0.0
cosh0053 cosh 0.0003 0.0 -> 1.0000000450000003375 0.0
cosh0054 cosh 0.2 0.0 -> 1.0200667556190758485 0.0
cosh0055 cosh 1.0 0.0 -> 1.5430806348152437785 0.0
cosh0056 cosh -1e-18 0.0 -> 1.0 -0.0
cosh0057 cosh -0.0003 0.0 -> 1.0000000450000003375 -0.0
cosh0058 cosh -1.0 0.0 -> 1.5430806348152437785 -0.0
cosh0059 cosh 1.3169578969248168 0.0 -> 2.0000000000000001504 0.0
cosh0060 cosh -1.3169578969248168 0.0 -> 2.0000000000000001504 -0.0
cosh0061 cosh 17.328679513998633 0.0 -> 16777216.000000021938 0.0
cosh0062 cosh 18.714973875118524 0.0 -> 67108864.000000043662 0.0
cosh0063 cosh 709.7827 0.0 -> 8.9883497833190073272e+307 0.0
cosh0064 cosh -709.7827 0.0 -> 8.9883497833190073272e+307 -0.0
-- special values
cosh1000 cosh 0.0 0.0 -> 1.0 0.0
cosh1001 cosh 0.0 inf -> nan 0.0 invalid ignore-imag-sign
cosh1002 cosh 0.0 nan -> nan 0.0 ignore-imag-sign
cosh1003 cosh 2.3 inf -> nan nan invalid
cosh1004 cosh 2.3 nan -> nan nan
cosh1005 cosh inf 0.0 -> inf 0.0
cosh1006 cosh inf 1.4 -> inf inf
cosh1007 cosh inf 2.8 -> -inf inf
cosh1008 cosh inf 4.2 -> -inf -inf
cosh1009 cosh inf 5.6 -> inf -inf
cosh1010 cosh inf 7.0 -> inf inf
cosh1011 cosh inf inf -> inf nan invalid ignore-real-sign
cosh1012 cosh inf nan -> inf nan
cosh1013 cosh nan 0.0 -> nan 0.0 ignore-imag-sign
cosh1014 cosh nan 2.3 -> nan nan
cosh1015 cosh nan inf -> nan nan
cosh1016 cosh nan nan -> nan nan
cosh1017 cosh 0.0 -0.0 -> 1.0 -0.0
cosh1018 cosh 0.0 -inf -> nan 0.0 invalid ignore-imag-sign
cosh1019 cosh 2.3 -inf -> nan nan invalid
cosh1020 cosh inf -0.0 -> inf -0.0
cosh1021 cosh inf -1.4 -> inf -inf
cosh1022 cosh inf -2.8 -> -inf -inf
cosh1023 cosh inf -4.2 -> -inf inf
cosh1024 cosh inf -5.6 -> inf inf
cosh1025 cosh inf -7.0 -> inf -inf
cosh1026 cosh inf -inf -> inf nan invalid ignore-real-sign
cosh1027 cosh nan -0.0 -> nan 0.0 ignore-imag-sign
cosh1028 cosh nan -2.3 -> nan nan
cosh1029 cosh nan -inf -> nan nan
cosh1030 cosh -0.0 -0.0 -> 1.0 0.0
cosh1031 cosh -0.0 -inf -> nan 0.0 invalid ignore-imag-sign
cosh1032 cosh -0.0 nan -> nan 0.0 ignore-imag-sign
cosh1033 cosh -2.3 -inf -> nan nan invalid
cosh1034 cosh -2.3 nan -> nan nan
cosh1035 cosh -inf -0.0 -> inf 0.0
cosh1036 cosh -inf -1.4 -> inf inf
cosh1037 cosh -inf -2.8 -> -inf inf
cosh1038 cosh -inf -4.2 -> -inf -inf
cosh1039 cosh -inf -5.6 -> inf -inf
cosh1040 cosh -inf -7.0 -> inf inf
cosh1041 cosh -inf -inf -> inf nan invalid ignore-real-sign
cosh1042 cosh -inf nan -> inf nan
cosh1043 cosh -0.0 0.0 -> 1.0 -0.0
cosh1044 cosh -0.0 inf -> nan 0.0 invalid ignore-imag-sign
cosh1045 cosh -2.3 inf -> nan nan invalid
cosh1046 cosh -inf 0.0 -> inf -0.0
cosh1047 cosh -inf 1.4 -> inf -inf
cosh1048 cosh -inf 2.8 -> -inf -inf
cosh1049 cosh -inf 4.2 -> -inf inf
cosh1050 cosh -inf 5.6 -> inf inf
cosh1051 cosh -inf 7.0 -> inf -inf
cosh1052 cosh -inf inf -> inf nan invalid ignore-real-sign
---------------------------
-- sinh: Hyperbolic Sine --
---------------------------
-- zeros
sinh0000 sinh 0.0 0.0 -> 0.0 0.0
sinh0001 sinh 0.0 -0.0 -> 0.0 -0.0
sinh0002 sinh -0.0 0.0 -> -0.0 0.0
sinh0003 sinh -0.0 -0.0 -> -0.0 -0.0
-- random inputs
sinh0004 sinh -17.282588091462742 -0.38187948694103546 -> -14867386.857248396 -5970648.6553516639
sinh0005 sinh -343.91971203143208 -5.0172868877771525e-22 -> -1.1518691776521735e+149 -5.7792581214689021e+127
sinh0006 sinh -14.178122253300922 -1.9387157579351293 -> 258440.37909034826 -670452.58500946441
sinh0007 sinh -1.0343810581686239 -1.0970235266369905 -> -0.56070858278092739 -1.4098883258046697
sinh0008 sinh -0.066126561416368204 -0.070461584169961872 -> -0.066010558700938124 -0.070557276738637542
sinh0009 sinh -0.37630149150308484 3.3621734692162173 -> 0.37591118119332617 -0.23447115926369383
sinh0010 sinh -0.049941960978670055 0.40323767020414625 -> -0.045955482136329009 0.3928878494430646
sinh0011 sinh -16.647852603903715 0.0026852219129082098 -> -8492566.5739382561 22804.480671133562
sinh0012 sinh -1.476625314303694 0.89473773116683386 -> -1.2982943334382224 1.7966593367791204
sinh0013 sinh -422.36429577556913 0.10366634502307912 -> -1.3400321008920044e+183 1.3941600948045599e+182
sinh0014 sinh 0.09108340745641981 -0.40408227416070353 -> 0.083863724802237902 -0.39480716553935602
sinh0015 sinh 2.036064132067386 -2.6831729961386239 -> -3.37621124363175 -1.723868330002817
sinh0016 sinh 2.5616717223063317 -0.0078978498622717767 -> 6.4399415853815869 -0.051472264400722133
sinh0017 sinh 0.336804011985188 -6.5654622971649337 -> 0.32962499307574578 -0.29449170159995197
sinh0018 sinh 0.23774603755649693 -0.92467195799232049 -> 0.14449839490603389 -0.82109449053556793
sinh0019 sinh 0.0011388273541465494 1.9676196882949855 -> -0.00044014605389634999 0.92229398407098806
sinh0020 sinh 3.2443870105663759 0.8054287559616895 -> 8.8702890778527426 9.2610748597042196
sinh0021 sinh 0.040628908857054738 0.098206391190944958 -> 0.04044426841671233 0.098129544739707392
sinh0022 sinh 4.7252283918217696e-30 9.1198155642656697 -> -4.5071980561644404e-30 0.30025730701661713
sinh0023 sinh 0.043713693678420068 0.22512549887532657 -> 0.042624198673416713 0.22344201231217961
-- large real part
sinh0030 sinh 710.5 -2.3999999999999999 -> -1.3579970564885919e+308 -1.24394470907798e+308
sinh0031 sinh -710.5 0.80000000000000004 -> -1.2830671601735164e+308 1.3210954193997678e+308
-- Additional real values (mpmath)
sinh0050 sinh 1e-100 0.0 -> 1.00000000000000002e-100 0.0
sinh0051 sinh 5e-17 0.0 -> 4.9999999999999998955e-17 0.0
sinh0052 sinh 1e-16 0.0 -> 9.999999999999999791e-17 0.0
sinh0053 sinh 3.7e-08 0.0 -> 3.7000000000000008885e-8 0.0
sinh0054 sinh 0.001 0.0 -> 0.0010000001666666750208 0.0
sinh0055 sinh 0.2 0.0 -> 0.20133600254109399895 0.0
sinh0056 sinh 1.0 0.0 -> 1.1752011936438014569 0.0
sinh0057 sinh -3.7e-08 0.0 -> -3.7000000000000008885e-8 0.0
sinh0058 sinh -0.001 0.0 -> -0.0010000001666666750208 0.0
sinh0059 sinh -1.0 0.0 -> -1.1752011936438014569 0.0
sinh0060 sinh 1.4436354751788103 0.0 -> 1.9999999999999999078 0.0
sinh0061 sinh -1.4436354751788103 0.0 -> -1.9999999999999999078 0.0
sinh0062 sinh 17.328679513998633 0.0 -> 16777215.999999992136 0.0
sinh0063 sinh 18.714973875118524 0.0 -> 67108864.000000036211 0.0
sinh0064 sinh 709.7827 0.0 -> 8.9883497833190073272e+307 0.0
sinh0065 sinh -709.7827 0.0 -> -8.9883497833190073272e+307 0.0
-- special values
sinh1000 sinh 0.0 0.0 -> 0.0 0.0
sinh1001 sinh 0.0 inf -> 0.0 nan invalid ignore-real-sign
sinh1002 sinh 0.0 nan -> 0.0 nan ignore-real-sign
sinh1003 sinh 2.3 inf -> nan nan invalid
sinh1004 sinh 2.3 nan -> nan nan
sinh1005 sinh inf 0.0 -> inf 0.0
sinh1006 sinh inf 1.4 -> inf inf
sinh1007 sinh inf 2.8 -> -inf inf
sinh1008 sinh inf 4.2 -> -inf -inf
sinh1009 sinh inf 5.6 -> inf -inf
sinh1010 sinh inf 7.0 -> inf inf
sinh1011 sinh inf inf -> inf nan invalid ignore-real-sign
sinh1012 sinh inf nan -> inf nan ignore-real-sign
sinh1013 sinh nan 0.0 -> nan 0.0
sinh1014 sinh nan 2.3 -> nan nan
sinh1015 sinh nan inf -> nan nan
sinh1016 sinh nan nan -> nan nan
sinh1017 sinh 0.0 -0.0 -> 0.0 -0.0
sinh1018 sinh 0.0 -inf -> 0.0 nan invalid ignore-real-sign
sinh1019 sinh 2.3 -inf -> nan nan invalid
sinh1020 sinh inf -0.0 -> inf -0.0
sinh1021 sinh inf -1.4 -> inf -inf
sinh1022 sinh inf -2.8 -> -inf -inf
sinh1023 sinh inf -4.2 -> -inf inf
sinh1024 sinh inf -5.6 -> inf inf
sinh1025 sinh inf -7.0 -> inf -inf
sinh1026 sinh inf -inf -> inf nan invalid ignore-real-sign
sinh1027 sinh nan -0.0 -> nan -0.0
sinh1028 sinh nan -2.3 -> nan nan
sinh1029 sinh nan -inf -> nan nan
sinh1030 sinh -0.0 -0.0 -> -0.0 -0.0
sinh1031 sinh -0.0 -inf -> 0.0 nan invalid ignore-real-sign
sinh1032 sinh -0.0 nan -> 0.0 nan ignore-real-sign
sinh1033 sinh -2.3 -inf -> nan nan invalid
sinh1034 sinh -2.3 nan -> nan nan
sinh1035 sinh -inf -0.0 -> -inf -0.0
sinh1036 sinh -inf -1.4 -> -inf -inf
sinh1037 sinh -inf -2.8 -> inf -inf
sinh1038 sinh -inf -4.2 -> inf inf
sinh1039 sinh -inf -5.6 -> -inf inf
sinh1040 sinh -inf -7.0 -> -inf -inf
sinh1041 sinh -inf -inf -> inf nan invalid ignore-real-sign
sinh1042 sinh -inf nan -> inf nan ignore-real-sign
sinh1043 sinh -0.0 0.0 -> -0.0 0.0
sinh1044 sinh -0.0 inf -> 0.0 nan invalid ignore-real-sign
sinh1045 sinh -2.3 inf -> nan nan invalid
sinh1046 sinh -inf 0.0 -> -inf 0.0
sinh1047 sinh -inf 1.4 -> -inf inf
sinh1048 sinh -inf 2.8 -> inf inf
sinh1049 sinh -inf 4.2 -> inf -inf
sinh1050 sinh -inf 5.6 -> -inf -inf
sinh1051 sinh -inf 7.0 -> -inf inf
sinh1052 sinh -inf inf -> inf nan invalid ignore-real-sign
------------------------------
-- tanh: Hyperbolic Tangent --
------------------------------
-- Disabled test: replaced by test_math.testTanhSign()
-- and test_cmath.testTanhSign()
-- -- zeros
-- tanh0000 tanh 0.0 0.0 -> 0.0 0.0
-- tanh0001 tanh 0.0 -0.0 -> 0.0 -0.0
-- tanh0002 tanh -0.0 0.0 -> -0.0 0.0
-- tanh0003 tanh -0.0 -0.0 -> -0.0 -0.0
-- random inputs
tanh0004 tanh -21.200500450664993 -1.6970729480342996 -> -1.0 1.9241352344849399e-19
tanh0005 tanh -0.34158771504251928 -8.0848504951747131 -> -2.123711225855613 1.2827526782026006
tanh0006 tanh -15.454144725193689 -0.23619582288265617 -> -0.99999999999993283 -3.4336684248260036e-14
tanh0007 tanh -7.6103163119661952 -0.7802748320307008 -> -0.99999999497219438 -4.9064845343755437e-07
tanh0008 tanh -0.15374717235792129 -0.6351086327306138 -> -0.23246081703561869 -0.71083467433910219
tanh0009 tanh -0.49101115474392465 0.09723001264886301 -> -0.45844445715492133 0.077191158541805888
tanh0010 tanh -0.10690612157664491 2.861612800856395 -> -0.11519761626257358 -0.28400488355647507
tanh0011 tanh -0.91505774192066702 1.5431174597727007 -> -1.381109893068114 0.025160819663709356
tanh0012 tanh -0.057433367093792223 0.35491159541246459 -> -0.065220499046696953 0.36921788332369498
tanh0013 tanh -1.3540418621233514 0.18969415642242535 -> -0.88235642861151387 0.043764069984411721
tanh0014 tanh 0.94864783961003529 -0.11333689578867717 -> 0.74348401861861368 -0.051271042543855221
tanh0015 tanh 1.9591698133845488 -0.0029654444904578339 -> 0.9610270776968135 -0.00022664240049212933
tanh0016 tanh 1.0949715796669197 -0.24706642853984456 -> 0.81636574501369386 -0.087767436914149954
tanh0017 tanh 5770428.2113731047 -3.7160580339833165 -> 1.0 -0.0
tanh0018 tanh 1.5576782321399629 -1.0357943787966468 -> 1.0403002384895388 -0.081126347894671463
tanh0019 tanh 0.62378536230552961 2.3471393579560216 -> 0.85582499238960363 -0.53569473646842869
tanh0020 tanh 17.400628602508025 9.3987059533841979 -> 0.99999999999999845 -8.0175867720530832e-17
tanh0021 tanh 0.15026177509871896 0.50630349159505472 -> 0.19367536571827768 0.53849847858853661
tanh0022 tanh 0.57433977530711167 1.0071604546265627 -> 1.0857848159262844 0.69139213955872214
tanh0023 tanh 0.16291181500449456 0.006972810241567544 -> 0.16149335907551157 0.0067910772903467817
-- large real part
tanh0030 tanh 710 0.13 -> 1.0 0.0
tanh0031 tanh -711 7.4000000000000004 -> -1.0 0.0
tanh0032 tanh 1000 -2.3199999999999998 -> 1.0 0.0
tanh0033 tanh -1.0000000000000001e+300 -9.6699999999999999 -> -1.0 -0.0
-- Additional real values (mpmath)
tanh0050 tanh 1e-100 0.0 -> 1.00000000000000002e-100 0.0
tanh0051 tanh 5e-17 0.0 -> 4.9999999999999998955e-17 0.0
tanh0052 tanh 1e-16 0.0 -> 9.999999999999999791e-17 0.0
tanh0053 tanh 3.7e-08 0.0 -> 3.6999999999999983559e-8 0.0
tanh0054 tanh 0.001 0.0 -> 0.00099999966666680002076 0.0
tanh0055 tanh 0.2 0.0 -> 0.19737532022490401141 0.0
tanh0056 tanh 1.0 0.0 -> 0.76159415595576488812 0.0
tanh0057 tanh -3.7e-08 0.0 -> -3.6999999999999983559e-8 0.0
tanh0058 tanh -0.001 0.0 -> -0.00099999966666680002076 0.0
tanh0059 tanh -1.0 0.0 -> -0.76159415595576488812 0.0
tanh0060 tanh 0.5493061443340549 0.0 -> 0.50000000000000003402 0.0
tanh0061 tanh -0.5493061443340549 0.0 -> -0.50000000000000003402 0.0
tanh0062 tanh 17.328679513998633 0.0 -> 0.99999999999999822364 0.0
tanh0063 tanh 18.714973875118524 0.0 -> 0.99999999999999988898 0.0
tanh0064 tanh 711 0.0 -> 1.0 0.0
tanh0065 tanh 1.797e+308 0.0 -> 1.0 0.0
--special values
tanh1000 tanh 0.0 0.0 -> 0.0 0.0
tanh1001 tanh 0.0 inf -> nan nan invalid
tanh1002 tanh 2.3 inf -> nan nan invalid
tanh1003 tanh 0.0 nan -> nan nan
tanh1004 tanh 2.3 nan -> nan nan
tanh1005 tanh inf 0.0 -> 1.0 0.0
tanh1006 tanh inf 0.7 -> 1.0 0.0
tanh1007 tanh inf 1.4 -> 1.0 0.0
tanh1008 tanh inf 2.1 -> 1.0 -0.0
tanh1009 tanh inf 2.8 -> 1.0 -0.0
tanh1010 tanh inf 3.5 -> 1.0 0.0
tanh1011 tanh inf inf -> 1.0 0.0 ignore-imag-sign
tanh1012 tanh inf nan -> 1.0 0.0 ignore-imag-sign
tanh1013 tanh nan 0.0 -> nan 0.0
tanh1014 tanh nan 2.3 -> nan nan
tanh1015 tanh nan inf -> nan nan
tanh1016 tanh nan nan -> nan nan
tanh1017 tanh 0.0 -0.0 -> 0.0 -0.0
tanh1018 tanh 0.0 -inf -> nan nan invalid
tanh1019 tanh 2.3 -inf -> nan nan invalid
tanh1020 tanh inf -0.0 -> 1.0 -0.0
tanh1021 tanh inf -0.7 -> 1.0 -0.0
tanh1022 tanh inf -1.4 -> 1.0 -0.0
tanh1023 tanh inf -2.1 -> 1.0 0.0
tanh1024 tanh inf -2.8 -> 1.0 0.0
tanh1025 tanh inf -3.5 -> 1.0 -0.0
tanh1026 tanh inf -inf -> 1.0 0.0 ignore-imag-sign
tanh1027 tanh nan -0.0 -> nan -0.0
tanh1028 tanh nan -2.3 -> nan nan
tanh1029 tanh nan -inf -> nan nan
tanh1030 tanh -0.0 -0.0 -> -0.0 -0.0
tanh1031 tanh -0.0 -inf -> nan nan invalid
tanh1032 tanh -2.3 -inf -> nan nan invalid
tanh1033 tanh -0.0 nan -> nan nan
tanh1034 tanh -2.3 nan -> nan nan
tanh1035 tanh -inf -0.0 -> -1.0 -0.0
tanh1036 tanh -inf -0.7 -> -1.0 -0.0
tanh1037 tanh -inf -1.4 -> -1.0 -0.0
tanh1038 tanh -inf -2.1 -> -1.0 0.0
tanh1039 tanh -inf -2.8 -> -1.0 0.0
tanh1040 tanh -inf -3.5 -> -1.0 -0.0
tanh1041 tanh -inf -inf -> -1.0 0.0 ignore-imag-sign
tanh1042 tanh -inf nan -> -1.0 0.0 ignore-imag-sign
tanh1043 tanh -0.0 0.0 -> -0.0 0.0
tanh1044 tanh -0.0 inf -> nan nan invalid
tanh1045 tanh -2.3 inf -> nan nan invalid
tanh1046 tanh -inf 0.0 -> -1.0 0.0
tanh1047 tanh -inf 0.7 -> -1.0 0.0
tanh1048 tanh -inf 1.4 -> -1.0 0.0
tanh1049 tanh -inf 2.1 -> -1.0 -0.0
tanh1050 tanh -inf 2.8 -> -1.0 -0.0
tanh1051 tanh -inf 3.5 -> -1.0 0.0
tanh1052 tanh -inf inf -> -1.0 0.0 ignore-imag-sign
-----------------
-- cos: Cosine --
-----------------
-- zeros
cos0000 cos 0.0 0.0 -> 1.0 -0.0
cos0001 cos 0.0 -0.0 -> 1.0 0.0
cos0002 cos -0.0 0.0 -> 1.0 0.0
cos0003 cos -0.0 -0.0 -> 1.0 -0.0
-- random inputs
cos0004 cos -2.0689194692073034 -0.0016802181751734313 -> -0.47777827208561469 -0.0014760401501695971
cos0005 cos -0.4209627318177977 -1.8238516774258027 -> 2.9010402201444108 -1.2329207042329617
cos0006 cos -1.9402181630694557 -2.9751857392891217 -> -3.5465459297970985 -9.1119163586282248
cos0007 cos -3.3118320290191616 -0.87871302909286142 -> -1.3911528636565498 0.16878141517391701
cos0008 cos -4.9540404623376872 -0.57949232239026827 -> 0.28062445586552065 0.59467861308508008
cos0009 cos -0.45374584316245026 1.3950283448373935 -> 1.9247665574290578 0.83004572204761107
cos0010 cos -0.42578172040176843 1.2715881615413049 -> 1.7517161459489148 0.67863902697363332
cos0011 cos -0.13862985354300136 0.43587635877670328 -> 1.0859880290361912 0.062157548146672272
cos0012 cos -0.11073221308966584 9.9384082307326475e-15 -> 0.99387545040722947 1.0982543264065479e-15
cos0013 cos -1.5027633662054623e-07 0.0069668060249955498 -> 1.0000242682912412 1.0469545565660995e-09
cos0014 cos 4.9728645490503052 -0.00027479808860952822 -> 0.25754011731975501 -0.00026552849549083186
cos0015 cos 7.81969303486719 -0.79621523445878783 -> 0.045734882501585063 0.88253139933082991
cos0016 cos 0.13272421880766716 -0.74668445308718201 -> 1.2806012244432847 0.10825373267437005
cos0017 cos 4.2396521985973274 -2.2178848380884881 -> -2.1165117057056855 -4.0416492444641401
cos0018 cos 1.1622206624927296 -0.50400115461197081 -> 0.44884072613370379 0.4823469915034318
cos0019 cos 1.628772864620884e-08 0.58205705428979282 -> 1.1742319995791435 -1.0024839481956604e-08
cos0020 cos 2.6385212606111241 2.9886107100937296 -> -8.7209475927161417 -4.7748352107199796
cos0021 cos 4.8048375263775256 0.0062248852898515658 -> 0.092318702015846243 0.0061983430422306142
cos0022 cos 7.9914515433858515 0.71659966615501436 -> -0.17375439906936566 -0.77217043527294582
cos0023 cos 0.45124351152540226 1.6992693993812158 -> 2.543477948972237 -1.1528193694875477
-- Additional real values (mpmath)
cos0050 cos 1e-150 0.0 -> 1.0 -0.0
cos0051 cos 1e-18 0.0 -> 1.0 -0.0
cos0052 cos 1e-09 0.0 -> 0.9999999999999999995 -0.0
cos0053 cos 0.0003 0.0 -> 0.9999999550000003375 -0.0
cos0054 cos 0.2 0.0 -> 0.98006657784124162892 -0.0
cos0055 cos 1.0 0.0 -> 0.5403023058681397174 -0.0
cos0056 cos -1e-18 0.0 -> 1.0 0.0
cos0057 cos -0.0003 0.0 -> 0.9999999550000003375 0.0
cos0058 cos -1.0 0.0 -> 0.5403023058681397174 0.0
cos0059 cos 1.0471975511965976 0.0 -> 0.50000000000000009945 -0.0
cos0060 cos 2.5707963267948966 0.0 -> -0.84147098480789647357 -0.0
cos0061 cos -2.5707963267948966 0.0 -> -0.84147098480789647357 0.0
cos0062 cos 7.225663103256523 0.0 -> 0.58778525229247407559 -0.0
cos0063 cos -8.79645943005142 0.0 -> -0.80901699437494722255 0.0
-- special values
cos1000 cos -0.0 0.0 -> 1.0 0.0
cos1001 cos -inf 0.0 -> nan 0.0 invalid ignore-imag-sign
cos1002 cos nan 0.0 -> nan 0.0 ignore-imag-sign
cos1003 cos -inf 2.2999999999999998 -> nan nan invalid
cos1004 cos nan 2.2999999999999998 -> nan nan
cos1005 cos -0.0 inf -> inf 0.0
cos1006 cos -1.3999999999999999 inf -> inf inf
cos1007 cos -2.7999999999999998 inf -> -inf inf
cos1008 cos -4.2000000000000002 inf -> -inf -inf
cos1009 cos -5.5999999999999996 inf -> inf -inf
cos1010 cos -7.0 inf -> inf inf
cos1011 cos -inf inf -> inf nan invalid ignore-real-sign
cos1012 cos nan inf -> inf nan
cos1013 cos -0.0 nan -> nan 0.0 ignore-imag-sign
cos1014 cos -2.2999999999999998 nan -> nan nan
cos1015 cos -inf nan -> nan nan
cos1016 cos nan nan -> nan nan
cos1017 cos 0.0 0.0 -> 1.0 -0.0
cos1018 cos inf 0.0 -> nan 0.0 invalid ignore-imag-sign
cos1019 cos inf 2.2999999999999998 -> nan nan invalid
cos1020 cos 0.0 inf -> inf -0.0
cos1021 cos 1.3999999999999999 inf -> inf -inf
cos1022 cos 2.7999999999999998 inf -> -inf -inf
cos1023 cos 4.2000000000000002 inf -> -inf inf
cos1024 cos 5.5999999999999996 inf -> inf inf
cos1025 cos 7.0 inf -> inf -inf
cos1026 cos inf inf -> inf nan invalid ignore-real-sign
cos1027 cos 0.0 nan -> nan 0.0 ignore-imag-sign
cos1028 cos 2.2999999999999998 nan -> nan nan
cos1029 cos inf nan -> nan nan
cos1030 cos 0.0 -0.0 -> 1.0 0.0
cos1031 cos inf -0.0 -> nan 0.0 invalid ignore-imag-sign
cos1032 cos nan -0.0 -> nan 0.0 ignore-imag-sign
cos1033 cos inf -2.2999999999999998 -> nan nan invalid
cos1034 cos nan -2.2999999999999998 -> nan nan
cos1035 cos 0.0 -inf -> inf 0.0
cos1036 cos 1.3999999999999999 -inf -> inf inf
cos1037 cos 2.7999999999999998 -inf -> -inf inf
cos1038 cos 4.2000000000000002 -inf -> -inf -inf
cos1039 cos 5.5999999999999996 -inf -> inf -inf
cos1040 cos 7.0 -inf -> inf inf
cos1041 cos inf -inf -> inf nan invalid ignore-real-sign
cos1042 cos nan -inf -> inf nan
cos1043 cos -0.0 -0.0 -> 1.0 -0.0
cos1044 cos -inf -0.0 -> nan 0.0 invalid ignore-imag-sign
cos1045 cos -inf -2.2999999999999998 -> nan nan invalid
cos1046 cos -0.0 -inf -> inf -0.0
cos1047 cos -1.3999999999999999 -inf -> inf -inf
cos1048 cos -2.7999999999999998 -inf -> -inf -inf
cos1049 cos -4.2000000000000002 -inf -> -inf inf
cos1050 cos -5.5999999999999996 -inf -> inf inf
cos1051 cos -7.0 -inf -> inf -inf
cos1052 cos -inf -inf -> inf nan invalid ignore-real-sign
---------------
-- sin: Sine --
---------------
-- zeros
sin0000 sin 0.0 0.0 -> 0.0 0.0
sin0001 sin 0.0 -0.0 -> 0.0 -0.0
sin0002 sin -0.0 0.0 -> -0.0 0.0
sin0003 sin -0.0 -0.0 -> -0.0 -0.0
-- random inputs
sin0004 sin -0.18691829163163759 -0.74388741985507034 -> -0.2396636733773444 -0.80023231101856751
sin0005 sin -0.45127453702459158 -461.81339920716164 -> -7.9722299331077877e+199 -1.6450205811004628e+200
sin0006 sin -0.47669228345768921 -2.7369936564987514 -> -3.557238022267124 -6.8308030771226615
sin0007 sin -0.31024285525950857 -1.4869219939188296 -> -0.70972676047175209 -1.9985029635426839
sin0008 sin -4.4194573407025608 -1.405999210989288 -> 2.0702480800802685 0.55362250792180601
sin0009 sin -1.7810832046434898e-05 0.0016439555384379083 -> -1.7810856113185261e-05 0.0016439562786668375
sin0010 sin -0.8200017874897666 0.61724876887771929 -> -0.8749078195948865 0.44835295550987758
sin0011 sin -1.4536502806107114 0.63998575534150415 -> -1.2035709929437679 0.080012187489163708
sin0012 sin -2.2653412155506079 0.13172760685583729 -> -0.77502093809190431 -0.084554426868229532
sin0013 sin -0.02613983069491858 0.18404766597776073 -> -0.026580778863127943 0.18502525396735642
sin0014 sin 1.5743065001054617 -0.53125574272642029 -> 1.1444596332092725 0.0019537598099352077
sin0015 sin 7.3833101791283289e-20 -0.16453221324236217 -> 7.4834720674379429e-20 -0.16527555646466915
sin0016 sin 0.34763834641254038 -2.8377416421089565 -> 2.918883541504663 -8.0002718053250224
sin0017 sin 0.077105785180421563 -0.090056027316200674 -> 0.077341973814471304 -0.089909869380524587
sin0018 sin 3.9063227798142329e-17 -0.05954098654295524 -> 3.9132490348956512e-17 -0.059576172859837351
sin0019 sin 0.57333917932544598 8.7785221430594696e-06 -> 0.54244029338302935 7.3747869125301368e-06
sin0020 sin 0.024861722816513169 0.33044620756118515 -> 0.026228801369651 0.3363889671570689
sin0021 sin 1.4342727387492671 0.81361889790284347 -> 1.3370960060947923 0.12336137961387163
sin0022 sin 1.1518087354403725 4.8597235966150558 -> 58.919141989603041 26.237003403758852
sin0023 sin 0.00087773078406649192 34.792379211312095 -> 565548145569.38245 644329685822700.62
-- Additional real values (mpmath)
sin0050 sin 1e-100 0.0 -> 1.00000000000000002e-100 0.0
sin0051 sin 3.7e-08 0.0 -> 3.6999999999999992001e-8 0.0
sin0052 sin 0.001 0.0 -> 0.00099999983333334168748 0.0
sin0053 sin 0.2 0.0 -> 0.19866933079506122634 0.0
sin0054 sin 1.0 0.0 -> 0.84147098480789650665 0.0
sin0055 sin -3.7e-08 0.0 -> -3.6999999999999992001e-8 0.0
sin0056 sin -0.001 0.0 -> -0.00099999983333334168748 0.0
sin0057 sin -1.0 0.0 -> -0.84147098480789650665 0.0
sin0058 sin 0.5235987755982989 0.0 -> 0.50000000000000004642 0.0
sin0059 sin -0.5235987755982989 0.0 -> -0.50000000000000004642 0.0
sin0060 sin 2.6179938779914944 0.0 -> 0.49999999999999996018 -0.0
sin0061 sin -2.6179938779914944 0.0 -> -0.49999999999999996018 -0.0
sin0062 sin 7.225663103256523 0.0 -> 0.80901699437494673648 0.0
sin0063 sin -8.79645943005142 0.0 -> -0.58778525229247340658 -0.0
-- special values
sin1000 sin -0.0 0.0 -> -0.0 0.0
sin1001 sin -inf 0.0 -> nan 0.0 invalid ignore-imag-sign
sin1002 sin nan 0.0 -> nan 0.0 ignore-imag-sign
sin1003 sin -inf 2.2999999999999998 -> nan nan invalid
sin1004 sin nan 2.2999999999999998 -> nan nan
sin1005 sin -0.0 inf -> -0.0 inf
sin1006 sin -1.3999999999999999 inf -> -inf inf
sin1007 sin -2.7999999999999998 inf -> -inf -inf
sin1008 sin -4.2000000000000002 inf -> inf -inf
sin1009 sin -5.5999999999999996 inf -> inf inf
sin1010 sin -7.0 inf -> -inf inf
sin1011 sin -inf inf -> nan inf invalid ignore-imag-sign
sin1012 sin nan inf -> nan inf ignore-imag-sign
sin1013 sin -0.0 nan -> -0.0 nan
sin1014 sin -2.2999999999999998 nan -> nan nan
sin1015 sin -inf nan -> nan nan
sin1016 sin nan nan -> nan nan
sin1017 sin 0.0 0.0 -> 0.0 0.0
sin1018 sin inf 0.0 -> nan 0.0 invalid ignore-imag-sign
sin1019 sin inf 2.2999999999999998 -> nan nan invalid
sin1020 sin 0.0 inf -> 0.0 inf
sin1021 sin 1.3999999999999999 inf -> inf inf
sin1022 sin 2.7999999999999998 inf -> inf -inf
sin1023 sin 4.2000000000000002 inf -> -inf -inf
sin1024 sin 5.5999999999999996 inf -> -inf inf
sin1025 sin 7.0 inf -> inf inf
sin1026 sin inf inf -> nan inf invalid ignore-imag-sign
sin1027 sin 0.0 nan -> 0.0 nan
sin1028 sin 2.2999999999999998 nan -> nan nan
sin1029 sin inf nan -> nan nan
sin1030 sin 0.0 -0.0 -> 0.0 -0.0
sin1031 sin inf -0.0 -> nan 0.0 invalid ignore-imag-sign
sin1032 sin nan -0.0 -> nan 0.0 ignore-imag-sign
sin1033 sin inf -2.2999999999999998 -> nan nan invalid
sin1034 sin nan -2.2999999999999998 -> nan nan
sin1035 sin 0.0 -inf -> 0.0 -inf
sin1036 sin 1.3999999999999999 -inf -> inf -inf
sin1037 sin 2.7999999999999998 -inf -> inf inf
sin1038 sin 4.2000000000000002 -inf -> -inf inf
sin1039 sin 5.5999999999999996 -inf -> -inf -inf
sin1040 sin 7.0 -inf -> inf -inf
sin1041 sin inf -inf -> nan inf invalid ignore-imag-sign
sin1042 sin nan -inf -> nan inf ignore-imag-sign
sin1043 sin -0.0 -0.0 -> -0.0 -0.0
sin1044 sin -inf -0.0 -> nan 0.0 invalid ignore-imag-sign
sin1045 sin -inf -2.2999999999999998 -> nan nan invalid
sin1046 sin -0.0 -inf -> -0.0 -inf
sin1047 sin -1.3999999999999999 -inf -> -inf -inf
sin1048 sin -2.7999999999999998 -inf -> -inf inf
sin1049 sin -4.2000000000000002 -inf -> inf inf
sin1050 sin -5.5999999999999996 -inf -> inf -inf
sin1051 sin -7.0 -inf -> -inf -inf
sin1052 sin -inf -inf -> nan inf invalid ignore-imag-sign
------------------
-- tan: Tangent --
------------------
-- zeros
tan0000 tan 0.0 0.0 -> 0.0 0.0
tan0001 tan 0.0 -0.0 -> 0.0 -0.0
tan0002 tan -0.0 0.0 -> -0.0 0.0
tan0003 tan -0.0 -0.0 -> -0.0 -0.0
-- random inputs
tan0004 tan -0.56378561833861074 -1.7110276237187664e+73 -> -0.0 -1.0
tan0005 tan -3.5451633993471915e-12 -2.855471863564059 -> -4.6622441304889575e-14 -0.99340273843093951
tan0006 tan -2.502442719638696 -0.26742234390504221 -> 0.66735215252994995 -0.39078997935420956
tan0007 tan -0.87639597720371365 -55.586225523280206 -> -1.0285264565948176e-48 -1.0
tan0008 tan -0.015783869596427243 -520.05944436039272 -> -0.0 -1.0
tan0009 tan -0.84643549990725164 2.0749097935396343 -> -0.031412661676959573 1.0033548479526764
tan0010 tan -0.43613792248559646 8.1082741629458059 -> -1.3879848444644593e-07 0.99999988344224011
tan0011 tan -1.0820906367833114 0.28571868992480248 -> -1.3622485737936536 0.99089269377971245
tan0012 tan -1.1477859580220084 1.9021637002708041 -> -0.034348450042071196 1.0293954097901687
tan0013 tan -0.12465543176953409 3.0606851016344815e-05 -> -0.12530514290387343 3.1087420769945479e-05
tan0014 tan 3.7582848717525343 -692787020.44038939 -> 0.0 -1.0
tan0015 tan 2.2321967655142176e-06 -10.090069423008169 -> 1.5369846120622643e-14 -0.99999999655723759
tan0016 tan 0.88371172390245012 -1.1635053630132823 -> 0.19705017118625889 -1.0196452280843129
tan0017 tan 2.1347414231849267 -1.9311339960416831 -> -0.038663576915982524 -1.0174399993980778
tan0018 tan 5.9027945255899974 -2.1574195684607135e-183 -> -0.39986591539281496 -2.5023753167976915e-183
tan0019 tan 0.44811489490805362 683216075670.07556 -> 0.0 1.0
tan0020 tan 4.1459766396068325 12.523017205605756 -> 2.4022514758988068e-11 1.0000000000112499
tan0021 tan 1.7809617968443272 1.5052381702853379 -> -0.044066222118946903 1.0932684517702778
tan0022 tan 1.1615313900880577 1.7956298728647107 -> 0.041793186826390362 1.0375339546034792
tan0023 tan 0.067014779477908945 5.8517361577457097 -> 2.2088639754800034e-06 0.9999836182420061
-- Additional real values (mpmath)
tan0050 tan 1e-100 0.0 -> 1.00000000000000002e-100 0.0
tan0051 tan 3.7e-08 0.0 -> 3.7000000000000017328e-8 0.0
tan0052 tan 0.001 0.0 -> 0.0010000003333334666875 0.0
tan0053 tan 0.2 0.0 -> 0.20271003550867249488 0.0
tan0054 tan 1.0 0.0 -> 1.5574077246549022305 0.0
tan0055 tan -3.7e-08 0.0 -> -3.7000000000000017328e-8 0.0
tan0056 tan -0.001 0.0 -> -0.0010000003333334666875 0.0
tan0057 tan -1.0 0.0 -> -1.5574077246549022305 0.0
tan0058 tan 0.4636476090008061 0.0 -> 0.49999999999999997163 0.0
tan0059 tan -0.4636476090008061 0.0 -> -0.49999999999999997163 0.0
tan0060 tan 1.1071487177940904 0.0 -> 1.9999999999999995298 0.0
tan0061 tan -1.1071487177940904 0.0 -> -1.9999999999999995298 0.0
tan0062 tan 1.5 0.0 -> 14.101419947171719388 0.0
tan0063 tan 1.57 0.0 -> 1255.7655915007896475 0.0
tan0064 tan 1.5707963267948961 0.0 -> 1978937966095219.0538 0.0
tan0065 tan 7.225663103256523 0.0 -> 1.3763819204711701522 0.0
tan0066 tan -8.79645943005142 0.0 -> 0.7265425280053614098 0.0
-- special values
tan1000 tan -0.0 0.0 -> -0.0 0.0
tan1001 tan -inf 0.0 -> nan nan invalid
tan1002 tan -inf 2.2999999999999998 -> nan nan invalid
tan1003 tan nan 0.0 -> nan nan
tan1004 tan nan 2.2999999999999998 -> nan nan
tan1005 tan -0.0 inf -> -0.0 1.0
tan1006 tan -0.69999999999999996 inf -> -0.0 1.0
tan1007 tan -1.3999999999999999 inf -> -0.0 1.0
tan1008 tan -2.1000000000000001 inf -> 0.0 1.0
tan1009 tan -2.7999999999999998 inf -> 0.0 1.0
tan1010 tan -3.5 inf -> -0.0 1.0
tan1011 tan -inf inf -> -0.0 1.0 ignore-real-sign
tan1012 tan nan inf -> -0.0 1.0 ignore-real-sign
tan1013 tan -0.0 nan -> -0.0 nan
tan1014 tan -2.2999999999999998 nan -> nan nan
tan1015 tan -inf nan -> nan nan
tan1016 tan nan nan -> nan nan
tan1017 tan 0.0 0.0 -> 0.0 0.0
tan1018 tan inf 0.0 -> nan nan invalid
tan1019 tan inf 2.2999999999999998 -> nan nan invalid
tan1020 tan 0.0 inf -> 0.0 1.0
tan1021 tan 0.69999999999999996 inf -> 0.0 1.0
tan1022 tan 1.3999999999999999 inf -> 0.0 1.0
tan1023 tan 2.1000000000000001 inf -> -0.0 1.0
tan1024 tan 2.7999999999999998 inf -> -0.0 1.0
tan1025 tan 3.5 inf -> 0.0 1.0
tan1026 tan inf inf -> -0.0 1.0 ignore-real-sign
tan1027 tan 0.0 nan -> 0.0 nan
tan1028 tan 2.2999999999999998 nan -> nan nan
tan1029 tan inf nan -> nan nan
tan1030 tan 0.0 -0.0 -> 0.0 -0.0
tan1031 tan inf -0.0 -> nan nan invalid
tan1032 tan inf -2.2999999999999998 -> nan nan invalid
tan1033 tan nan -0.0 -> nan nan
tan1034 tan nan -2.2999999999999998 -> nan nan
tan1035 tan 0.0 -inf -> 0.0 -1.0
tan1036 tan 0.69999999999999996 -inf -> 0.0 -1.0
tan1037 tan 1.3999999999999999 -inf -> 0.0 -1.0
tan1038 tan 2.1000000000000001 -inf -> -0.0 -1.0
tan1039 tan 2.7999999999999998 -inf -> -0.0 -1.0
tan1040 tan 3.5 -inf -> 0.0 -1.0
tan1041 tan inf -inf -> -0.0 -1.0 ignore-real-sign
tan1042 tan nan -inf -> -0.0 -1.0 ignore-real-sign
tan1043 tan -0.0 -0.0 -> -0.0 -0.0
tan1044 tan -inf -0.0 -> nan nan invalid
tan1045 tan -inf -2.2999999999999998 -> nan nan invalid
tan1046 tan -0.0 -inf -> -0.0 -1.0
tan1047 tan -0.69999999999999996 -inf -> -0.0 -1.0
tan1048 tan -1.3999999999999999 -inf -> -0.0 -1.0
tan1049 tan -2.1000000000000001 -inf -> 0.0 -1.0
tan1050 tan -2.7999999999999998 -inf -> 0.0 -1.0
tan1051 tan -3.5 -inf -> -0.0 -1.0
tan1052 tan -inf -inf -> -0.0 -1.0 ignore-real-sign
------------------------------------------------------------------------
-- rect: Conversion from polar coordinates to rectangular coordinates --
------------------------------------------------------------------------
--
-- For cmath.rect, we can use the same testcase syntax as for the
-- complex -> complex functions above, but here the input arguments
-- should be interpreted as a pair of floating-point numbers rather
-- than the real and imaginary parts of a complex number.
--
-- Here are the 'spirit of C99' rules for rect. First, the short
-- version:
--
-- rect(x, t) = exp(log(x)+it) for positive-signed x
-- rect(x, t) = -exp(log(-x)+it) for negative-signed x
-- rect(nan, t) = exp(nan + it), except that in rect(nan, +-0) the
-- sign of the imaginary part is unspecified.
--
-- and now the long version:
--
-- rect(x, -t) = conj(rect(x, t)) for all x and t
-- rect(-x, t) = -rect(x, t) for all x and t
-- rect(+0, +0) returns +0 + i0
-- rect(+0, inf) returns +- 0 +- i0, where the signs of the real and
-- imaginary parts are unspecified.
-- rect(x, inf) returns NaN + i NaN and raises the "invalid"
-- floating-point exception, for finite nonzero x.
-- rect(inf, inf) returns +-inf + i NaN and raises the "invalid"
-- floating-point exception (where the sign of the real part of the
-- result is unspecified).
-- rect(inf, +0) returns inf+i0
-- rect(inf, x) returns inf*cis(x), for finite nonzero x
-- rect(inf, NaN) returns +-inf+i NaN, where the sign of the real part
-- of the result is unspecified.
-- rect(NaN, x) returns NaN + i NaN for all nonzero numbers (including
-- infinities) x
-- rect(NaN, 0) returns NaN +- i0, where the sign of the imaginary
-- part is unspecified
-- rect(NaN, NaN) returns NaN + i NaN
-- rect(x, NaN) returns NaN + i NaN for finite nonzero x
-- rect(+0, NaN) return +-0 +- i0, where the signs of the real and
-- imaginary parts are unspecified.
-- special values
rect1000 rect 0.0 0.0 -> 0.0 0.0
rect1001 rect 0.0 inf -> 0.0 0.0 ignore-real-sign ignore-imag-sign
rect1002 rect 2.3 inf -> nan nan invalid
rect1003 rect inf inf -> inf nan invalid ignore-real-sign
rect1004 rect inf 0.0 -> inf 0.0
rect1005 rect inf 1.4 -> inf inf
rect1006 rect inf 2.8 -> -inf inf
rect1007 rect inf 4.2 -> -inf -inf
rect1008 rect inf 5.6 -> inf -inf
rect1009 rect inf 7.0 -> inf inf
rect1010 rect nan 0.0 -> nan 0.0 ignore-imag-sign
rect1011 rect nan 2.3 -> nan nan
rect1012 rect nan inf -> nan nan
rect1013 rect nan nan -> nan nan
rect1014 rect inf nan -> inf nan ignore-real-sign
rect1015 rect 2.3 nan -> nan nan
rect1016 rect 0.0 nan -> 0.0 0.0 ignore-real-sign ignore-imag-sign
rect1017 rect 0.0 -0.0 -> 0.0 -0.0
rect1018 rect 0.0 -inf -> 0.0 0.0 ignore-real-sign ignore-imag-sign
rect1019 rect 2.3 -inf -> nan nan invalid
rect1020 rect inf -inf -> inf nan invalid ignore-real-sign
rect1021 rect inf -0.0 -> inf -0.0
rect1022 rect inf -1.4 -> inf -inf
rect1023 rect inf -2.8 -> -inf -inf
rect1024 rect inf -4.2 -> -inf inf
rect1025 rect inf -5.6 -> inf inf
rect1026 rect inf -7.0 -> inf -inf
rect1027 rect nan -0.0 -> nan 0.0 ignore-imag-sign
rect1028 rect nan -2.3 -> nan nan
rect1029 rect nan -inf -> nan nan
rect1030 rect -0.0 0.0 -> -0.0 -0.0
rect1031 rect -0.0 inf -> 0.0 0.0 ignore-real-sign ignore-imag-sign
rect1032 rect -2.3 inf -> nan nan invalid
rect1033 rect -inf inf -> -inf nan invalid ignore-real-sign
rect1034 rect -inf 0.0 -> -inf -0.0
rect1035 rect -inf 1.4 -> -inf -inf
rect1036 rect -inf 2.8 -> inf -inf
rect1037 rect -inf 4.2 -> inf inf
rect1038 rect -inf 5.6 -> -inf inf
rect1039 rect -inf 7.0 -> -inf -inf
rect1040 rect -inf nan -> inf nan ignore-real-sign
rect1041 rect -2.3 nan -> nan nan
rect1042 rect -0.0 nan -> 0.0 0.0 ignore-real-sign ignore-imag-sign
rect1043 rect -0.0 -0.0 -> -0.0 0.0
rect1044 rect -0.0 -inf -> 0.0 0.0 ignore-real-sign ignore-imag-sign
rect1045 rect -2.3 -inf -> nan nan invalid
rect1046 rect -inf -inf -> -inf nan invalid ignore-real-sign
rect1047 rect -inf -0.0 -> -inf 0.0
rect1048 rect -inf -1.4 -> -inf inf
rect1049 rect -inf -2.8 -> inf inf
rect1050 rect -inf -4.2 -> inf -inf
rect1051 rect -inf -5.6 -> -inf -inf
rect1052 rect -inf -7.0 -> -inf inf
-------------------------------------------------------------------------
-- polar: Conversion from rectangular coordinates to polar coordinates --
-------------------------------------------------------------------------
--
-- For cmath.polar, we can use the same testcase syntax as for the
-- complex -> complex functions above, but here the output arguments
-- should be interpreted as a pair of floating-point numbers rather
-- than the real and imaginary parts of a complex number.
--
-- Annex G of the C99 standard describes fully both the real and
-- imaginary parts of polar (as cabs and carg, respectively, which in turn
-- are defined in terms of the functions hypot and atan2).
-- overflow
polar0100 polar 1.4e308 1.4e308 -> inf 0.78539816339744828 overflow
-- special values
polar1000 polar 0.0 0.0 -> 0.0 0.0
polar1001 polar 0.0 -0.0 -> 0.0 -0.0
polar1002 polar -0.0 0.0 -> 0.0 3.1415926535897931
polar1003 polar -0.0 -0.0 -> 0.0 -3.1415926535897931
polar1004 polar inf 0.0 -> inf 0.0
polar1005 polar inf 2.3 -> inf 0.0
polar1006 polar inf inf -> inf 0.78539816339744828
polar1007 polar 2.3 inf -> inf 1.5707963267948966
polar1008 polar 0.0 inf -> inf 1.5707963267948966
polar1009 polar -0.0 inf -> inf 1.5707963267948966
polar1010 polar -2.3 inf -> inf 1.5707963267948966
polar1011 polar -inf inf -> inf 2.3561944901923448
polar1012 polar -inf 2.3 -> inf 3.1415926535897931
polar1013 polar -inf 0.0 -> inf 3.1415926535897931
polar1014 polar -inf -0.0 -> inf -3.1415926535897931
polar1015 polar -inf -2.3 -> inf -3.1415926535897931
polar1016 polar -inf -inf -> inf -2.3561944901923448
polar1017 polar -2.3 -inf -> inf -1.5707963267948966
polar1018 polar -0.0 -inf -> inf -1.5707963267948966
polar1019 polar 0.0 -inf -> inf -1.5707963267948966
polar1020 polar 2.3 -inf -> inf -1.5707963267948966
polar1021 polar inf -inf -> inf -0.78539816339744828
polar1022 polar inf -2.3 -> inf -0.0
polar1023 polar inf -0.0 -> inf -0.0
polar1024 polar nan -inf -> inf nan
polar1025 polar nan -2.3 -> nan nan
polar1026 polar nan -0.0 -> nan nan
polar1027 polar nan 0.0 -> nan nan
polar1028 polar nan 2.3 -> nan nan
polar1029 polar nan inf -> inf nan
polar1030 polar nan nan -> nan nan
polar1031 polar inf nan -> inf nan
polar1032 polar 2.3 nan -> nan nan
polar1033 polar 0.0 nan -> nan nan
polar1034 polar -0.0 nan -> nan nan
polar1035 polar -2.3 nan -> nan nan
polar1036 polar -inf nan -> inf nan
| 144,432 | 2,512 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_spwd.py | import os
import unittest
from test import support
spwd = support.import_module('spwd')
@unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0,
'root privileges required')
class TestSpwdRoot(unittest.TestCase):
def test_getspall(self):
entries = spwd.getspall()
self.assertIsInstance(entries, list)
for entry in entries:
self.assertIsInstance(entry, spwd.struct_spwd)
def test_getspnam(self):
entries = spwd.getspall()
if not entries:
self.skipTest('empty shadow password database')
random_name = entries[0].sp_namp
entry = spwd.getspnam(random_name)
self.assertIsInstance(entry, spwd.struct_spwd)
self.assertEqual(entry.sp_namp, random_name)
self.assertEqual(entry.sp_namp, entry[0])
self.assertEqual(entry.sp_namp, entry.sp_nam)
self.assertIsInstance(entry.sp_pwdp, str)
self.assertEqual(entry.sp_pwdp, entry[1])
self.assertEqual(entry.sp_pwdp, entry.sp_pwd)
self.assertIsInstance(entry.sp_lstchg, int)
self.assertEqual(entry.sp_lstchg, entry[2])
self.assertIsInstance(entry.sp_min, int)
self.assertEqual(entry.sp_min, entry[3])
self.assertIsInstance(entry.sp_max, int)
self.assertEqual(entry.sp_max, entry[4])
self.assertIsInstance(entry.sp_warn, int)
self.assertEqual(entry.sp_warn, entry[5])
self.assertIsInstance(entry.sp_inact, int)
self.assertEqual(entry.sp_inact, entry[6])
self.assertIsInstance(entry.sp_expire, int)
self.assertEqual(entry.sp_expire, entry[7])
self.assertIsInstance(entry.sp_flag, int)
self.assertEqual(entry.sp_flag, entry[8])
with self.assertRaises(KeyError) as cx:
spwd.getspnam('invalid user name')
self.assertEqual(str(cx.exception), "'getspnam(): name not found'")
self.assertRaises(TypeError, spwd.getspnam)
self.assertRaises(TypeError, spwd.getspnam, 0)
self.assertRaises(TypeError, spwd.getspnam, random_name, 0)
try:
bytes_name = os.fsencode(random_name)
except UnicodeEncodeError:
pass
else:
self.assertRaises(TypeError, spwd.getspnam, bytes_name)
@unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() != 0,
'non-root user required')
class TestSpwdNonRoot(unittest.TestCase):
def test_getspnam_exception(self):
name = 'bin'
try:
with self.assertRaises(PermissionError) as cm:
spwd.getspnam(name)
except KeyError as exc:
self.skipTest("spwd entry %r doesn't exist: %s" % (name, exc))
if __name__ == "__main__":
unittest.main()
| 2,774 | 74 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/revocation.crl | -----BEGIN X509 CRL-----
MIICJjCBjwIBATANBgkqhkiG9w0BAQsFADBNMQswCQYDVQQGEwJYWTEmMCQGA1UE
CgwdUHl0aG9uIFNvZnR3YXJlIEZvdW5kYXRpb24gQ0ExFjAUBgNVBAMMDW91ci1j
YS1zZXJ2ZXIXDTE4MDgyOTE0MjMxNloXDTI4MDcwNzE0MjMxNlqgDjAMMAoGA1Ud
FAQDAgEAMA0GCSqGSIb3DQEBCwUAA4IBgQCPhrtGSbuvxPAI3YWQFDB4iOWdBnVk
ugW1lsifmCsE86FfID0EwUut1SRHlksltMtcoULMEIdu8yMLWci++4ve22EEuMKT
HUc3T/wBIuQUhA7U4deFG8CZPAxRpNoK470y7dkD4OVf0Gxa6WYDl9z8mXKmWCB9
hvzqVfLWNSLTAVPsHtkD5PXdi5yRkQr6wYD7poWaIvkpsn7EKCY6Tw5V3rsbRuZq
AGVCq5TH3mctcmwLloCJ4Xr/1q0DsRrYxeeLYxE+UpvvCbVBKgtjBK7zINS7AbcJ
CYCYKUwGWv1fYKJ+KQQHf75mT3jQ9lWuzOj/YWK4k1EBnYmVGuKKt73lLFxC6h3y
MUnaBZc1KZSyJj0IxfHg/o6qx8NgKOl9XRIQ5g5B30cwpPOskGhEhodbTTY3bPtm
RQ36JvQZngzmkhyhr+MDEV5yUTOShfUiclzQOx26CmLmLHWxOZgXtFZob/oKrvbm
Gen/+7K7YTw6hfY52U7J2FuQRGOyzBXfBYQ=
-----END X509 CRL-----
| 800 | 15 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/exception_hierarchy.txt | BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
| 1,822 | 65 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/zipdir.zip | PK
ýº%: a/UT }bIbIUx èèPK
»%: a/b/UT bIbIUx èèPK
»%: a/b/cUT bIbIUx èèPK
ýº%:
íA a/UT }bIUx PK
»%:
íA5 a/b/UT bIUx PK
»%:
¤l a/b/cUT bIUx PK ¼ ¤ | 374 | 10 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_openpty.py | # Test to see if openpty works. (But don't worry if it isn't available.)
import os, unittest
if not hasattr(os, "openpty"):
raise unittest.SkipTest("os.openpty() not available.")
class OpenptyTest(unittest.TestCase):
def test(self):
master, slave = os.openpty()
self.addCleanup(os.close, master)
self.addCleanup(os.close, slave)
if not os.isatty(slave):
self.fail("Slave-end of pty is not a terminal.")
os.write(slave, b'Ping!')
self.assertEqual(os.read(master, 1024), b'Ping!')
if __name__ == '__main__':
unittest.main()
| 600 | 22 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_xml_etree_c.py | # xml.etree test for cElementTree
import struct
from test import support
from test.support import import_fresh_module
import types
import unittest
from encodings import (
aliases,
base64_codec,
big5,
big5hkscs,
bz2_codec,
charmap,
cp037,
cp1006,
cp1026,
cp1125,
cp1140,
cp1250,
cp1251,
cp1252,
cp1253,
cp1254,
cp1255,
cp1256,
cp1257,
cp1258,
cp273,
cp424,
cp437,
cp500,
cp720,
cp737,
cp775,
cp850,
cp852,
cp855,
cp856,
cp857,
cp858,
cp860,
cp861,
cp862,
cp863,
cp864,
cp865,
cp866,
cp869,
cp874,
cp875,
cp932,
cp949,
cp950,
euc_jis_2004,
euc_jisx0213,
euc_jp,
euc_kr,
gb18030,
gb2312,
gbk,
hex_codec,
hp_roman8,
hz,
idna,
iso2022_jp,
iso2022_jp_1,
iso2022_jp_2,
iso2022_jp_2004,
iso2022_jp_3,
iso2022_jp_ext,
iso2022_kr,
iso8859_1,
iso8859_10,
iso8859_11,
iso8859_13,
iso8859_14,
iso8859_15,
iso8859_16,
iso8859_2,
iso8859_3,
iso8859_4,
iso8859_5,
iso8859_6,
iso8859_7,
iso8859_8,
iso8859_9,
johab,
koi8_r,
koi8_t,
koi8_u,
kz1048,
latin_1,
mac_arabic,
mac_centeuro,
mac_croatian,
mac_cyrillic,
mac_farsi,
mac_greek,
mac_iceland,
mac_latin2,
mac_roman,
mac_romanian,
mac_turkish,
palmos,
ptcp154,
punycode,
quopri_codec,
raw_unicode_escape,
rot_13,
shift_jis,
shift_jis_2004,
shift_jisx0213,
tis_620,
undefined,
unicode_escape,
unicode_internal,
utf_16,
utf_16_be,
utf_16_le,
utf_32,
utf_32_be,
utf_32_le,
utf_7,
utf_8,
utf_8_sig,
uu_codec,
zlib_codec,
)
if __name__ == 'PYOBJ.COM':
import _elementtree
import xml.etree
import xml.etree.cElementTree
cET = import_fresh_module('xml.etree.ElementTree',
fresh=['_elementtree'])
cET_alias = import_fresh_module('xml.etree.cElementTree',
fresh=['_elementtree', 'xml.etree'])
@unittest.skipUnless(cET, 'requires _elementtree')
class MiscTests(unittest.TestCase):
# Issue #8651.
@support.bigmemtest(size=support._2G + 100, memuse=1, dry_run=False)
def test_length_overflow(self, size):
data = b'x' * size
parser = cET.XMLParser()
try:
self.assertRaises(OverflowError, parser.feed, data)
finally:
data = None
def test_del_attribute(self):
element = cET.Element('tag')
element.tag = 'TAG'
with self.assertRaises(AttributeError):
del element.tag
self.assertEqual(element.tag, 'TAG')
with self.assertRaises(AttributeError):
del element.text
self.assertIsNone(element.text)
element.text = 'TEXT'
with self.assertRaises(AttributeError):
del element.text
self.assertEqual(element.text, 'TEXT')
with self.assertRaises(AttributeError):
del element.tail
self.assertIsNone(element.tail)
element.tail = 'TAIL'
with self.assertRaises(AttributeError):
del element.tail
self.assertEqual(element.tail, 'TAIL')
with self.assertRaises(AttributeError):
del element.attrib
self.assertEqual(element.attrib, {})
element.attrib = {'A': 'B', 'C': 'D'}
with self.assertRaises(AttributeError):
del element.attrib
self.assertEqual(element.attrib, {'A': 'B', 'C': 'D'})
def test_trashcan(self):
# If this test fails, it will most likely die via segfault.
e = root = cET.Element('root')
for i in range(200000):
e = cET.SubElement(e, 'x')
del e
del root
support.gc_collect()
def test_parser_ref_cycle(self):
# bpo-31499: xmlparser_dealloc() crashed with a segmentation fault when
# xmlparser_gc_clear() was called previously by the garbage collector,
# when the parser was part of a reference cycle.
def parser_ref_cycle():
parser = cET.XMLParser()
# Create a reference cycle using an exception to keep the frame
# alive, so the parser will be destroyed by the garbage collector
try:
raise ValueError
except ValueError as exc:
err = exc
# Create a parser part of reference cycle
parser_ref_cycle()
# Trigger an explicit garbage collection to break the reference cycle
# and so destroy the parser
support.gc_collect()
def test_bpo_31728(self):
# A crash or an assertion failure shouldn't happen, in case garbage
# collection triggers a call to clear() or a reading of text or tail,
# while a setter or clear() or __setstate__() is already running.
elem = cET.Element('elem')
class X:
def __del__(self):
elem.text
elem.tail
elem.clear()
elem.text = X()
elem.clear() # shouldn't crash
elem.tail = X()
elem.clear() # shouldn't crash
elem.text = X()
elem.text = X() # shouldn't crash
elem.clear()
elem.tail = X()
elem.tail = X() # shouldn't crash
elem.clear()
elem.text = X()
elem.__setstate__({'tag': 42}) # shouldn't cause an assertion failure
elem.clear()
elem.tail = X()
elem.__setstate__({'tag': 42}) # shouldn't cause an assertion failure
def test_setstate_leaks(self):
# Test reference leaks
elem = cET.Element.__new__(cET.Element)
for i in range(100):
elem.__setstate__({'tag': 'foo', 'attrib': {'bar': 42},
'_children': [cET.Element('child')],
'text': 'text goes here',
'tail': 'opposite of head'})
self.assertEqual(elem.tag, 'foo')
self.assertEqual(elem.text, 'text goes here')
self.assertEqual(elem.tail, 'opposite of head')
self.assertEqual(list(elem.attrib.items()), [('bar', 42)])
self.assertEqual(len(elem), 1)
self.assertEqual(elem[0].tag, 'child')
@unittest.skipUnless(cET, 'requires _elementtree')
class TestAliasWorking(unittest.TestCase):
# Test that the cET alias module is alive
def test_alias_working(self):
e = cET_alias.Element('foo')
self.assertEqual(e.tag, 'foo')
@unittest.skipUnless(cET, 'requires _elementtree')
@support.cpython_only
class TestAcceleratorImported(unittest.TestCase):
# Test that the C accelerator was imported, as expected
def test_correct_import_cET(self):
# SubElement is a function so it retains _elementtree as its module.
self.assertEqual(cET.SubElement.__module__, '_elementtree')
def test_correct_import_cET_alias(self):
self.assertEqual(cET_alias.SubElement.__module__, '_elementtree')
def test_parser_comes_from_C(self):
# The type of methods defined in Python code is types.FunctionType,
# while the type of methods defined inside _elementtree is
# <class 'wrapper_descriptor'>
self.assertNotIsInstance(cET.Element.__init__, types.FunctionType)
@unittest.skipUnless(cET, 'requires _elementtree')
@support.cpython_only
class SizeofTest(unittest.TestCase):
def setUp(self):
self.elementsize = support.calcobjsize('5P')
# extra
self.extra = struct.calcsize('PnnP4P')
check_sizeof = support.check_sizeof
def test_element(self):
e = cET.Element('a')
self.check_sizeof(e, self.elementsize)
def test_element_with_attrib(self):
e = cET.Element('a', href='about:')
self.check_sizeof(e, self.elementsize + self.extra)
def test_element_with_children(self):
e = cET.Element('a')
for i in range(5):
cET.SubElement(e, 'span')
# should have space for 8 children now
self.check_sizeof(e, self.elementsize + self.extra +
struct.calcsize('8P'))
def test_main():
from test import test_xml_etree
# Run the tests specific to the C implementation
support.run_unittest(
MiscTests,
TestAliasWorking,
TestAcceleratorImported,
SizeofTest,
)
# Run the same test suite as the Python module
test_xml_etree.test_main(module=cET)
if __name__ == '__main__':
test_main()
| 8,652 | 333 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_platform.py | from unittest import mock
import os
import platform
import subprocess
import sys
import sysconfig
import tempfile
import unittest
import warnings
from test import support
class PlatformTest(unittest.TestCase):
def test_architecture(self):
res = platform.architecture()
@support.skip_unless_symlink
def test_architecture_via_symlink(self): # issue3762
# On Windows, the EXE needs to know where pythonXY.dll and *.pyd is at
# so we add the directory to the path, PYTHONHOME and PYTHONPATH.
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", ""))
env["PYTHONHOME"] = os.path.dirname(sys.executable)
if sysconfig.is_python_build(True):
env["PYTHONPATH"] = os.path.dirname(os.__file__)
def get(python, env=None):
cmd = [python, '-c',
'import platform; print(platform.architecture())']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, env=env)
r = p.communicate()
if p.returncode:
print(repr(r[0]))
print(repr(r[1]), file=sys.stderr)
self.fail('unexpected return code: {0} (0x{0:08X})'
.format(p.returncode))
return r
real = os.path.realpath(sys.executable)
link = os.path.abspath(support.TESTFN)
os.symlink(real, link)
try:
self.assertEqual(get(real), get(link, env=env))
finally:
os.remove(link)
def test_platform(self):
for aliased in (False, True):
for terse in (False, True):
res = platform.platform(aliased, terse)
def test_system(self):
res = platform.system()
def test_node(self):
res = platform.node()
def test_release(self):
res = platform.release()
def test_version(self):
res = platform.version()
def test_machine(self):
res = platform.machine()
def test_processor(self):
res = platform.processor()
def setUp(self):
self.save_version = sys.version
self.save_git = sys._git
self.save_platform = sys.platform
def tearDown(self):
sys.version = self.save_version
sys._git = self.save_git
sys.platform = self.save_platform
def test_sys_version(self):
# Old test.
for input, output in (
('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]',
('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')),
('IronPython 1.0.60816 on .NET 2.0.50727.42',
('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')),
('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42',
('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42')),
('2.4.3 (truncation, date, t) \n[GCC]',
('CPython', '2.4.3', '', '', 'truncation', 'date t', 'GCC')),
('2.4.3 (truncation, date, ) \n[GCC]',
('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
('2.4.3 (truncation, date,) \n[GCC]',
('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
('2.4.3 (truncation, date) \n[GCC]',
('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
('2.4.3 (truncation, d) \n[GCC]',
('CPython', '2.4.3', '', '', 'truncation', 'd', 'GCC')),
('2.4.3 (truncation, ) \n[GCC]',
('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')),
('2.4.3 (truncation,) \n[GCC]',
('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')),
('2.4.3 (truncation) \n[GCC]',
('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')),
):
# branch and revision are not "parsed", but fetched
# from sys._git. Ignore them
(name, version, branch, revision, buildno, builddate, compiler) \
= platform._sys_version(input)
self.assertEqual(
(name, version, '', '', buildno, builddate, compiler), output)
# Tests for python_implementation(), python_version(), python_branch(),
# python_revision(), python_build(), and python_compiler().
sys_versions = {
("2.6.1 (r261:67515, Dec 6 2008, 15:26:00) \n[GCC 4.0.1 (Apple Computer, Inc. build 5370)]",
('CPython', 'tags/r261', '67515'), self.save_platform)
:
("CPython", "2.6.1", "tags/r261", "67515",
('r261:67515', 'Dec 6 2008 15:26:00'),
'GCC 4.0.1 (Apple Computer, Inc. build 5370)'),
("IronPython 2.0 (2.0.0.0) on .NET 2.0.50727.3053", None, "cli")
:
("IronPython", "2.0.0", "", "", ("", ""),
".NET 2.0.50727.3053"),
("2.6.1 (IronPython 2.6.1 (2.6.10920.0) on .NET 2.0.50727.1433)", None, "cli")
:
("IronPython", "2.6.1", "", "", ("", ""),
".NET 2.0.50727.1433"),
("2.7.4 (IronPython 2.7.4 (2.7.0.40) on Mono 4.0.30319.1 (32-bit))", None, "cli")
:
("IronPython", "2.7.4", "", "", ("", ""),
"Mono 4.0.30319.1 (32-bit)"),
("2.5 (trunk:6107, Mar 26 2009, 13:02:18) \n[Java HotSpot(TM) Client VM (\"Apple Computer, Inc.\")]",
('Jython', 'trunk', '6107'), "java1.5.0_16")
:
("Jython", "2.5.0", "trunk", "6107",
('trunk:6107', 'Mar 26 2009'), "java1.5.0_16"),
("2.5.2 (63378, Mar 26 2009, 18:03:29)\n[PyPy 1.0.0]",
('PyPy', 'trunk', '63378'), self.save_platform)
:
("PyPy", "2.5.2", "trunk", "63378", ('63378', 'Mar 26 2009'),
"")
}
for (version_tag, subversion, sys_platform), info in \
sys_versions.items():
sys.version = version_tag
if subversion is None:
if hasattr(sys, "_git"):
del sys._git
else:
sys._git = subversion
if sys_platform is not None:
sys.platform = sys_platform
self.assertEqual(platform.python_implementation(), info[0])
self.assertEqual(platform.python_version(), info[1])
self.assertEqual(platform.python_branch(), info[2])
self.assertEqual(platform.python_revision(), info[3])
self.assertEqual(platform.python_build(), info[4])
self.assertEqual(platform.python_compiler(), info[5])
def test_system_alias(self):
res = platform.system_alias(
platform.system(),
platform.release(),
platform.version(),
)
def test_uname(self):
res = platform.uname()
self.assertTrue(any(res))
self.assertEqual(res[0], res.system)
self.assertEqual(res[1], res.node)
self.assertEqual(res[2], res.release)
self.assertEqual(res[3], res.version)
self.assertEqual(res[4], res.machine)
self.assertEqual(res[5], res.processor)
@unittest.skipUnless(sys.platform.startswith('win'), "windows only test")
def test_uname_win32_ARCHITEW6432(self):
# Issue 7860: make sure we get architecture from the correct variable
# on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
# using it, per
# http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
try:
with support.EnvironmentVarGuard() as environ:
if 'PROCESSOR_ARCHITEW6432' in environ:
del environ['PROCESSOR_ARCHITEW6432']
environ['PROCESSOR_ARCHITECTURE'] = 'foo'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'foo')
environ['PROCESSOR_ARCHITEW6432'] = 'bar'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'bar')
finally:
platform._uname_cache = None
def test_java_ver(self):
res = platform.java_ver()
if sys.platform == 'java':
self.assertTrue(all(res))
def test_win32_ver(self):
res = platform.win32_ver()
def test_mac_ver(self):
res = platform.mac_ver()
if platform.uname().system == 'Darwin':
# We're on a MacOSX system, check that
# the right version information is returned
fd = os.popen('sw_vers', 'r')
real_ver = None
for ln in fd:
if ln.startswith('ProductVersion:'):
real_ver = ln.strip().split()[-1]
break
fd.close()
self.assertFalse(real_ver is None)
result_list = res[0].split('.')
expect_list = real_ver.split('.')
len_diff = len(result_list) - len(expect_list)
# On Snow Leopard, sw_vers reports 10.6.0 as 10.6
if len_diff > 0:
expect_list.extend(['0'] * len_diff)
self.assertEqual(result_list, expect_list)
# res[1] claims to contain
# (version, dev_stage, non_release_version)
# That information is no longer available
self.assertEqual(res[1], ('', '', ''))
if sys.byteorder == 'little':
self.assertIn(res[2], ('i386', 'x86_64'))
else:
self.assertEqual(res[2], 'PowerPC')
@unittest.skipUnless(sys.platform == 'darwin', "OSX only test")
def test_mac_ver_with_fork(self):
# Issue7895: platform.mac_ver() crashes when using fork without exec
#
# This test checks that the fix for that issue works.
#
pid = os.fork()
if pid == 0:
# child
info = platform.mac_ver()
os._exit(0)
else:
# parent
cpid, sts = os.waitpid(pid, 0)
self.assertEqual(cpid, pid)
self.assertEqual(sts, 0)
def test_dist(self):
with warnings.catch_warnings():
warnings.filterwarnings(
'ignore',
r'dist\(\) and linux_distribution\(\) '
'functions are deprecated .*',
PendingDeprecationWarning,
)
res = platform.dist()
def test_libc_ver(self):
if os.path.isdir(sys.executable) and \
os.path.exists(sys.executable+'.exe'):
# Cygwin horror
executable = sys.executable + '.exe'
else:
executable = sys.executable
res = platform.libc_ver(executable)
self.addCleanup(support.unlink, support.TESTFN)
with open(support.TESTFN, 'wb') as f:
f.write(b'x'*(16384-10))
f.write(b'GLIBC_1.23.4\0GLIBC_1.9\0GLIBC_1.21\0')
self.assertEqual(platform.libc_ver(support.TESTFN),
('glibc', '1.23.4'))
@support.cpython_only
def test__comparable_version(self):
from platform import _comparable_version as V
self.assertEqual(V('1.2.3'), V('1.2.3'))
self.assertLess(V('1.2.3'), V('1.2.10'))
self.assertEqual(V('1.2.3.4'), V('1_2-3+4'))
self.assertLess(V('1.2spam'), V('1.2dev'))
self.assertLess(V('1.2dev'), V('1.2alpha'))
self.assertLess(V('1.2dev'), V('1.2a'))
self.assertLess(V('1.2alpha'), V('1.2beta'))
self.assertLess(V('1.2a'), V('1.2b'))
self.assertLess(V('1.2beta'), V('1.2c'))
self.assertLess(V('1.2b'), V('1.2c'))
self.assertLess(V('1.2c'), V('1.2RC'))
self.assertLess(V('1.2c'), V('1.2rc'))
self.assertLess(V('1.2RC'), V('1.2.0'))
self.assertLess(V('1.2rc'), V('1.2.0'))
self.assertLess(V('1.2.0'), V('1.2pl'))
self.assertLess(V('1.2.0'), V('1.2p'))
self.assertLess(V('1.5.1'), V('1.5.2b2'))
self.assertLess(V('3.10a'), V('161'))
self.assertEqual(V('8.02'), V('8.02'))
self.assertLess(V('3.4j'), V('1996.07.12'))
self.assertLess(V('3.1.1.6'), V('3.2.pl0'))
self.assertLess(V('2g6'), V('11g'))
self.assertLess(V('0.9'), V('2.2'))
self.assertLess(V('1.2'), V('1.2.1'))
self.assertLess(V('1.1'), V('1.2.2'))
self.assertLess(V('1.1'), V('1.2'))
self.assertLess(V('1.2.1'), V('1.2.2'))
self.assertLess(V('1.2'), V('1.2.2'))
self.assertLess(V('0.4'), V('0.4.0'))
self.assertLess(V('1.13++'), V('5.5.kw'))
self.assertLess(V('0.960923'), V('2.2beta29'))
def test_parse_release_file(self):
for input, output in (
# Examples of release file contents:
('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64')),
('SUSE LINUX 10.1 (X86-64)', ('SUSE LINUX ', '10.1', 'X86-64')),
('SUSE LINUX 10.1 (i586)', ('SUSE LINUX ', '10.1', 'i586')),
('Fedora Core release 5 (Bordeaux)', ('Fedora Core', '5', 'Bordeaux')),
('Red Hat Linux release 8.0 (Psyche)', ('Red Hat Linux', '8.0', 'Psyche')),
('Red Hat Linux release 9 (Shrike)', ('Red Hat Linux', '9', 'Shrike')),
('Red Hat Enterprise Linux release 4 (Nahant)', ('Red Hat Enterprise Linux', '4', 'Nahant')),
('CentOS release 4', ('CentOS', '4', None)),
('Rocks release 4.2.1 (Cydonia)', ('Rocks', '4.2.1', 'Cydonia')),
('', ('', '', '')), # If there's nothing there.
):
self.assertEqual(platform._parse_release_file(input), output)
def test_popen(self):
mswindows = (sys.platform == "win32")
if mswindows:
command = '"{}" -c "print(\'Hello\')"'.format(sys.executable)
else:
command = "'{}' -c 'print(\"Hello\")'".format(sys.executable)
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
with platform.popen(command) as stdout:
hello = stdout.read().strip()
stdout.close()
self.assertEqual(hello, "Hello")
data = 'plop'
if mswindows:
command = '"{}" -c "import sys; data=sys.stdin.read(); exit(len(data))"'
else:
command = "'{}' -c 'import sys; data=sys.stdin.read(); exit(len(data))'"
command = command.format(sys.executable)
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
with platform.popen(command, 'w') as stdin:
stdout = stdin.write(data)
ret = stdin.close()
self.assertIsNotNone(ret)
if os.name == 'nt':
returncode = ret
else:
returncode = ret >> 8
self.assertEqual(returncode, len(data))
def test_linux_distribution_encoding(self):
# Issue #17429
with tempfile.TemporaryDirectory() as tempdir:
filename = os.path.join(tempdir, 'fedora-release')
with open(filename, 'w', encoding='utf-8') as f:
f.write('Fedora release 19 (Schr\xf6dinger\u2019s Cat)\n')
with mock.patch('platform._UNIXCONFDIR', tempdir):
with warnings.catch_warnings():
warnings.filterwarnings(
'ignore',
r'dist\(\) and linux_distribution\(\) '
'functions are deprecated .*',
PendingDeprecationWarning,
)
distname, version, distid = platform.linux_distribution()
self.assertEqual(distname, 'Fedora')
self.assertEqual(version, '19')
self.assertEqual(distid, 'Schr\xf6dinger\u2019s Cat')
class DeprecationTest(unittest.TestCase):
def test_dist_deprecation(self):
with self.assertWarns(PendingDeprecationWarning) as cm:
platform.dist()
self.assertEqual(str(cm.warning),
'dist() and linux_distribution() functions are '
'deprecated in Python 3.5')
def test_linux_distribution_deprecation(self):
with self.assertWarns(PendingDeprecationWarning) as cm:
platform.linux_distribution()
self.assertEqual(str(cm.warning),
'dist() and linux_distribution() functions are '
'deprecated in Python 3.5')
if __name__ == '__main__':
unittest.main()
| 17,058 | 419 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_extcall.py |
"""Doctest for method/function calls.
We're going the use these types for extra testing
>>> from collections import UserList
>>> from collections import UserDict
We're defining four helper functions
>>> def e(a,b):
... print(a, b)
>>> def f(*a, **k):
... print(a, support.sortdict(k))
>>> def g(x, *y, **z):
... print(x, y, support.sortdict(z))
>>> def h(j=1, a=2, h=3):
... print(j, a, h)
Argument list examples
>>> f()
() {}
>>> f(1)
(1,) {}
>>> f(1, 2)
(1, 2) {}
>>> f(1, 2, 3)
(1, 2, 3) {}
>>> f(1, 2, 3, *(4, 5))
(1, 2, 3, 4, 5) {}
>>> f(1, 2, 3, *[4, 5])
(1, 2, 3, 4, 5) {}
>>> f(*[1, 2, 3], 4, 5)
(1, 2, 3, 4, 5) {}
>>> f(1, 2, 3, *UserList([4, 5]))
(1, 2, 3, 4, 5) {}
>>> f(1, 2, 3, *[4, 5], *[6, 7])
(1, 2, 3, 4, 5, 6, 7) {}
>>> f(1, *[2, 3], 4, *[5, 6], 7)
(1, 2, 3, 4, 5, 6, 7) {}
>>> f(*UserList([1, 2]), *UserList([3, 4]), 5, *UserList([6, 7]))
(1, 2, 3, 4, 5, 6, 7) {}
Here we add keyword arguments
>>> f(1, 2, 3, **{'a':4, 'b':5})
(1, 2, 3) {'a': 4, 'b': 5}
>>> f(1, 2, **{'a': -1, 'b': 5}, **{'a': 4, 'c': 6})
Traceback (most recent call last):
...
TypeError: f() got multiple values for keyword argument 'a'
>>> f(1, 2, **{'a': -1, 'b': 5}, a=4, c=6)
Traceback (most recent call last):
...
TypeError: f() got multiple values for keyword argument 'a'
>>> f(1, 2, a=3, **{'a': 4}, **{'a': 5})
Traceback (most recent call last):
...
TypeError: f() got multiple values for keyword argument 'a'
>>> f(1, 2, 3, *[4, 5], **{'a':6, 'b':7})
(1, 2, 3, 4, 5) {'a': 6, 'b': 7}
>>> f(1, 2, 3, x=4, y=5, *(6, 7), **{'a':8, 'b': 9})
(1, 2, 3, 6, 7) {'a': 8, 'b': 9, 'x': 4, 'y': 5}
>>> f(1, 2, 3, *[4, 5], **{'c': 8}, **{'a':6, 'b':7})
(1, 2, 3, 4, 5) {'a': 6, 'b': 7, 'c': 8}
>>> f(1, 2, 3, *(4, 5), x=6, y=7, **{'a':8, 'b': 9})
(1, 2, 3, 4, 5) {'a': 8, 'b': 9, 'x': 6, 'y': 7}
>>> f(1, 2, 3, **UserDict(a=4, b=5))
(1, 2, 3) {'a': 4, 'b': 5}
>>> f(1, 2, 3, *(4, 5), **UserDict(a=6, b=7))
(1, 2, 3, 4, 5) {'a': 6, 'b': 7}
>>> f(1, 2, 3, x=4, y=5, *(6, 7), **UserDict(a=8, b=9))
(1, 2, 3, 6, 7) {'a': 8, 'b': 9, 'x': 4, 'y': 5}
>>> f(1, 2, 3, *(4, 5), x=6, y=7, **UserDict(a=8, b=9))
(1, 2, 3, 4, 5) {'a': 8, 'b': 9, 'x': 6, 'y': 7}
Examples with invalid arguments (TypeErrors). We're also testing the function
names in the exception messages.
Verify clearing of SF bug #733667
>>> e(c=4)
Traceback (most recent call last):
...
TypeError: e() got an unexpected keyword argument 'c'
>>> g()
Traceback (most recent call last):
...
TypeError: g() missing 1 required positional argument: 'x'
>>> g(*())
Traceback (most recent call last):
...
TypeError: g() missing 1 required positional argument: 'x'
>>> g(*(), **{})
Traceback (most recent call last):
...
TypeError: g() missing 1 required positional argument: 'x'
>>> g(1)
1 () {}
>>> g(1, 2)
1 (2,) {}
>>> g(1, 2, 3)
1 (2, 3) {}
>>> g(1, 2, 3, *(4, 5))
1 (2, 3, 4, 5) {}
>>> class Nothing: pass
...
>>> g(*Nothing())
Traceback (most recent call last):
...
TypeError: g() argument after * must be an iterable, not Nothing
>>> class Nothing:
... def __len__(self): return 5
...
>>> g(*Nothing())
Traceback (most recent call last):
...
TypeError: g() argument after * must be an iterable, not Nothing
>>> class Nothing():
... def __len__(self): return 5
... def __getitem__(self, i):
... if i<3: return i
... else: raise IndexError(i)
...
>>> g(*Nothing())
0 (1, 2) {}
>>> class Nothing:
... def __init__(self): self.c = 0
... def __iter__(self): return self
... def __next__(self):
... if self.c == 4:
... raise StopIteration
... c = self.c
... self.c += 1
... return c
...
>>> g(*Nothing())
0 (1, 2, 3) {}
Check for issue #4806: Does a TypeError in a generator get propagated with the
right error message? (Also check with other iterables.)
>>> def broken(): raise TypeError("myerror")
...
>>> g(*(broken() for i in range(1)))
Traceback (most recent call last):
...
TypeError: myerror
>>> g(*range(1), *(broken() for i in range(1)))
Traceback (most recent call last):
...
TypeError: myerror
>>> class BrokenIterable1:
... def __iter__(self):
... raise TypeError('myerror')
...
>>> g(*BrokenIterable1())
Traceback (most recent call last):
...
TypeError: myerror
>>> g(*range(1), *BrokenIterable1())
Traceback (most recent call last):
...
TypeError: myerror
>>> class BrokenIterable2:
... def __iter__(self):
... yield 0
... raise TypeError('myerror')
...
>>> g(*BrokenIterable2())
Traceback (most recent call last):
...
TypeError: myerror
>>> g(*range(1), *BrokenIterable2())
Traceback (most recent call last):
...
TypeError: myerror
>>> class BrokenSequence:
... def __getitem__(self, idx):
... raise TypeError('myerror')
...
>>> g(*BrokenSequence())
Traceback (most recent call last):
...
TypeError: myerror
>>> g(*range(1), *BrokenSequence())
Traceback (most recent call last):
...
TypeError: myerror
Make sure that the function doesn't stomp the dictionary
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> d2 = d.copy()
>>> g(1, d=4, **d)
1 () {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> d == d2
True
What about willful misconduct?
>>> def saboteur(**kw):
... kw['x'] = 'm'
... return kw
>>> d = {}
>>> kw = saboteur(a=1, **d)
>>> d
{}
>>> g(1, 2, 3, **{'x': 4, 'y': 5})
Traceback (most recent call last):
...
TypeError: g() got multiple values for argument 'x'
>>> f(**{1:2})
Traceback (most recent call last):
...
TypeError: f() keywords must be strings
>>> h(**{'e': 2})
Traceback (most recent call last):
...
TypeError: h() got an unexpected keyword argument 'e'
>>> h(*h)
Traceback (most recent call last):
...
TypeError: h() argument after * must be an iterable, not function
>>> h(1, *h)
Traceback (most recent call last):
...
TypeError: h() argument after * must be an iterable, not function
>>> h(*[1], *h)
Traceback (most recent call last):
...
TypeError: h() argument after * must be an iterable, not function
>>> dir(*h)
Traceback (most recent call last):
...
TypeError: dir() argument after * must be an iterable, not function
>>> None(*h)
Traceback (most recent call last):
...
TypeError: NoneType object argument after * must be an iterable, \
not function
>>> h(**h)
Traceback (most recent call last):
...
TypeError: h() argument after ** must be a mapping, not function
>>> h(**[])
Traceback (most recent call last):
...
TypeError: h() argument after ** must be a mapping, not list
>>> h(a=1, **h)
Traceback (most recent call last):
...
TypeError: h() argument after ** must be a mapping, not function
>>> h(a=1, **[])
Traceback (most recent call last):
...
TypeError: h() argument after ** must be a mapping, not list
>>> h(**{'a': 1}, **h)
Traceback (most recent call last):
...
TypeError: h() argument after ** must be a mapping, not function
>>> h(**{'a': 1}, **[])
Traceback (most recent call last):
...
TypeError: h() argument after ** must be a mapping, not list
>>> dir(**h)
Traceback (most recent call last):
...
TypeError: dir() argument after ** must be a mapping, not function
>>> None(**h)
Traceback (most recent call last):
...
TypeError: NoneType object argument after ** must be a mapping, \
not function
>>> dir(b=1, **{'b': 1})
Traceback (most recent call last):
...
TypeError: dir() got multiple values for keyword argument 'b'
Another helper function
>>> def f2(*a, **b):
... return a, b
>>> d = {}
>>> for i in range(512):
... key = 'k%d' % i
... d[key] = i
>>> a, b = f2(1, *(2,3), **d)
>>> len(a), len(b), b == d
(3, 512, True)
>>> class Foo:
... def method(self, arg1, arg2):
... return arg1+arg2
>>> x = Foo()
>>> Foo.method(*(x, 1, 2))
3
>>> Foo.method(x, *(1, 2))
3
>>> Foo.method(*(1, 2, 3))
5
>>> Foo.method(1, *[2, 3])
5
A PyCFunction that takes only positional parameters should allow an
empty keyword dictionary to pass without a complaint, but raise a
TypeError if te dictionary is not empty
>>> try:
... silence = id(1, *{})
... True
... except:
... False
True
>>> id(1, **{'foo': 1})
Traceback (most recent call last):
...
TypeError: id() takes no keyword arguments
A corner case of keyword dictionary items being deleted during
the function call setup. See <http://bugs.python.org/issue2016>.
>>> class Name(str):
... def __eq__(self, other):
... try:
... del x[self]
... except KeyError:
... pass
... return str.__eq__(self, other)
... def __hash__(self):
... return str.__hash__(self)
>>> x = {Name("a"):1, Name("b"):2}
>>> def f(a, b):
... print(a,b)
>>> f(**x)
1 2
Too many arguments:
>>> def f(): pass
>>> f(1)
Traceback (most recent call last):
...
TypeError: f() takes 0 positional arguments but 1 was given
>>> def f(a): pass
>>> f(1, 2)
Traceback (most recent call last):
...
TypeError: f() takes 1 positional argument but 2 were given
>>> def f(a, b=1): pass
>>> f(1, 2, 3)
Traceback (most recent call last):
...
TypeError: f() takes from 1 to 2 positional arguments but 3 were given
>>> def f(*, kw): pass
>>> f(1, kw=3)
Traceback (most recent call last):
...
TypeError: f() takes 0 positional arguments but 1 positional argument (and 1 keyword-only argument) were given
>>> def f(*, kw, b): pass
>>> f(1, 2, 3, b=3, kw=3)
Traceback (most recent call last):
...
TypeError: f() takes 0 positional arguments but 3 positional arguments (and 2 keyword-only arguments) were given
>>> def f(a, b=2, *, kw): pass
>>> f(2, 3, 4, kw=4)
Traceback (most recent call last):
...
TypeError: f() takes from 1 to 2 positional arguments but 3 positional arguments (and 1 keyword-only argument) were given
Too few and missing arguments:
>>> def f(a): pass
>>> f()
Traceback (most recent call last):
...
TypeError: f() missing 1 required positional argument: 'a'
>>> def f(a, b): pass
>>> f()
Traceback (most recent call last):
...
TypeError: f() missing 2 required positional arguments: 'a' and 'b'
>>> def f(a, b, c): pass
>>> f()
Traceback (most recent call last):
...
TypeError: f() missing 3 required positional arguments: 'a', 'b', and 'c'
>>> def f(a, b, c, d, e): pass
>>> f()
Traceback (most recent call last):
...
TypeError: f() missing 5 required positional arguments: 'a', 'b', 'c', 'd', and 'e'
>>> def f(a, b=4, c=5, d=5): pass
>>> f(c=12, b=9)
Traceback (most recent call last):
...
TypeError: f() missing 1 required positional argument: 'a'
Same with keyword only args:
>>> def f(*, w): pass
>>> f()
Traceback (most recent call last):
...
TypeError: f() missing 1 required keyword-only argument: 'w'
>>> def f(*, a, b, c, d, e): pass
>>> f()
Traceback (most recent call last):
...
TypeError: f() missing 5 required keyword-only arguments: 'a', 'b', 'c', 'd', and 'e'
"""
import sys
from test import support
def test_main():
support.run_doctest(sys.modules[__name__], True)
if __name__ == '__main__':
test_main()
| 12,380 | 466 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/badsyntax_future7.py | """This is a test"""
from __future__ import nested_scopes; import string; from __future__ import \
nested_scopes
def f(x):
def g(y):
return x + y
return g
result = f(2)(4)
| 196 | 12 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_abc.py | # Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Unit tests for abc.py."""
import unittest
from test import support
import abc
from inspect import isabstract
class TestLegacyAPI(unittest.TestCase):
def test_abstractproperty_basics(self):
@abc.abstractproperty
def foo(self): pass
self.assertTrue(foo.__isabstractmethod__)
def bar(self): pass
self.assertFalse(hasattr(bar, "__isabstractmethod__"))
class C(metaclass=abc.ABCMeta):
@abc.abstractproperty
def foo(self): return 3
self.assertRaises(TypeError, C)
class D(C):
@property
def foo(self): return super().foo
self.assertEqual(D().foo, 3)
self.assertFalse(getattr(D.foo, "__isabstractmethod__", False))
def test_abstractclassmethod_basics(self):
@abc.abstractclassmethod
def foo(cls): pass
self.assertTrue(foo.__isabstractmethod__)
@classmethod
def bar(cls): pass
self.assertFalse(getattr(bar, "__isabstractmethod__", False))
class C(metaclass=abc.ABCMeta):
@abc.abstractclassmethod
def foo(cls): return cls.__name__
self.assertRaises(TypeError, C)
class D(C):
@classmethod
def foo(cls): return super().foo()
self.assertEqual(D.foo(), 'D')
self.assertEqual(D().foo(), 'D')
def test_abstractstaticmethod_basics(self):
@abc.abstractstaticmethod
def foo(): pass
self.assertTrue(foo.__isabstractmethod__)
@staticmethod
def bar(): pass
self.assertFalse(getattr(bar, "__isabstractmethod__", False))
class C(metaclass=abc.ABCMeta):
@abc.abstractstaticmethod
def foo(): return 3
self.assertRaises(TypeError, C)
class D(C):
@staticmethod
def foo(): return 4
self.assertEqual(D.foo(), 4)
self.assertEqual(D().foo(), 4)
class TestABC(unittest.TestCase):
def test_ABC_helper(self):
# create an ABC using the helper class and perform basic checks
class C(abc.ABC):
@classmethod
@abc.abstractmethod
def foo(cls): return cls.__name__
self.assertEqual(type(C), abc.ABCMeta)
self.assertRaises(TypeError, C)
class D(C):
@classmethod
def foo(cls): return super().foo()
self.assertEqual(D.foo(), 'D')
def test_abstractmethod_basics(self):
@abc.abstractmethod
def foo(self): pass
self.assertTrue(foo.__isabstractmethod__)
def bar(self): pass
self.assertFalse(hasattr(bar, "__isabstractmethod__"))
def test_abstractproperty_basics(self):
@property
@abc.abstractmethod
def foo(self): pass
self.assertTrue(foo.__isabstractmethod__)
def bar(self): pass
self.assertFalse(getattr(bar, "__isabstractmethod__", False))
class C(metaclass=abc.ABCMeta):
@property
@abc.abstractmethod
def foo(self): return 3
self.assertRaises(TypeError, C)
class D(C):
@C.foo.getter
def foo(self): return super().foo
self.assertEqual(D().foo, 3)
def test_abstractclassmethod_basics(self):
@classmethod
@abc.abstractmethod
def foo(cls): pass
self.assertTrue(foo.__isabstractmethod__)
@classmethod
def bar(cls): pass
self.assertFalse(getattr(bar, "__isabstractmethod__", False))
class C(metaclass=abc.ABCMeta):
@classmethod
@abc.abstractmethod
def foo(cls): return cls.__name__
self.assertRaises(TypeError, C)
class D(C):
@classmethod
def foo(cls): return super().foo()
self.assertEqual(D.foo(), 'D')
self.assertEqual(D().foo(), 'D')
def test_abstractstaticmethod_basics(self):
@staticmethod
@abc.abstractmethod
def foo(): pass
self.assertTrue(foo.__isabstractmethod__)
@staticmethod
def bar(): pass
self.assertFalse(getattr(bar, "__isabstractmethod__", False))
class C(metaclass=abc.ABCMeta):
@staticmethod
@abc.abstractmethod
def foo(): return 3
self.assertRaises(TypeError, C)
class D(C):
@staticmethod
def foo(): return 4
self.assertEqual(D.foo(), 4)
self.assertEqual(D().foo(), 4)
def test_abstractmethod_integration(self):
for abstractthing in [abc.abstractmethod, abc.abstractproperty,
abc.abstractclassmethod,
abc.abstractstaticmethod]:
class C(metaclass=abc.ABCMeta):
@abstractthing
def foo(self): pass # abstract
def bar(self): pass # concrete
self.assertEqual(C.__abstractmethods__, {"foo"})
self.assertRaises(TypeError, C) # because foo is abstract
self.assertTrue(isabstract(C))
class D(C):
def bar(self): pass # concrete override of concrete
self.assertEqual(D.__abstractmethods__, {"foo"})
self.assertRaises(TypeError, D) # because foo is still abstract
self.assertTrue(isabstract(D))
class E(D):
def foo(self): pass
self.assertEqual(E.__abstractmethods__, set())
E() # now foo is concrete, too
self.assertFalse(isabstract(E))
class F(E):
@abstractthing
def bar(self): pass # abstract override of concrete
self.assertEqual(F.__abstractmethods__, {"bar"})
self.assertRaises(TypeError, F) # because bar is abstract now
self.assertTrue(isabstract(F))
def test_descriptors_with_abstractmethod(self):
class C(metaclass=abc.ABCMeta):
@property
@abc.abstractmethod
def foo(self): return 3
@foo.setter
@abc.abstractmethod
def foo(self, val): pass
self.assertRaises(TypeError, C)
class D(C):
@C.foo.getter
def foo(self): return super().foo
self.assertRaises(TypeError, D)
class E(D):
@D.foo.setter
def foo(self, val): pass
self.assertEqual(E().foo, 3)
# check that the property's __isabstractmethod__ descriptor does the
# right thing when presented with a value that fails truth testing:
class NotBool(object):
def __bool__(self):
raise ValueError()
__len__ = __bool__
with self.assertRaises(ValueError):
class F(C):
def bar(self):
pass
bar.__isabstractmethod__ = NotBool()
foo = property(bar)
def test_customdescriptors_with_abstractmethod(self):
class Descriptor:
def __init__(self, fget, fset=None):
self._fget = fget
self._fset = fset
def getter(self, callable):
return Descriptor(callable, self._fget)
def setter(self, callable):
return Descriptor(self._fget, callable)
@property
def __isabstractmethod__(self):
return (getattr(self._fget, '__isabstractmethod__', False)
or getattr(self._fset, '__isabstractmethod__', False))
class C(metaclass=abc.ABCMeta):
@Descriptor
@abc.abstractmethod
def foo(self): return 3
@foo.setter
@abc.abstractmethod
def foo(self, val): pass
self.assertRaises(TypeError, C)
class D(C):
@C.foo.getter
def foo(self): return super().foo
self.assertRaises(TypeError, D)
class E(D):
@D.foo.setter
def foo(self, val): pass
self.assertFalse(E.foo.__isabstractmethod__)
def test_metaclass_abc(self):
# Metaclasses can be ABCs, too.
class A(metaclass=abc.ABCMeta):
@abc.abstractmethod
def x(self):
pass
self.assertEqual(A.__abstractmethods__, {"x"})
class meta(type, A):
def x(self):
return 1
class C(metaclass=meta):
pass
def test_registration_basics(self):
class A(metaclass=abc.ABCMeta):
pass
class B(object):
pass
b = B()
self.assertFalse(issubclass(B, A))
self.assertFalse(issubclass(B, (A,)))
self.assertNotIsInstance(b, A)
self.assertNotIsInstance(b, (A,))
B1 = A.register(B)
self.assertTrue(issubclass(B, A))
self.assertTrue(issubclass(B, (A,)))
self.assertIsInstance(b, A)
self.assertIsInstance(b, (A,))
self.assertIs(B1, B)
class C(B):
pass
c = C()
self.assertTrue(issubclass(C, A))
self.assertTrue(issubclass(C, (A,)))
self.assertIsInstance(c, A)
self.assertIsInstance(c, (A,))
def test_register_as_class_deco(self):
class A(metaclass=abc.ABCMeta):
pass
@A.register
class B(object):
pass
b = B()
self.assertTrue(issubclass(B, A))
self.assertTrue(issubclass(B, (A,)))
self.assertIsInstance(b, A)
self.assertIsInstance(b, (A,))
@A.register
class C(B):
pass
c = C()
self.assertTrue(issubclass(C, A))
self.assertTrue(issubclass(C, (A,)))
self.assertIsInstance(c, A)
self.assertIsInstance(c, (A,))
self.assertIs(C, A.register(C))
def test_isinstance_invalidation(self):
class A(metaclass=abc.ABCMeta):
pass
class B:
pass
b = B()
self.assertFalse(isinstance(b, A))
self.assertFalse(isinstance(b, (A,)))
token_old = abc.get_cache_token()
A.register(B)
token_new = abc.get_cache_token()
self.assertNotEqual(token_old, token_new)
self.assertTrue(isinstance(b, A))
self.assertTrue(isinstance(b, (A,)))
def test_registration_builtins(self):
class A(metaclass=abc.ABCMeta):
pass
A.register(int)
self.assertIsInstance(42, A)
self.assertIsInstance(42, (A,))
self.assertTrue(issubclass(int, A))
self.assertTrue(issubclass(int, (A,)))
class B(A):
pass
B.register(str)
class C(str): pass
self.assertIsInstance("", A)
self.assertIsInstance("", (A,))
self.assertTrue(issubclass(str, A))
self.assertTrue(issubclass(str, (A,)))
self.assertTrue(issubclass(C, A))
self.assertTrue(issubclass(C, (A,)))
def test_registration_edge_cases(self):
class A(metaclass=abc.ABCMeta):
pass
A.register(A) # should pass silently
class A1(A):
pass
self.assertRaises(RuntimeError, A1.register, A) # cycles not allowed
class B(object):
pass
A1.register(B) # ok
A1.register(B) # should pass silently
class C(A):
pass
A.register(C) # should pass silently
self.assertRaises(RuntimeError, C.register, A) # cycles not allowed
C.register(B) # ok
def test_register_non_class(self):
class A(metaclass=abc.ABCMeta):
pass
self.assertRaisesRegex(TypeError, "Can only register classes",
A.register, 4)
def test_registration_transitiveness(self):
class A(metaclass=abc.ABCMeta):
pass
self.assertTrue(issubclass(A, A))
self.assertTrue(issubclass(A, (A,)))
class B(metaclass=abc.ABCMeta):
pass
self.assertFalse(issubclass(A, B))
self.assertFalse(issubclass(A, (B,)))
self.assertFalse(issubclass(B, A))
self.assertFalse(issubclass(B, (A,)))
class C(metaclass=abc.ABCMeta):
pass
A.register(B)
class B1(B):
pass
self.assertTrue(issubclass(B1, A))
self.assertTrue(issubclass(B1, (A,)))
class C1(C):
pass
B1.register(C1)
self.assertFalse(issubclass(C, B))
self.assertFalse(issubclass(C, (B,)))
self.assertFalse(issubclass(C, B1))
self.assertFalse(issubclass(C, (B1,)))
self.assertTrue(issubclass(C1, A))
self.assertTrue(issubclass(C1, (A,)))
self.assertTrue(issubclass(C1, B))
self.assertTrue(issubclass(C1, (B,)))
self.assertTrue(issubclass(C1, B1))
self.assertTrue(issubclass(C1, (B1,)))
C1.register(int)
class MyInt(int):
pass
self.assertTrue(issubclass(MyInt, A))
self.assertTrue(issubclass(MyInt, (A,)))
self.assertIsInstance(42, A)
self.assertIsInstance(42, (A,))
def test_all_new_methods_are_called(self):
class A(metaclass=abc.ABCMeta):
pass
class B(object):
counter = 0
def __new__(cls):
B.counter += 1
return super().__new__(cls)
class C(A, B):
pass
self.assertEqual(B.counter, 0)
C()
self.assertEqual(B.counter, 1)
class TestABCWithInitSubclass(unittest.TestCase):
def test_works_with_init_subclass(self):
saved_kwargs = {}
class ReceivesClassKwargs:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__()
saved_kwargs.update(kwargs)
class Receiver(ReceivesClassKwargs, abc.ABC, x=1, y=2, z=3):
pass
self.assertEqual(saved_kwargs, dict(x=1, y=2, z=3))
if __name__ == "__main__":
unittest.main()
| 14,088 | 421 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_grp.py | """Test script for the grp module."""
import unittest
from test import support
grp = support.import_module('grp')
class GroupDatabaseTestCase(unittest.TestCase):
def check_value(self, value):
# check that a grp tuple has the entries and
# attributes promised by the docs
self.assertEqual(len(value), 4)
self.assertEqual(value[0], value.gr_name)
self.assertIsInstance(value.gr_name, str)
self.assertEqual(value[1], value.gr_passwd)
self.assertIsInstance(value.gr_passwd, str)
self.assertEqual(value[2], value.gr_gid)
self.assertIsInstance(value.gr_gid, int)
self.assertEqual(value[3], value.gr_mem)
self.assertIsInstance(value.gr_mem, list)
def test_values(self):
entries = grp.getgrall()
for e in entries:
self.check_value(e)
def test_values_extended(self):
entries = grp.getgrall()
if len(entries) > 1000: # Huge group file (NIS?) -- skip the rest
self.skipTest('huge group file, extended test skipped')
for e in entries:
e2 = grp.getgrgid(e.gr_gid)
self.check_value(e2)
self.assertEqual(e2.gr_gid, e.gr_gid)
name = e.gr_name
if name.startswith('+') or name.startswith('-'):
# NIS-related entry
continue
e2 = grp.getgrnam(name)
self.check_value(e2)
# There are instances where getgrall() returns group names in
# lowercase while getgrgid() returns proper casing.
# Discovered on Ubuntu 5.04 (custom).
self.assertEqual(e2.gr_name.lower(), name.lower())
def test_errors(self):
self.assertRaises(TypeError, grp.getgrgid)
self.assertRaises(TypeError, grp.getgrnam)
self.assertRaises(TypeError, grp.getgrall, 42)
# embedded null character
self.assertRaises(ValueError, grp.getgrnam, 'a\x00b')
# try to get some errors
bynames = {}
bygids = {}
for (n, p, g, mem) in grp.getgrall():
if not n or n == '+':
continue # skip NIS entries etc.
bynames[n] = g
bygids[g] = n
allnames = list(bynames.keys())
namei = 0
fakename = allnames[namei]
while fakename in bynames:
chars = list(fakename)
for i in range(len(chars)):
if chars[i] == 'z':
chars[i] = 'A'
break
elif chars[i] == 'Z':
continue
else:
chars[i] = chr(ord(chars[i]) + 1)
break
else:
namei = namei + 1
try:
fakename = allnames[namei]
except IndexError:
# should never happen... if so, just forget it
break
fakename = ''.join(chars)
self.assertRaises(KeyError, grp.getgrnam, fakename)
# Choose a non-existent gid.
fakegid = 4127
while fakegid in bygids:
fakegid = (fakegid * 3) % 0x10000
self.assertRaises(KeyError, grp.getgrgid, fakegid)
def test_noninteger_gid(self):
entries = grp.getgrall()
if not entries:
self.skipTest('no groups')
# Choose an existent gid.
gid = entries[0][2]
self.assertWarns(DeprecationWarning, grp.getgrgid, float(gid))
self.assertWarns(DeprecationWarning, grp.getgrgid, str(gid))
if __name__ == "__main__":
unittest.main()
| 3,628 | 109 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_compileall.py | import sys
import compileall
import importlib.util
import test.test_importlib.util
import os
import pathlib
import py_compile
import shutil
import struct
import tempfile
import time
import unittest
import io
from unittest import mock, skipUnless
try:
from concurrent.futures import ProcessPoolExecutor
_have_multiprocessing = True
except ImportError:
_have_multiprocessing = False
from test import support
from test.support import script_helper
class CompileallTests(unittest.TestCase):
def setUp(self):
self.directory = tempfile.mkdtemp()
self.source_path = os.path.join(self.directory, '_test.py')
self.bc_path = importlib.util.cache_from_source(self.source_path)
with open(self.source_path, 'w') as file:
file.write('x = 123\n')
self.source_path2 = os.path.join(self.directory, '_test2.py')
self.bc_path2 = importlib.util.cache_from_source(self.source_path2)
shutil.copyfile(self.source_path, self.source_path2)
self.subdirectory = os.path.join(self.directory, '_subdir')
os.mkdir(self.subdirectory)
self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
shutil.copyfile(self.source_path, self.source_path3)
def tearDown(self):
shutil.rmtree(self.directory)
def add_bad_source_file(self):
self.bad_source_path = os.path.join(self.directory, '_test_bad.py')
with open(self.bad_source_path, 'w') as file:
file.write('x (\n')
def data(self):
with open(self.bc_path, 'rb') as file:
data = file.read(8)
mtime = int(os.stat(self.source_path).st_mtime)
compare = struct.pack('<4sl', importlib.util.MAGIC_NUMBER, mtime)
return data, compare
@unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
def recreation_check(self, metadata):
"""Check that compileall recreates bytecode when the new metadata is
used."""
py_compile.compile(self.source_path)
self.assertEqual(*self.data())
with open(self.bc_path, 'rb') as file:
bc = file.read()[len(metadata):]
with open(self.bc_path, 'wb') as file:
file.write(metadata)
file.write(bc)
self.assertNotEqual(*self.data())
compileall.compile_dir(self.directory, force=False, quiet=True)
self.assertTrue(*self.data())
def test_mtime(self):
# Test a change in mtime leads to a new .pyc.
self.recreation_check(struct.pack('<4sl', importlib.util.MAGIC_NUMBER,
1))
def test_magic_number(self):
# Test a change in mtime leads to a new .pyc.
self.recreation_check(b'\0\0\0\0')
def test_compile_files(self):
# Test compiling a single file, and complete directory
for fn in (self.bc_path, self.bc_path2):
try:
os.unlink(fn)
except:
pass
self.assertTrue(compileall.compile_file(self.source_path,
force=False, quiet=True))
self.assertTrue(os.path.isfile(self.bc_path) and
not os.path.isfile(self.bc_path2))
os.unlink(self.bc_path)
self.assertTrue(compileall.compile_dir(self.directory, force=False,
quiet=True))
self.assertTrue(os.path.isfile(self.bc_path) and
os.path.isfile(self.bc_path2))
os.unlink(self.bc_path)
os.unlink(self.bc_path2)
# Test against bad files
self.add_bad_source_file()
self.assertFalse(compileall.compile_file(self.bad_source_path,
force=False, quiet=2))
self.assertFalse(compileall.compile_dir(self.directory,
force=False, quiet=2))
def test_compile_file_pathlike(self):
self.assertFalse(os.path.isfile(self.bc_path))
# we should also test the output
with support.captured_stdout() as stdout:
self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path)))
self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)')
self.assertTrue(os.path.isfile(self.bc_path))
def test_compile_file_pathlike_ddir(self):
self.assertFalse(os.path.isfile(self.bc_path))
self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
ddir=pathlib.Path('ddir_path'),
quiet=2))
self.assertTrue(os.path.isfile(self.bc_path))
def test_compile_path(self):
with test.test_importlib.util.import_state(path=[self.directory]):
self.assertTrue(compileall.compile_path(quiet=2))
with test.test_importlib.util.import_state(path=[self.directory]):
self.add_bad_source_file()
self.assertFalse(compileall.compile_path(skip_curdir=False,
force=True, quiet=2))
def test_no_pycache_in_non_package(self):
# Bug 8563 reported that __pycache__ directories got created by
# compile_file() for non-.py files.
data_dir = os.path.join(self.directory, 'data')
data_file = os.path.join(data_dir, 'file')
os.mkdir(data_dir)
# touch data/file
with open(data_file, 'w'):
pass
compileall.compile_file(data_file)
self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
def test_optimize(self):
# make sure compiling with different optimization settings than the
# interpreter's creates the correct file names
optimize, opt = (1, 1) if __debug__ else (0, '')
compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
cached = importlib.util.cache_from_source(self.source_path,
optimization=opt)
self.assertTrue(os.path.isfile(cached))
cached2 = importlib.util.cache_from_source(self.source_path2,
optimization=opt)
self.assertTrue(os.path.isfile(cached2))
cached3 = importlib.util.cache_from_source(self.source_path3,
optimization=opt)
self.assertTrue(os.path.isfile(cached3))
def test_compile_dir_pathlike(self):
self.assertFalse(os.path.isfile(self.bc_path))
with support.captured_stdout() as stdout:
compileall.compile_dir(pathlib.Path(self.directory))
line = stdout.getvalue().splitlines()[0]
self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)')
self.assertTrue(os.path.isfile(self.bc_path))
@mock.patch('concurrent.futures.ProcessPoolExecutor')
def test_compile_pool_called(self, pool_mock):
compileall.compile_dir(self.directory, quiet=True, workers=5)
self.assertTrue(pool_mock.called)
def test_compile_workers_non_positive(self):
with self.assertRaisesRegex(ValueError,
"workers must be greater or equal to 0"):
compileall.compile_dir(self.directory, workers=-1)
@mock.patch('concurrent.futures.ProcessPoolExecutor')
def test_compile_workers_cpu_count(self, pool_mock):
compileall.compile_dir(self.directory, quiet=True, workers=0)
self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
@mock.patch('concurrent.futures.ProcessPoolExecutor')
@mock.patch('compileall.compile_file')
def test_compile_one_worker(self, compile_file_mock, pool_mock):
compileall.compile_dir(self.directory, quiet=True)
self.assertFalse(pool_mock.called)
self.assertTrue(compile_file_mock.called)
@mock.patch('concurrent.futures.ProcessPoolExecutor', new=None)
@mock.patch('compileall.compile_file')
def test_compile_missing_multiprocessing(self, compile_file_mock):
compileall.compile_dir(self.directory, quiet=True, workers=5)
self.assertTrue(compile_file_mock.called)
class EncodingTest(unittest.TestCase):
"""Issue 6716: compileall should escape source code when printing errors
to stdout."""
def setUp(self):
self.directory = tempfile.mkdtemp()
self.source_path = os.path.join(self.directory, '_test.py')
with open(self.source_path, 'w', encoding='utf-8') as file:
file.write('# -*- coding: utf-8 -*-\n')
file.write('print u"\u20ac"\n')
def tearDown(self):
shutil.rmtree(self.directory)
def test_error(self):
try:
orig_stdout = sys.stdout
sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
compileall.compile_dir(self.directory)
finally:
sys.stdout = orig_stdout
class CommandLineTests(unittest.TestCase):
"""Test compileall's CLI."""
@classmethod
def setUpClass(cls):
for path in filter(os.path.isdir, sys.path):
directory_created = False
directory = pathlib.Path(path) / '__pycache__'
path = directory / 'test.try'
try:
if not directory.is_dir():
directory.mkdir()
directory_created = True
with path.open('w') as file:
file.write('# for test_compileall')
except OSError:
sys_path_writable = False
break
finally:
support.unlink(str(path))
if directory_created:
directory.rmdir()
else:
sys_path_writable = True
cls._sys_path_writable = sys_path_writable
def _skip_if_sys_path_not_writable(self):
if not self._sys_path_writable:
raise unittest.SkipTest('not all entries on sys.path are writable')
def _get_run_args(self, args):
return [*support.optim_args_from_interpreter_flags(),
'-S', '-m', 'compileall',
*args]
def assertRunOK(self, *args, **env_vars):
rc, out, err = script_helper.assert_python_ok(
*self._get_run_args(args), **env_vars)
self.assertEqual(b'', err)
return out
def assertRunNotOK(self, *args, **env_vars):
rc, out, err = script_helper.assert_python_failure(
*self._get_run_args(args), **env_vars)
return rc, out, err
def assertCompiled(self, fn):
path = importlib.util.cache_from_source(fn)
self.assertTrue(os.path.exists(path))
def assertNotCompiled(self, fn):
path = importlib.util.cache_from_source(fn)
self.assertFalse(os.path.exists(path))
def setUp(self):
self.directory = tempfile.mkdtemp()
self.addCleanup(support.rmtree, self.directory)
self.pkgdir = os.path.join(self.directory, 'foo')
os.mkdir(self.pkgdir)
self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
# Create the __init__.py and a package module.
self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
def test_no_args_compiles_path(self):
# Note that -l is implied for the no args case.
self._skip_if_sys_path_not_writable()
bazfn = script_helper.make_script(self.directory, 'baz', '')
self.assertRunOK(PYTHONPATH=self.directory)
self.assertCompiled(bazfn)
self.assertNotCompiled(self.initfn)
self.assertNotCompiled(self.barfn)
def test_no_args_respects_force_flag(self):
self._skip_if_sys_path_not_writable()
bazfn = script_helper.make_script(self.directory, 'baz', '')
self.assertRunOK(PYTHONPATH=self.directory)
pycpath = importlib.util.cache_from_source(bazfn)
# Set atime/mtime backward to avoid file timestamp resolution issues
os.utime(pycpath, (time.time()-60,)*2)
mtime = os.stat(pycpath).st_mtime
# Without force, no recompilation
self.assertRunOK(PYTHONPATH=self.directory)
mtime2 = os.stat(pycpath).st_mtime
self.assertEqual(mtime, mtime2)
# Now force it.
self.assertRunOK('-f', PYTHONPATH=self.directory)
mtime2 = os.stat(pycpath).st_mtime
self.assertNotEqual(mtime, mtime2)
def test_no_args_respects_quiet_flag(self):
self._skip_if_sys_path_not_writable()
script_helper.make_script(self.directory, 'baz', '')
noisy = self.assertRunOK(PYTHONPATH=self.directory)
self.assertIn(b'Listing ', noisy)
quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
self.assertNotIn(b'Listing ', quiet)
# Ensure that the default behavior of compileall's CLI is to create
# PEP 3147/PEP 488 pyc files.
for name, ext, switch in [
('normal', 'pyc', []),
('optimize', 'opt-1.pyc', ['-O']),
('doubleoptimize', 'opt-2.pyc', ['-OO']),
]:
def f(self, ext=ext, switch=switch):
script_helper.assert_python_ok(*(switch +
['-m', 'compileall', '-q', self.pkgdir]))
# Verify the __pycache__ directory contents.
self.assertTrue(os.path.exists(self.pkgdir_cachedir))
expected = sorted(base.format(sys.implementation.cache_tag, ext)
for base in ('__init__.{}.{}', 'bar.{}.{}'))
self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
# Make sure there are no .pyc files in the source directory.
self.assertFalse([fn for fn in os.listdir(self.pkgdir)
if fn.endswith(ext)])
locals()['test_pep3147_paths_' + name] = f
def test_legacy_paths(self):
# Ensure that with the proper switch, compileall leaves legacy
# pyc files, and no __pycache__ directory.
self.assertRunOK('-b', '-q', self.pkgdir)
# Verify the __pycache__ directory contents.
self.assertFalse(os.path.exists(self.pkgdir_cachedir))
expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
'bar.pyc'])
self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
def test_multiple_runs(self):
# Bug 8527 reported that multiple calls produced empty
# __pycache__/__pycache__ directories.
self.assertRunOK('-q', self.pkgdir)
# Verify the __pycache__ directory contents.
self.assertTrue(os.path.exists(self.pkgdir_cachedir))
cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
self.assertFalse(os.path.exists(cachecachedir))
# Call compileall again.
self.assertRunOK('-q', self.pkgdir)
self.assertTrue(os.path.exists(self.pkgdir_cachedir))
self.assertFalse(os.path.exists(cachecachedir))
def test_force(self):
self.assertRunOK('-q', self.pkgdir)
pycpath = importlib.util.cache_from_source(self.barfn)
# set atime/mtime backward to avoid file timestamp resolution issues
os.utime(pycpath, (time.time()-60,)*2)
mtime = os.stat(pycpath).st_mtime
# without force, no recompilation
self.assertRunOK('-q', self.pkgdir)
mtime2 = os.stat(pycpath).st_mtime
self.assertEqual(mtime, mtime2)
# now force it.
self.assertRunOK('-q', '-f', self.pkgdir)
mtime2 = os.stat(pycpath).st_mtime
self.assertNotEqual(mtime, mtime2)
def test_recursion_control(self):
subpackage = os.path.join(self.pkgdir, 'spam')
os.mkdir(subpackage)
subinitfn = script_helper.make_script(subpackage, '__init__', '')
hamfn = script_helper.make_script(subpackage, 'ham', '')
self.assertRunOK('-q', '-l', self.pkgdir)
self.assertNotCompiled(subinitfn)
self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
self.assertRunOK('-q', self.pkgdir)
self.assertCompiled(subinitfn)
self.assertCompiled(hamfn)
def test_recursion_limit(self):
subpackage = os.path.join(self.pkgdir, 'spam')
subpackage2 = os.path.join(subpackage, 'ham')
subpackage3 = os.path.join(subpackage2, 'eggs')
for pkg in (subpackage, subpackage2, subpackage3):
script_helper.make_pkg(pkg)
subinitfn = os.path.join(subpackage, '__init__.py')
hamfn = script_helper.make_script(subpackage, 'ham', '')
spamfn = script_helper.make_script(subpackage2, 'spam', '')
eggfn = script_helper.make_script(subpackage3, 'egg', '')
self.assertRunOK('-q', '-r 0', self.pkgdir)
self.assertNotCompiled(subinitfn)
self.assertFalse(
os.path.exists(os.path.join(subpackage, '__pycache__')))
self.assertRunOK('-q', '-r 1', self.pkgdir)
self.assertCompiled(subinitfn)
self.assertCompiled(hamfn)
self.assertNotCompiled(spamfn)
self.assertRunOK('-q', '-r 2', self.pkgdir)
self.assertCompiled(subinitfn)
self.assertCompiled(hamfn)
self.assertCompiled(spamfn)
self.assertNotCompiled(eggfn)
self.assertRunOK('-q', '-r 5', self.pkgdir)
self.assertCompiled(subinitfn)
self.assertCompiled(hamfn)
self.assertCompiled(spamfn)
self.assertCompiled(eggfn)
def test_quiet(self):
noisy = self.assertRunOK(self.pkgdir)
quiet = self.assertRunOK('-q', self.pkgdir)
self.assertNotEqual(b'', noisy)
self.assertEqual(b'', quiet)
def test_silent(self):
script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
_, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
_, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
self.assertNotEqual(b'', quiet)
self.assertEqual(b'', silent)
def test_regexp(self):
self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
self.assertNotCompiled(self.barfn)
self.assertCompiled(self.initfn)
def test_multiple_dirs(self):
pkgdir2 = os.path.join(self.directory, 'foo2')
os.mkdir(pkgdir2)
init2fn = script_helper.make_script(pkgdir2, '__init__', '')
bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
self.assertRunOK('-q', self.pkgdir, pkgdir2)
self.assertCompiled(self.initfn)
self.assertCompiled(self.barfn)
self.assertCompiled(init2fn)
self.assertCompiled(bar2fn)
def test_d_compile_error(self):
script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
self.assertRegex(out, b'File "dinsdale')
def test_d_runtime_error(self):
bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
pyc = importlib.util.cache_from_source(bazfn)
os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
os.remove(bazfn)
rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
self.assertRegex(err, b'File "dinsdale')
def test_include_bad_file(self):
rc, out, err = self.assertRunNotOK(
'-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
self.assertRegex(out, b'rror.*nosuchfile')
self.assertNotRegex(err, b'Traceback')
self.assertFalse(os.path.exists(importlib.util.cache_from_source(
self.pkgdir_cachedir)))
def test_include_file_with_arg(self):
f1 = script_helper.make_script(self.pkgdir, 'f1', '')
f2 = script_helper.make_script(self.pkgdir, 'f2', '')
f3 = script_helper.make_script(self.pkgdir, 'f3', '')
f4 = script_helper.make_script(self.pkgdir, 'f4', '')
with open(os.path.join(self.directory, 'l1'), 'w') as l1:
l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
self.assertCompiled(f1)
self.assertCompiled(f2)
self.assertNotCompiled(f3)
self.assertCompiled(f4)
def test_include_file_no_arg(self):
f1 = script_helper.make_script(self.pkgdir, 'f1', '')
f2 = script_helper.make_script(self.pkgdir, 'f2', '')
f3 = script_helper.make_script(self.pkgdir, 'f3', '')
f4 = script_helper.make_script(self.pkgdir, 'f4', '')
with open(os.path.join(self.directory, 'l1'), 'w') as l1:
l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
self.assertNotCompiled(f1)
self.assertCompiled(f2)
self.assertNotCompiled(f3)
self.assertNotCompiled(f4)
def test_include_on_stdin(self):
f1 = script_helper.make_script(self.pkgdir, 'f1', '')
f2 = script_helper.make_script(self.pkgdir, 'f2', '')
f3 = script_helper.make_script(self.pkgdir, 'f3', '')
f4 = script_helper.make_script(self.pkgdir, 'f4', '')
p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
p.stdin.write((f3+os.linesep).encode('ascii'))
script_helper.kill_python(p)
self.assertNotCompiled(f1)
self.assertNotCompiled(f2)
self.assertCompiled(f3)
self.assertNotCompiled(f4)
def test_compiles_as_much_as_possible(self):
bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
bingfn, self.barfn)
self.assertRegex(out, b'rror')
self.assertNotCompiled(bingfn)
self.assertCompiled(self.initfn)
self.assertCompiled(self.barfn)
def test_invalid_arg_produces_message(self):
out = self.assertRunOK('badfilename')
self.assertRegex(out, b"Can't list 'badfilename'")
@skipUnless(_have_multiprocessing, "requires multiprocessing")
def test_workers(self):
bar2fn = script_helper.make_script(self.directory, 'bar2', '')
files = []
for suffix in range(5):
pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
os.mkdir(pkgdir)
fn = script_helper.make_script(pkgdir, '__init__', '')
files.append(script_helper.make_script(pkgdir, 'bar2', ''))
self.assertRunOK(self.directory, '-j', '0')
self.assertCompiled(bar2fn)
for file in files:
self.assertCompiled(file)
@mock.patch('compileall.compile_dir')
def test_workers_available_cores(self, compile_dir):
with mock.patch("sys.argv",
new=[sys.executable, self.directory, "-j0"]):
compileall.main()
self.assertTrue(compile_dir.called)
self.assertEqual(compile_dir.call_args[-1]['workers'], None)
if __name__ == "__main__":
unittest.main()
| 23,386 | 548 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_codecencodings_tw.py | #
# test_codecencodings_tw.py
# Codec encoding tests for ROC encodings.
#
from test import multibytecodec_support
import unittest
class Test_Big5(multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'big5'
tstring = multibytecodec_support.load_teststring('big5')
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\u8b10"),
(b"abc\x80\x80\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\u8b10\ufffd"),
(b"abc\x80\x80\xc1\xc4", "ignore", "abc\u8b10"),
)
if __name__ == "__main__":
unittest.main()
| 681 | 23 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_urllib2_localnet.py | import base64
import os
import email
import urllib.parse
import urllib.request
import http.server
import unittest
import hashlib
from test import support
threading = support.import_module('threading')
try:
import ssl
except ImportError:
ssl = None
here = os.path.dirname(__file__)
# Self-signed cert file for 'localhost'
CERT_localhost = os.path.join(here, 'keycert.pem')
# Self-signed cert file for 'fakehostname'
CERT_fakehostname = os.path.join(here, 'keycert2.pem')
# Loopback http server infrastructure
class LoopbackHttpServer(http.server.HTTPServer):
"""HTTP server w/ a few modifications that make it useful for
loopback testing purposes.
"""
def __init__(self, server_address, RequestHandlerClass):
http.server.HTTPServer.__init__(self,
server_address,
RequestHandlerClass)
# Set the timeout of our listening socket really low so
# that we can stop the server easily.
self.socket.settimeout(0.1)
def get_request(self):
"""HTTPServer method, overridden."""
request, client_address = self.socket.accept()
# It's a loopback connection, so setting the timeout
# really low shouldn't affect anything, but should make
# deadlocks less likely to occur.
request.settimeout(10.0)
return (request, client_address)
class LoopbackHttpServerThread(threading.Thread):
"""Stoppable thread that runs a loopback http server."""
def __init__(self, request_handler):
threading.Thread.__init__(self)
self._stop_server = False
self.ready = threading.Event()
request_handler.protocol_version = "HTTP/1.0"
self.httpd = LoopbackHttpServer(("127.0.0.1", 0),
request_handler)
self.port = self.httpd.server_port
def stop(self):
"""Stops the webserver if it's currently running."""
self._stop_server = True
self.join()
self.httpd.server_close()
def run(self):
self.ready.set()
while not self._stop_server:
self.httpd.handle_request()
# Authentication infrastructure
class DigestAuthHandler:
"""Handler for performing digest authentication."""
def __init__(self):
self._request_num = 0
self._nonces = []
self._users = {}
self._realm_name = "Test Realm"
self._qop = "auth"
def set_qop(self, qop):
self._qop = qop
def set_users(self, users):
assert isinstance(users, dict)
self._users = users
def set_realm(self, realm):
self._realm_name = realm
def _generate_nonce(self):
self._request_num += 1
nonce = hashlib.md5(str(self._request_num).encode("ascii")).hexdigest()
self._nonces.append(nonce)
return nonce
def _create_auth_dict(self, auth_str):
first_space_index = auth_str.find(" ")
auth_str = auth_str[first_space_index+1:]
parts = auth_str.split(",")
auth_dict = {}
for part in parts:
name, value = part.split("=")
name = name.strip()
if value[0] == '"' and value[-1] == '"':
value = value[1:-1]
else:
value = value.strip()
auth_dict[name] = value
return auth_dict
def _validate_auth(self, auth_dict, password, method, uri):
final_dict = {}
final_dict.update(auth_dict)
final_dict["password"] = password
final_dict["method"] = method
final_dict["uri"] = uri
HA1_str = "%(username)s:%(realm)s:%(password)s" % final_dict
HA1 = hashlib.md5(HA1_str.encode("ascii")).hexdigest()
HA2_str = "%(method)s:%(uri)s" % final_dict
HA2 = hashlib.md5(HA2_str.encode("ascii")).hexdigest()
final_dict["HA1"] = HA1
final_dict["HA2"] = HA2
response_str = "%(HA1)s:%(nonce)s:%(nc)s:" \
"%(cnonce)s:%(qop)s:%(HA2)s" % final_dict
response = hashlib.md5(response_str.encode("ascii")).hexdigest()
return response == auth_dict["response"]
def _return_auth_challenge(self, request_handler):
request_handler.send_response(407, "Proxy Authentication Required")
request_handler.send_header("Content-Type", "text/html")
request_handler.send_header(
'Proxy-Authenticate', 'Digest realm="%s", '
'qop="%s",'
'nonce="%s", ' % \
(self._realm_name, self._qop, self._generate_nonce()))
# XXX: Not sure if we're supposed to add this next header or
# not.
#request_handler.send_header('Connection', 'close')
request_handler.end_headers()
request_handler.wfile.write(b"Proxy Authentication Required.")
return False
def handle_request(self, request_handler):
"""Performs digest authentication on the given HTTP request
handler. Returns True if authentication was successful, False
otherwise.
If no users have been set, then digest auth is effectively
disabled and this method will always return True.
"""
if len(self._users) == 0:
return True
if "Proxy-Authorization" not in request_handler.headers:
return self._return_auth_challenge(request_handler)
else:
auth_dict = self._create_auth_dict(
request_handler.headers["Proxy-Authorization"]
)
if auth_dict["username"] in self._users:
password = self._users[ auth_dict["username"] ]
else:
return self._return_auth_challenge(request_handler)
if not auth_dict.get("nonce") in self._nonces:
return self._return_auth_challenge(request_handler)
else:
self._nonces.remove(auth_dict["nonce"])
auth_validated = False
# MSIE uses short_path in its validation, but Python's
# urllib.request uses the full path, so we're going to see if
# either of them works here.
for path in [request_handler.path, request_handler.short_path]:
if self._validate_auth(auth_dict,
password,
request_handler.command,
path):
auth_validated = True
if not auth_validated:
return self._return_auth_challenge(request_handler)
return True
class BasicAuthHandler(http.server.BaseHTTPRequestHandler):
"""Handler for performing basic authentication."""
# Server side values
USER = 'testUser'
PASSWD = 'testPass'
REALM = 'Test'
USER_PASSWD = "%s:%s" % (USER, PASSWD)
ENCODED_AUTH = base64.b64encode(USER_PASSWD.encode('ascii')).decode('ascii')
def __init__(self, *args, **kwargs):
http.server.BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
def log_message(self, format, *args):
# Suppress console log message
pass
def do_HEAD(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def do_AUTHHEAD(self):
self.send_response(401)
self.send_header("WWW-Authenticate", "Basic realm=\"%s\"" % self.REALM)
self.send_header("Content-type", "text/html")
self.end_headers()
def do_GET(self):
if not self.headers.get("Authorization", ""):
self.do_AUTHHEAD()
self.wfile.write(b"No Auth header received")
elif self.headers.get(
"Authorization", "") == "Basic " + self.ENCODED_AUTH:
self.send_response(200)
self.end_headers()
self.wfile.write(b"It works")
else:
# Request Unauthorized
self.do_AUTHHEAD()
# Proxy test infrastructure
class FakeProxyHandler(http.server.BaseHTTPRequestHandler):
"""This is a 'fake proxy' that makes it look like the entire
internet has gone down due to a sudden zombie invasion. It main
utility is in providing us with authentication support for
testing.
"""
def __init__(self, digest_auth_handler, *args, **kwargs):
# This has to be set before calling our parent's __init__(), which will
# try to call do_GET().
self.digest_auth_handler = digest_auth_handler
http.server.BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
def log_message(self, format, *args):
# Uncomment the next line for debugging.
# sys.stderr.write(format % args)
pass
def do_GET(self):
(scm, netloc, path, params, query, fragment) = urllib.parse.urlparse(
self.path, "http")
self.short_path = path
if self.digest_auth_handler.handle_request(self):
self.send_response(200, "OK")
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write(bytes("You've reached %s!<BR>" % self.path,
"ascii"))
self.wfile.write(b"Our apologies, but our server is down due to "
b"a sudden zombie invasion.")
# Test cases
@unittest.skipUnless(threading, "Threading required for this test.")
class BasicAuthTests(unittest.TestCase):
USER = "testUser"
PASSWD = "testPass"
INCORRECT_PASSWD = "Incorrect"
REALM = "Test"
def setUp(self):
super(BasicAuthTests, self).setUp()
# With Basic Authentication
def http_server_with_basic_auth_handler(*args, **kwargs):
return BasicAuthHandler(*args, **kwargs)
self.server = LoopbackHttpServerThread(http_server_with_basic_auth_handler)
self.addCleanup(self.stop_server)
self.server_url = 'http://127.0.0.1:%s' % self.server.port
self.server.start()
self.server.ready.wait()
def stop_server(self):
self.server.stop()
self.server = None
def tearDown(self):
super(BasicAuthTests, self).tearDown()
def test_basic_auth_success(self):
ah = urllib.request.HTTPBasicAuthHandler()
ah.add_password(self.REALM, self.server_url, self.USER, self.PASSWD)
urllib.request.install_opener(urllib.request.build_opener(ah))
try:
self.assertTrue(urllib.request.urlopen(self.server_url))
except urllib.error.HTTPError:
self.fail("Basic auth failed for the url: %s" % self.server_url)
def test_basic_auth_httperror(self):
ah = urllib.request.HTTPBasicAuthHandler()
ah.add_password(self.REALM, self.server_url, self.USER, self.INCORRECT_PASSWD)
urllib.request.install_opener(urllib.request.build_opener(ah))
self.assertRaises(urllib.error.HTTPError, urllib.request.urlopen, self.server_url)
@unittest.skipUnless(threading, "Threading required for this test.")
class ProxyAuthTests(unittest.TestCase):
URL = "http://localhost"
USER = "tester"
PASSWD = "test123"
REALM = "TestRealm"
def setUp(self):
super(ProxyAuthTests, self).setUp()
# Ignore proxy bypass settings in the environment.
def restore_environ(old_environ):
os.environ.clear()
os.environ.update(old_environ)
self.addCleanup(restore_environ, os.environ.copy())
os.environ['NO_PROXY'] = ''
os.environ['no_proxy'] = ''
self.digest_auth_handler = DigestAuthHandler()
self.digest_auth_handler.set_users({self.USER: self.PASSWD})
self.digest_auth_handler.set_realm(self.REALM)
# With Digest Authentication.
def create_fake_proxy_handler(*args, **kwargs):
return FakeProxyHandler(self.digest_auth_handler, *args, **kwargs)
self.server = LoopbackHttpServerThread(create_fake_proxy_handler)
self.addCleanup(self.stop_server)
self.server.start()
self.server.ready.wait()
proxy_url = "http://127.0.0.1:%d" % self.server.port
handler = urllib.request.ProxyHandler({"http" : proxy_url})
self.proxy_digest_handler = urllib.request.ProxyDigestAuthHandler()
self.opener = urllib.request.build_opener(
handler, self.proxy_digest_handler)
def stop_server(self):
self.server.stop()
self.server = None
def test_proxy_with_bad_password_raises_httperror(self):
self.proxy_digest_handler.add_password(self.REALM, self.URL,
self.USER, self.PASSWD+"bad")
self.digest_auth_handler.set_qop("auth")
self.assertRaises(urllib.error.HTTPError,
self.opener.open,
self.URL)
def test_proxy_with_no_password_raises_httperror(self):
self.digest_auth_handler.set_qop("auth")
self.assertRaises(urllib.error.HTTPError,
self.opener.open,
self.URL)
def test_proxy_qop_auth_works(self):
self.proxy_digest_handler.add_password(self.REALM, self.URL,
self.USER, self.PASSWD)
self.digest_auth_handler.set_qop("auth")
result = self.opener.open(self.URL)
while result.read():
pass
result.close()
def test_proxy_qop_auth_int_works_or_throws_urlerror(self):
self.proxy_digest_handler.add_password(self.REALM, self.URL,
self.USER, self.PASSWD)
self.digest_auth_handler.set_qop("auth-int")
try:
result = self.opener.open(self.URL)
except urllib.error.URLError:
# It's okay if we don't support auth-int, but we certainly
# shouldn't receive any kind of exception here other than
# a URLError.
result = None
if result:
while result.read():
pass
result.close()
def GetRequestHandler(responses):
class FakeHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
server_version = "TestHTTP/"
requests = []
headers_received = []
port = 80
def do_GET(self):
body = self.send_head()
while body:
done = self.wfile.write(body)
body = body[done:]
def do_POST(self):
content_length = self.headers["Content-Length"]
post_data = self.rfile.read(int(content_length))
self.do_GET()
self.requests.append(post_data)
def send_head(self):
FakeHTTPRequestHandler.headers_received = self.headers
self.requests.append(self.path)
response_code, headers, body = responses.pop(0)
self.send_response(response_code)
for (header, value) in headers:
self.send_header(header, value % {'port':self.port})
if body:
self.send_header("Content-type", "text/plain")
self.end_headers()
return body
self.end_headers()
def log_message(self, *args):
pass
return FakeHTTPRequestHandler
@unittest.skipUnless(threading, "Threading required for this test.")
class TestUrlopen(unittest.TestCase):
"""Tests urllib.request.urlopen using the network.
These tests are not exhaustive. Assuming that testing using files does a
good job overall of some of the basic interface features. There are no
tests exercising the optional 'data' and 'proxies' arguments. No tests
for transparent redirection have been written.
"""
def setUp(self):
super(TestUrlopen, self).setUp()
# Ignore proxies for localhost tests.
def restore_environ(old_environ):
os.environ.clear()
os.environ.update(old_environ)
self.addCleanup(restore_environ, os.environ.copy())
os.environ['NO_PROXY'] = '*'
os.environ['no_proxy'] = '*'
def urlopen(self, url, data=None, **kwargs):
l = []
f = urllib.request.urlopen(url, data, **kwargs)
try:
# Exercise various methods
l.extend(f.readlines(200))
l.append(f.readline())
l.append(f.read(1024))
l.append(f.read())
finally:
f.close()
return b"".join(l)
def stop_server(self):
self.server.stop()
self.server = None
def start_server(self, responses=None):
if responses is None:
responses = [(200, [], b"we don't care")]
handler = GetRequestHandler(responses)
self.server = LoopbackHttpServerThread(handler)
self.addCleanup(self.stop_server)
self.server.start()
self.server.ready.wait()
port = self.server.port
handler.port = port
return handler
def start_https_server(self, responses=None, **kwargs):
if not hasattr(urllib.request, 'HTTPSHandler'):
self.skipTest('ssl support required')
# from test.ssl_servers import make_https_server
if responses is None:
responses = [(200, [], b"we care a bit")]
handler = GetRequestHandler(responses)
server = make_https_server(self, handler_class=handler, **kwargs)
handler.port = server.port
return handler
def test_redirection(self):
expected_response = b"We goth here..."
responses = [
(302, [("Location", "http://localhost:%(port)s/somewhere_else")],
""),
(200, [], expected_response)
]
handler = self.start_server(responses)
data = self.urlopen("http://localhost:%s/" % handler.port)
self.assertEqual(data, expected_response)
self.assertEqual(handler.requests, ["/", "/somewhere_else"])
def test_chunked(self):
expected_response = b"hello world"
chunked_start = (
b'a\r\n'
b'hello worl\r\n'
b'1\r\n'
b'd\r\n'
b'0\r\n'
)
response = [(200, [("Transfer-Encoding", "chunked")], chunked_start)]
handler = self.start_server(response)
data = self.urlopen("http://localhost:%s/" % handler.port)
self.assertEqual(data, expected_response)
def test_404(self):
expected_response = b"Bad bad bad..."
handler = self.start_server([(404, [], expected_response)])
try:
self.urlopen("http://localhost:%s/weeble" % handler.port)
except urllib.error.URLError as f:
data = f.read()
f.close()
else:
self.fail("404 should raise URLError")
self.assertEqual(data, expected_response)
self.assertEqual(handler.requests, ["/weeble"])
def test_200(self):
expected_response = b"pycon 2008..."
handler = self.start_server([(200, [], expected_response)])
data = self.urlopen("http://localhost:%s/bizarre" % handler.port)
self.assertEqual(data, expected_response)
self.assertEqual(handler.requests, ["/bizarre"])
def test_200_with_parameters(self):
expected_response = b"pycon 2008..."
handler = self.start_server([(200, [], expected_response)])
data = self.urlopen("http://localhost:%s/bizarre" % handler.port,
b"get=with_feeling")
self.assertEqual(data, expected_response)
self.assertEqual(handler.requests, ["/bizarre", b"get=with_feeling"])
def test_https(self):
handler = self.start_https_server()
context = ssl.create_default_context(cafile=CERT_localhost)
data = self.urlopen("https://localhost:%s/bizarre" % handler.port, context=context)
self.assertEqual(data, b"we care a bit")
def test_https_with_cafile(self):
handler = self.start_https_server(certfile=CERT_localhost)
with support.check_warnings(('', DeprecationWarning)):
# Good cert
data = self.urlopen("https://localhost:%s/bizarre" % handler.port,
cafile=CERT_localhost)
self.assertEqual(data, b"we care a bit")
# Bad cert
with self.assertRaises(urllib.error.URLError) as cm:
self.urlopen("https://localhost:%s/bizarre" % handler.port,
cafile=CERT_fakehostname)
# Good cert, but mismatching hostname
handler = self.start_https_server(certfile=CERT_fakehostname)
with self.assertRaises(ssl.CertificateError) as cm:
self.urlopen("https://localhost:%s/bizarre" % handler.port,
cafile=CERT_fakehostname)
def test_https_with_cadefault(self):
handler = self.start_https_server(certfile=CERT_localhost)
# Self-signed cert should fail verification with system certificate store
with support.check_warnings(('', DeprecationWarning)):
with self.assertRaises(urllib.error.URLError) as cm:
self.urlopen("https://localhost:%s/bizarre" % handler.port,
cadefault=True)
def test_https_sni(self):
if ssl is None:
self.skipTest("ssl module required")
if not ssl.HAS_SNI:
self.skipTest("SNI support required in OpenSSL")
sni_name = None
def cb_sni(ssl_sock, server_name, initial_context):
nonlocal sni_name
sni_name = server_name
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
context.set_servername_callback(cb_sni)
handler = self.start_https_server(context=context, certfile=CERT_localhost)
context = ssl.create_default_context(cafile=CERT_localhost)
self.urlopen("https://localhost:%s" % handler.port, context=context)
self.assertEqual(sni_name, "localhost")
def test_sending_headers(self):
handler = self.start_server()
req = urllib.request.Request("http://localhost:%s/" % handler.port,
headers={"Range": "bytes=20-39"})
with urllib.request.urlopen(req):
pass
self.assertEqual(handler.headers_received["Range"], "bytes=20-39")
def test_basic(self):
handler = self.start_server()
open_url = urllib.request.urlopen("http://localhost:%s" % handler.port)
for attr in ("read", "close", "info", "geturl"):
self.assertTrue(hasattr(open_url, attr), "object returned from "
"urlopen lacks the %s attribute" % attr)
try:
self.assertTrue(open_url.read(), "calling 'read' failed")
finally:
open_url.close()
def test_info(self):
handler = self.start_server()
open_url = urllib.request.urlopen(
"http://localhost:%s" % handler.port)
with open_url:
info_obj = open_url.info()
self.assertIsInstance(info_obj, email.message.Message,
"object returned by 'info' is not an "
"instance of email.message.Message")
self.assertEqual(info_obj.get_content_subtype(), "plain")
def test_geturl(self):
# Make sure same URL as opened is returned by geturl.
handler = self.start_server()
open_url = urllib.request.urlopen("http://localhost:%s" % handler.port)
with open_url:
url = open_url.geturl()
self.assertEqual(url, "http://localhost:%s" % handler.port)
def test_iteration(self):
expected_response = b"pycon 2008..."
handler = self.start_server([(200, [], expected_response)])
data = urllib.request.urlopen("http://localhost:%s" % handler.port)
for line in data:
self.assertEqual(line, expected_response)
def test_line_iteration(self):
lines = [b"We\n", b"got\n", b"here\n", b"verylong " * 8192 + b"\n"]
expected_response = b"".join(lines)
handler = self.start_server([(200, [], expected_response)])
data = urllib.request.urlopen("http://localhost:%s" % handler.port)
for index, line in enumerate(data):
self.assertEqual(line, lines[index],
"Fetched line number %s doesn't match expected:\n"
" Expected length was %s, got %s" %
(index, len(lines[index]), len(line)))
self.assertEqual(index + 1, len(lines))
threads_key = None
def setUpModule():
# Store the threading_setup in a key and ensure that it is cleaned up
# in the tearDown
global threads_key
threads_key = support.threading_setup()
def tearDownModule():
if threads_key:
support.threading_cleanup(*threads_key)
if __name__ == "__main__":
unittest.main()
| 25,073 | 680 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_pyexpat.py | # XXX TypeErrors on calling handlers, or on bad return values from a
# handler, are obscure and unhelpful.
from io import BytesIO
import os
import sys
import sysconfig
import unittest
import traceback
from xml.parsers import expat
from xml.parsers.expat import errors
from test.support import sortdict
class SetAttributeTest(unittest.TestCase):
def setUp(self):
self.parser = expat.ParserCreate(namespace_separator='!')
def test_buffer_text(self):
self.assertIs(self.parser.buffer_text, False)
for x in 0, 1, 2, 0:
self.parser.buffer_text = x
self.assertIs(self.parser.buffer_text, bool(x))
def test_namespace_prefixes(self):
self.assertIs(self.parser.namespace_prefixes, False)
for x in 0, 1, 2, 0:
self.parser.namespace_prefixes = x
self.assertIs(self.parser.namespace_prefixes, bool(x))
def test_ordered_attributes(self):
self.assertIs(self.parser.ordered_attributes, False)
for x in 0, 1, 2, 0:
self.parser.ordered_attributes = x
self.assertIs(self.parser.ordered_attributes, bool(x))
def test_specified_attributes(self):
self.assertIs(self.parser.specified_attributes, False)
for x in 0, 1, 2, 0:
self.parser.specified_attributes = x
self.assertIs(self.parser.specified_attributes, bool(x))
def test_invalid_attributes(self):
with self.assertRaises(AttributeError):
self.parser.returns_unicode = 1
with self.assertRaises(AttributeError):
self.parser.returns_unicode
# Issue #25019
self.assertRaises(TypeError, setattr, self.parser, range(0xF), 0)
self.assertRaises(TypeError, self.parser.__setattr__, range(0xF), 0)
self.assertRaises(TypeError, getattr, self.parser, range(0xF))
data = b'''\
<?xml version="1.0" encoding="iso-8859-1" standalone="no"?>
<?xml-stylesheet href="stylesheet.css"?>
<!-- comment data -->
<!DOCTYPE quotations SYSTEM "quotations.dtd" [
<!ELEMENT root ANY>
<!ATTLIST root attr1 CDATA #REQUIRED attr2 CDATA #IMPLIED>
<!NOTATION notation SYSTEM "notation.jpeg">
<!ENTITY acirc "â">
<!ENTITY external_entity SYSTEM "entity.file">
<!ENTITY unparsed_entity SYSTEM "entity.file" NDATA notation>
%unparsed_entity;
]>
<root attr1="value1" attr2="value2ὀ">
<myns:subelement xmlns:myns="http://www.python.org/namespace">
Contents of subelements
</myns:subelement>
<sub2><![CDATA[contents of CDATA section]]></sub2>
&external_entity;
&skipped_entity;
\xb5
</root>
'''
# Produce UTF-8 output
class ParseTest(unittest.TestCase):
class Outputter:
def __init__(self):
self.out = []
def StartElementHandler(self, name, attrs):
self.out.append('Start element: ' + repr(name) + ' ' +
sortdict(attrs))
def EndElementHandler(self, name):
self.out.append('End element: ' + repr(name))
def CharacterDataHandler(self, data):
data = data.strip()
if data:
self.out.append('Character data: ' + repr(data))
def ProcessingInstructionHandler(self, target, data):
self.out.append('PI: ' + repr(target) + ' ' + repr(data))
def StartNamespaceDeclHandler(self, prefix, uri):
self.out.append('NS decl: ' + repr(prefix) + ' ' + repr(uri))
def EndNamespaceDeclHandler(self, prefix):
self.out.append('End of NS decl: ' + repr(prefix))
def StartCdataSectionHandler(self):
self.out.append('Start of CDATA section')
def EndCdataSectionHandler(self):
self.out.append('End of CDATA section')
def CommentHandler(self, text):
self.out.append('Comment: ' + repr(text))
def NotationDeclHandler(self, *args):
name, base, sysid, pubid = args
self.out.append('Notation declared: %s' %(args,))
def UnparsedEntityDeclHandler(self, *args):
entityName, base, systemId, publicId, notationName = args
self.out.append('Unparsed entity decl: %s' %(args,))
def NotStandaloneHandler(self):
self.out.append('Not standalone')
return 1
def ExternalEntityRefHandler(self, *args):
context, base, sysId, pubId = args
self.out.append('External entity ref: %s' %(args[1:],))
return 1
def StartDoctypeDeclHandler(self, *args):
self.out.append(('Start doctype', args))
return 1
def EndDoctypeDeclHandler(self):
self.out.append("End doctype")
return 1
def EntityDeclHandler(self, *args):
self.out.append(('Entity declaration', args))
return 1
def XmlDeclHandler(self, *args):
self.out.append(('XML declaration', args))
return 1
def ElementDeclHandler(self, *args):
self.out.append(('Element declaration', args))
return 1
def AttlistDeclHandler(self, *args):
self.out.append(('Attribute list declaration', args))
return 1
def SkippedEntityHandler(self, *args):
self.out.append(("Skipped entity", args))
return 1
def DefaultHandler(self, userData):
pass
def DefaultHandlerExpand(self, userData):
pass
handler_names = [
'StartElementHandler', 'EndElementHandler', 'CharacterDataHandler',
'ProcessingInstructionHandler', 'UnparsedEntityDeclHandler',
'NotationDeclHandler', 'StartNamespaceDeclHandler',
'EndNamespaceDeclHandler', 'CommentHandler',
'StartCdataSectionHandler', 'EndCdataSectionHandler', 'DefaultHandler',
'DefaultHandlerExpand', 'NotStandaloneHandler',
'ExternalEntityRefHandler', 'StartDoctypeDeclHandler',
'EndDoctypeDeclHandler', 'EntityDeclHandler', 'XmlDeclHandler',
'ElementDeclHandler', 'AttlistDeclHandler', 'SkippedEntityHandler',
]
def _hookup_callbacks(self, parser, handler):
"""
Set each of the callbacks defined on handler and named in
self.handler_names on the given parser.
"""
for name in self.handler_names:
setattr(parser, name, getattr(handler, name))
def _verify_parse_output(self, operations):
expected_operations = [
('XML declaration', ('1.0', 'iso-8859-1', 0)),
'PI: \'xml-stylesheet\' \'href="stylesheet.css"\'',
"Comment: ' comment data '",
"Not standalone",
("Start doctype", ('quotations', 'quotations.dtd', None, 1)),
('Element declaration', ('root', (2, 0, None, ()))),
('Attribute list declaration', ('root', 'attr1', 'CDATA', None,
1)),
('Attribute list declaration', ('root', 'attr2', 'CDATA', None,
0)),
"Notation declared: ('notation', None, 'notation.jpeg', None)",
('Entity declaration', ('acirc', 0, '\xe2', None, None, None, None)),
('Entity declaration', ('external_entity', 0, None, None,
'entity.file', None, None)),
"Unparsed entity decl: ('unparsed_entity', None, 'entity.file', None, 'notation')",
"Not standalone",
"End doctype",
"Start element: 'root' {'attr1': 'value1', 'attr2': 'value2\u1f40'}",
"NS decl: 'myns' 'http://www.python.org/namespace'",
"Start element: 'http://www.python.org/namespace!subelement' {}",
"Character data: 'Contents of subelements'",
"End element: 'http://www.python.org/namespace!subelement'",
"End of NS decl: 'myns'",
"Start element: 'sub2' {}",
'Start of CDATA section',
"Character data: 'contents of CDATA section'",
'End of CDATA section',
"End element: 'sub2'",
"External entity ref: (None, 'entity.file', None)",
('Skipped entity', ('skipped_entity', 0)),
"Character data: '\xb5'",
"End element: 'root'",
]
for operation, expected_operation in zip(operations, expected_operations):
self.assertEqual(operation, expected_operation)
def test_parse_bytes(self):
out = self.Outputter()
parser = expat.ParserCreate(namespace_separator='!')
self._hookup_callbacks(parser, out)
parser.Parse(data, 1)
operations = out.out
self._verify_parse_output(operations)
# Issue #6697.
self.assertRaises(AttributeError, getattr, parser, '\uD800')
def test_parse_str(self):
out = self.Outputter()
parser = expat.ParserCreate(namespace_separator='!')
self._hookup_callbacks(parser, out)
parser.Parse(data.decode('iso-8859-1'), 1)
operations = out.out
self._verify_parse_output(operations)
def test_parse_file(self):
# Try parsing a file
out = self.Outputter()
parser = expat.ParserCreate(namespace_separator='!')
self._hookup_callbacks(parser, out)
file = BytesIO(data)
parser.ParseFile(file)
operations = out.out
self._verify_parse_output(operations)
def test_parse_again(self):
parser = expat.ParserCreate()
file = BytesIO(data)
parser.ParseFile(file)
# Issue 6676: ensure a meaningful exception is raised when attempting
# to parse more than one XML document per xmlparser instance,
# a limitation of the Expat library.
with self.assertRaises(expat.error) as cm:
parser.ParseFile(file)
self.assertEqual(expat.ErrorString(cm.exception.code),
expat.errors.XML_ERROR_FINISHED)
class NamespaceSeparatorTest(unittest.TestCase):
def test_legal(self):
# Tests that make sure we get errors when the namespace_separator value
# is illegal, and that we don't for good values:
expat.ParserCreate()
expat.ParserCreate(namespace_separator=None)
expat.ParserCreate(namespace_separator=' ')
def test_illegal(self):
try:
expat.ParserCreate(namespace_separator=42)
self.fail()
except TypeError as e:
self.assertEqual(str(e),
'ParserCreate() argument 2 must be str or None, not int')
try:
expat.ParserCreate(namespace_separator='too long')
self.fail()
except ValueError as e:
self.assertEqual(str(e),
'namespace_separator must be at most one character, omitted, or None')
def test_zero_length(self):
# ParserCreate() needs to accept a namespace_separator of zero length
# to satisfy the requirements of RDF applications that are required
# to simply glue together the namespace URI and the localname. Though
# considered a wart of the RDF specifications, it needs to be supported.
#
# See XML-SIG mailing list thread starting with
# http://mail.python.org/pipermail/xml-sig/2001-April/005202.html
#
expat.ParserCreate(namespace_separator='') # too short
class InterningTest(unittest.TestCase):
def test(self):
# Test the interning machinery.
p = expat.ParserCreate()
L = []
def collector(name, *args):
L.append(name)
p.StartElementHandler = collector
p.EndElementHandler = collector
p.Parse(b"<e> <e/> <e></e> </e>", 1)
tag = L[0]
self.assertEqual(len(L), 6)
for entry in L:
# L should have the same string repeated over and over.
self.assertTrue(tag is entry)
def test_issue9402(self):
# create an ExternalEntityParserCreate with buffer text
class ExternalOutputter:
def __init__(self, parser):
self.parser = parser
self.parser_result = None
def ExternalEntityRefHandler(self, context, base, sysId, pubId):
external_parser = self.parser.ExternalEntityParserCreate("")
self.parser_result = external_parser.Parse(b"", 1)
return 1
parser = expat.ParserCreate(namespace_separator='!')
parser.buffer_text = 1
out = ExternalOutputter(parser)
parser.ExternalEntityRefHandler = out.ExternalEntityRefHandler
parser.Parse(data, 1)
self.assertEqual(out.parser_result, 1)
class BufferTextTest(unittest.TestCase):
def setUp(self):
self.stuff = []
self.parser = expat.ParserCreate()
self.parser.buffer_text = 1
self.parser.CharacterDataHandler = self.CharacterDataHandler
def check(self, expected, label):
self.assertEqual(self.stuff, expected,
"%s\nstuff = %r\nexpected = %r"
% (label, self.stuff, map(str, expected)))
def CharacterDataHandler(self, text):
self.stuff.append(text)
def StartElementHandler(self, name, attrs):
self.stuff.append("<%s>" % name)
bt = attrs.get("buffer-text")
if bt == "yes":
self.parser.buffer_text = 1
elif bt == "no":
self.parser.buffer_text = 0
def EndElementHandler(self, name):
self.stuff.append("</%s>" % name)
def CommentHandler(self, data):
self.stuff.append("<!--%s-->" % data)
def setHandlers(self, handlers=[]):
for name in handlers:
setattr(self.parser, name, getattr(self, name))
def test_default_to_disabled(self):
parser = expat.ParserCreate()
self.assertFalse(parser.buffer_text)
def test_buffering_enabled(self):
# Make sure buffering is turned on
self.assertTrue(self.parser.buffer_text)
self.parser.Parse(b"<a>1<b/>2<c/>3</a>", 1)
self.assertEqual(self.stuff, ['123'],
"buffered text not properly collapsed")
def test1(self):
# XXX This test exposes more detail of Expat's text chunking than we
# XXX like, but it tests what we need to concisely.
self.setHandlers(["StartElementHandler"])
self.parser.Parse(b"<a>1<b buffer-text='no'/>2\n3<c buffer-text='yes'/>4\n5</a>", 1)
self.assertEqual(self.stuff,
["<a>", "1", "<b>", "2", "\n", "3", "<c>", "4\n5"],
"buffering control not reacting as expected")
def test2(self):
self.parser.Parse(b"<a>1<b/><2><c/> \n 3</a>", 1)
self.assertEqual(self.stuff, ["1<2> \n 3"],
"buffered text not properly collapsed")
def test3(self):
self.setHandlers(["StartElementHandler"])
self.parser.Parse(b"<a>1<b/>2<c/>3</a>", 1)
self.assertEqual(self.stuff, ["<a>", "1", "<b>", "2", "<c>", "3"],
"buffered text not properly split")
def test4(self):
self.setHandlers(["StartElementHandler", "EndElementHandler"])
self.parser.CharacterDataHandler = None
self.parser.Parse(b"<a>1<b/>2<c/>3</a>", 1)
self.assertEqual(self.stuff,
["<a>", "<b>", "</b>", "<c>", "</c>", "</a>"])
def test5(self):
self.setHandlers(["StartElementHandler", "EndElementHandler"])
self.parser.Parse(b"<a>1<b></b>2<c/>3</a>", 1)
self.assertEqual(self.stuff,
["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "3", "</a>"])
def test6(self):
self.setHandlers(["CommentHandler", "EndElementHandler",
"StartElementHandler"])
self.parser.Parse(b"<a>1<b/>2<c></c>345</a> ", 1)
self.assertEqual(self.stuff,
["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "345", "</a>"],
"buffered text not properly split")
def test7(self):
self.setHandlers(["CommentHandler", "EndElementHandler",
"StartElementHandler"])
self.parser.Parse(b"<a>1<b/>2<c></c>3<!--abc-->4<!--def-->5</a> ", 1)
self.assertEqual(self.stuff,
["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "3",
"<!--abc-->", "4", "<!--def-->", "5", "</a>"],
"buffered text not properly split")
# Test handling of exception from callback:
class HandlerExceptionTest(unittest.TestCase):
def StartElementHandler(self, name, attrs):
raise RuntimeError(name)
def check_traceback_entry(self, entry, filename, funcname):
self.assertEqual(os.path.basename(entry[0]), filename)
self.assertEqual(entry[2], funcname)
def test_exception(self):
parser = expat.ParserCreate()
parser.StartElementHandler = self.StartElementHandler
try:
parser.Parse(b"<a><b><c/></b></a>", 1)
self.fail()
except RuntimeError as e:
self.assertEqual(e.args[0], 'a',
"Expected RuntimeError for element 'a', but" + \
" found %r" % e.args[0])
# Check that the traceback contains the relevant line in pyexpat.c
entries = traceback.extract_tb(e.__traceback__)
self.assertEqual(len(entries), 3)
self.check_traceback_entry(entries[0],
"test_pyexpat.py", "test_exception")
self.check_traceback_entry(entries[1],
"pyexpat.c", "StartElement")
self.check_traceback_entry(entries[2],
"test_pyexpat.py", "StartElementHandler")
return
if sysconfig.is_python_build():
self.assertIn('call_with_frame("StartElement"', entries[1][3])
# Test Current* members:
class PositionTest(unittest.TestCase):
def StartElementHandler(self, name, attrs):
self.check_pos('s')
def EndElementHandler(self, name):
self.check_pos('e')
def check_pos(self, event):
pos = (event,
self.parser.CurrentByteIndex,
self.parser.CurrentLineNumber,
self.parser.CurrentColumnNumber)
self.assertTrue(self.upto < len(self.expected_list),
'too many parser events')
expected = self.expected_list[self.upto]
self.assertEqual(pos, expected,
'Expected position %s, got position %s' %(pos, expected))
self.upto += 1
def test(self):
self.parser = expat.ParserCreate()
self.parser.StartElementHandler = self.StartElementHandler
self.parser.EndElementHandler = self.EndElementHandler
self.upto = 0
self.expected_list = [('s', 0, 1, 0), ('s', 5, 2, 1), ('s', 11, 3, 2),
('e', 15, 3, 6), ('e', 17, 4, 1), ('e', 22, 5, 0)]
xml = b'<a>\n <b>\n <c/>\n </b>\n</a>'
self.parser.Parse(xml, 1)
class sf1296433Test(unittest.TestCase):
def test_parse_only_xml_data(self):
# http://python.org/sf/1296433
#
xml = "<?xml version='1.0' encoding='iso8859'?><s>%s</s>" % ('a' * 1025)
# this one doesn't crash
#xml = "<?xml version='1.0'?><s>%s</s>" % ('a' * 10000)
class SpecificException(Exception):
pass
def handler(text):
raise SpecificException
parser = expat.ParserCreate()
parser.CharacterDataHandler = handler
self.assertRaises(Exception, parser.Parse, xml.encode('iso8859'))
class ChardataBufferTest(unittest.TestCase):
"""
test setting of chardata buffer size
"""
def test_1025_bytes(self):
self.assertEqual(self.small_buffer_test(1025), 2)
def test_1000_bytes(self):
self.assertEqual(self.small_buffer_test(1000), 1)
def test_wrong_size(self):
parser = expat.ParserCreate()
parser.buffer_text = 1
with self.assertRaises(ValueError):
parser.buffer_size = -1
with self.assertRaises(ValueError):
parser.buffer_size = 0
with self.assertRaises((ValueError, OverflowError)):
parser.buffer_size = sys.maxsize + 1
with self.assertRaises(TypeError):
parser.buffer_size = 512.0
def test_unchanged_size(self):
xml1 = b"<?xml version='1.0' encoding='iso8859'?><s>" + b'a' * 512
xml2 = b'a'*512 + b'</s>'
parser = expat.ParserCreate()
parser.CharacterDataHandler = self.counting_handler
parser.buffer_size = 512
parser.buffer_text = 1
# Feed 512 bytes of character data: the handler should be called
# once.
self.n = 0
parser.Parse(xml1)
self.assertEqual(self.n, 1)
# Reassign to buffer_size, but assign the same size.
parser.buffer_size = parser.buffer_size
self.assertEqual(self.n, 1)
# Try parsing rest of the document
parser.Parse(xml2)
self.assertEqual(self.n, 2)
def test_disabling_buffer(self):
xml1 = b"<?xml version='1.0' encoding='iso8859'?><a>" + b'a' * 512
xml2 = b'b' * 1024
xml3 = b'c' * 1024 + b'</a>';
parser = expat.ParserCreate()
parser.CharacterDataHandler = self.counting_handler
parser.buffer_text = 1
parser.buffer_size = 1024
self.assertEqual(parser.buffer_size, 1024)
# Parse one chunk of XML
self.n = 0
parser.Parse(xml1, 0)
self.assertEqual(parser.buffer_size, 1024)
self.assertEqual(self.n, 1)
# Turn off buffering and parse the next chunk.
parser.buffer_text = 0
self.assertFalse(parser.buffer_text)
self.assertEqual(parser.buffer_size, 1024)
for i in range(10):
parser.Parse(xml2, 0)
self.assertEqual(self.n, 11)
parser.buffer_text = 1
self.assertTrue(parser.buffer_text)
self.assertEqual(parser.buffer_size, 1024)
parser.Parse(xml3, 1)
self.assertEqual(self.n, 12)
def counting_handler(self, text):
self.n += 1
def small_buffer_test(self, buffer_len):
xml = b"<?xml version='1.0' encoding='iso8859'?><s>" + b'a' * buffer_len + b'</s>'
parser = expat.ParserCreate()
parser.CharacterDataHandler = self.counting_handler
parser.buffer_size = 1024
parser.buffer_text = 1
self.n = 0
parser.Parse(xml)
return self.n
def test_change_size_1(self):
xml1 = b"<?xml version='1.0' encoding='iso8859'?><a><s>" + b'a' * 1024
xml2 = b'aaa</s><s>' + b'a' * 1025 + b'</s></a>'
parser = expat.ParserCreate()
parser.CharacterDataHandler = self.counting_handler
parser.buffer_text = 1
parser.buffer_size = 1024
self.assertEqual(parser.buffer_size, 1024)
self.n = 0
parser.Parse(xml1, 0)
parser.buffer_size *= 2
self.assertEqual(parser.buffer_size, 2048)
parser.Parse(xml2, 1)
self.assertEqual(self.n, 2)
def test_change_size_2(self):
xml1 = b"<?xml version='1.0' encoding='iso8859'?><a>a<s>" + b'a' * 1023
xml2 = b'aaa</s><s>' + b'a' * 1025 + b'</s></a>'
parser = expat.ParserCreate()
parser.CharacterDataHandler = self.counting_handler
parser.buffer_text = 1
parser.buffer_size = 2048
self.assertEqual(parser.buffer_size, 2048)
self.n=0
parser.Parse(xml1, 0)
parser.buffer_size = parser.buffer_size // 2
self.assertEqual(parser.buffer_size, 1024)
parser.Parse(xml2, 1)
self.assertEqual(self.n, 4)
class MalformedInputTest(unittest.TestCase):
def test1(self):
xml = b"\0\r\n"
parser = expat.ParserCreate()
try:
parser.Parse(xml, True)
self.fail()
except expat.ExpatError as e:
self.assertEqual(str(e), 'unclosed token: line 2, column 0')
def test2(self):
# \xc2\x85 is UTF-8 encoded U+0085 (NEXT LINE)
xml = b"<?xml version\xc2\x85='1.0'?>\r\n"
parser = expat.ParserCreate()
err_pattern = r'XML declaration not well-formed: line 1, column \d+'
with self.assertRaisesRegex(expat.ExpatError, err_pattern):
parser.Parse(xml, True)
class ErrorMessageTest(unittest.TestCase):
def test_codes(self):
# verify mapping of errors.codes and errors.messages
self.assertEqual(errors.XML_ERROR_SYNTAX,
errors.messages[errors.codes[errors.XML_ERROR_SYNTAX]])
def test_expaterror(self):
xml = b'<'
parser = expat.ParserCreate()
try:
parser.Parse(xml, True)
self.fail()
except expat.ExpatError as e:
self.assertEqual(e.code,
errors.codes[errors.XML_ERROR_UNCLOSED_TOKEN])
class ForeignDTDTests(unittest.TestCase):
"""
Tests for the UseForeignDTD method of expat parser objects.
"""
def test_use_foreign_dtd(self):
"""
If UseForeignDTD is passed True and a document without an external
entity reference is parsed, ExternalEntityRefHandler is first called
with None for the public and system ids.
"""
handler_call_args = []
def resolve_entity(context, base, system_id, public_id):
handler_call_args.append((public_id, system_id))
return 1
parser = expat.ParserCreate()
parser.UseForeignDTD(True)
parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS)
parser.ExternalEntityRefHandler = resolve_entity
parser.Parse(b"<?xml version='1.0'?><element/>")
self.assertEqual(handler_call_args, [(None, None)])
# test UseForeignDTD() is equal to UseForeignDTD(True)
handler_call_args[:] = []
parser = expat.ParserCreate()
parser.UseForeignDTD()
parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS)
parser.ExternalEntityRefHandler = resolve_entity
parser.Parse(b"<?xml version='1.0'?><element/>")
self.assertEqual(handler_call_args, [(None, None)])
def test_ignore_use_foreign_dtd(self):
"""
If UseForeignDTD is passed True and a document with an external
entity reference is parsed, ExternalEntityRefHandler is called with
the public and system ids from the document.
"""
handler_call_args = []
def resolve_entity(context, base, system_id, public_id):
handler_call_args.append((public_id, system_id))
return 1
parser = expat.ParserCreate()
parser.UseForeignDTD(True)
parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS)
parser.ExternalEntityRefHandler = resolve_entity
parser.Parse(
b"<?xml version='1.0'?><!DOCTYPE foo PUBLIC 'bar' 'baz'><element/>")
self.assertEqual(handler_call_args, [("bar", "baz")])
if __name__ == "__main__":
unittest.main()
| 27,178 | 735 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_uu.py | """
Tests for uu module.
Nick Mathewson
"""
import unittest
from test import support
import sys
import uu
import io
plaintext = b"The smooth-scaled python crept over the sleeping dog\n"
encodedtext = b"""\
M5&AE('-M;V]T:\"US8V%L960@<'ET:&]N(&-R97!T(&]V97(@=&AE('-L965P
(:6YG(&1O9PH """
# Stolen from io.py
class FakeIO(io.TextIOWrapper):
"""Text I/O implementation using an in-memory buffer.
Can be a used as a drop-in replacement for sys.stdin and sys.stdout.
"""
# XXX This is really slow, but fully functional
def __init__(self, initial_value="", encoding="utf-8",
errors="strict", newline="\n"):
super(FakeIO, self).__init__(io.BytesIO(),
encoding=encoding,
errors=errors,
newline=newline)
self._encoding = encoding
self._errors = errors
if initial_value:
if not isinstance(initial_value, str):
initial_value = str(initial_value)
self.write(initial_value)
self.seek(0)
def getvalue(self):
self.flush()
return self.buffer.getvalue().decode(self._encoding, self._errors)
def encodedtextwrapped(mode, filename):
return (bytes("begin %03o %s\n" % (mode, filename), "ascii") +
encodedtext + b"\n \nend\n")
class UUTest(unittest.TestCase):
def test_encode(self):
inp = io.BytesIO(plaintext)
out = io.BytesIO()
uu.encode(inp, out, "t1")
self.assertEqual(out.getvalue(), encodedtextwrapped(0o666, "t1"))
inp = io.BytesIO(plaintext)
out = io.BytesIO()
uu.encode(inp, out, "t1", 0o644)
self.assertEqual(out.getvalue(), encodedtextwrapped(0o644, "t1"))
def test_decode(self):
inp = io.BytesIO(encodedtextwrapped(0o666, "t1"))
out = io.BytesIO()
uu.decode(inp, out)
self.assertEqual(out.getvalue(), plaintext)
inp = io.BytesIO(
b"UUencoded files may contain many lines,\n" +
b"even some that have 'begin' in them.\n" +
encodedtextwrapped(0o666, "t1")
)
out = io.BytesIO()
uu.decode(inp, out)
self.assertEqual(out.getvalue(), plaintext)
def test_truncatedinput(self):
inp = io.BytesIO(b"begin 644 t1\n" + encodedtext)
out = io.BytesIO()
try:
uu.decode(inp, out)
self.fail("No exception raised")
except uu.Error as e:
self.assertEqual(str(e), "Truncated input file")
def test_missingbegin(self):
inp = io.BytesIO(b"")
out = io.BytesIO()
try:
uu.decode(inp, out)
self.fail("No exception raised")
except uu.Error as e:
self.assertEqual(str(e), "No valid begin line found in input file")
def test_garbage_padding(self):
# Issue #22406
encodedtext = (
b"begin 644 file\n"
# length 1; bits 001100 111111 111111 111111
b"\x21\x2C\x5F\x5F\x5F\n"
b"\x20\n"
b"end\n"
)
plaintext = b"\x33" # 00110011
with self.subTest("uu.decode()"):
inp = io.BytesIO(encodedtext)
out = io.BytesIO()
uu.decode(inp, out, quiet=True)
self.assertEqual(out.getvalue(), plaintext)
return
with self.subTest("uu_codec"):
import codecs
decoded = codecs.decode(encodedtext, "uu_codec")
self.assertEqual(decoded, plaintext)
def test_newlines_escaped(self):
# Test newlines are escaped with uu.encode
inp = io.BytesIO(plaintext)
out = io.BytesIO()
filename = "test.txt\n\roverflow.txt"
safefilename = b"test.txt\\n\\roverflow.txt"
uu.encode(inp, out, filename)
self.assertIn(safefilename, out.getvalue())
class UUStdIOTest(unittest.TestCase):
def setUp(self):
self.stdin = sys.stdin
self.stdout = sys.stdout
def tearDown(self):
sys.stdin = self.stdin
sys.stdout = self.stdout
def test_encode(self):
sys.stdin = FakeIO(plaintext.decode("ascii"))
sys.stdout = FakeIO()
uu.encode("-", "-", "t1", 0o666)
self.assertEqual(sys.stdout.getvalue(),
encodedtextwrapped(0o666, "t1").decode("ascii"))
def test_decode(self):
sys.stdin = FakeIO(encodedtextwrapped(0o666, "t1").decode("ascii"))
sys.stdout = FakeIO()
uu.decode("-", "-")
stdout = sys.stdout
sys.stdout = self.stdout
sys.stdin = self.stdin
self.assertEqual(stdout.getvalue(), plaintext.decode("ascii"))
class UUFileTest(unittest.TestCase):
def setUp(self):
self.tmpin = support.TESTFN + "i"
self.tmpout = support.TESTFN + "o"
self.addCleanup(support.unlink, self.tmpin)
self.addCleanup(support.unlink, self.tmpout)
def test_encode(self):
with open(self.tmpin, 'wb') as fin:
fin.write(plaintext)
with open(self.tmpin, 'rb') as fin:
with open(self.tmpout, 'wb') as fout:
uu.encode(fin, fout, self.tmpin, mode=0o644)
with open(self.tmpout, 'rb') as fout:
s = fout.read()
self.assertEqual(s, encodedtextwrapped(0o644, self.tmpin))
# in_file and out_file as filenames
uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0o644)
with open(self.tmpout, 'rb') as fout:
s = fout.read()
self.assertEqual(s, encodedtextwrapped(0o644, self.tmpin))
def test_decode(self):
with open(self.tmpin, 'wb') as f:
f.write(encodedtextwrapped(0o644, self.tmpout))
with open(self.tmpin, 'rb') as f:
uu.decode(f)
with open(self.tmpout, 'rb') as f:
s = f.read()
self.assertEqual(s, plaintext)
# XXX is there an xp way to verify the mode?
def test_decode_filename(self):
with open(self.tmpin, 'wb') as f:
f.write(encodedtextwrapped(0o644, self.tmpout))
uu.decode(self.tmpin)
with open(self.tmpout, 'rb') as f:
s = f.read()
self.assertEqual(s, plaintext)
def test_decodetwice(self):
# Verify that decode() will refuse to overwrite an existing file
with open(self.tmpin, 'wb') as f:
f.write(encodedtextwrapped(0o644, self.tmpout))
with open(self.tmpin, 'rb') as f:
uu.decode(f)
with open(self.tmpin, 'rb') as f:
self.assertRaises(uu.Error, uu.decode, f)
def test_main():
support.run_unittest(UUTest,
UUStdIOTest,
UUFileTest,
)
if __name__=="__main__":
test_main()
| 6,875 | 219 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/xmltests.py | # Convenience test module to run all of the XML-related tests in the
# standard library.
import sys
import test.support
test.support.verbose = 0
def runtest(name):
__import__(name)
module = sys.modules[name]
if hasattr(module, "test_main"):
module.test_main()
runtest("test.test_minidom")
runtest("test.test_pyexpat")
runtest("test.test_sax")
runtest("test.test_xml_dom_minicompat")
runtest("test.test_xml_etree")
runtest("test.test_xml_etree_c")
runtest("test.test_xmlrpc")
| 499 | 22 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/BIG5.TXT | #
# Name: BIG5 to Unicode table (complete)
# Unicode version: 1.1
# Table version: 1.0
# Table format: Format A
# Date: 2011 October 14
#
# Copyright (c) 1994-2011 Unicode, Inc. All Rights reserved.
#
# This file is provided as-is by Unicode, Inc. (The Unicode Consortium).
# No claims are made as to fitness for any particular purpose. No
# warranties of any kind are expressed or implied. The recipient
# agrees to determine applicability of information provided. If this
# file has been provided on magnetic media by Unicode, Inc., the sole
# remedy for any claim will be exchange of defective media within 90
# days of receipt.
#
# Unicode, Inc. hereby grants the right to freely use the information
# supplied in this file in the creation of products supporting the
# Unicode Standard, and to make copies of this file in any form for
# internal or external distribution as long as this notice remains
# attached.
#
# General notes:
#
#
# This table contains one set of mappings from BIG5 into Unicode.
# Note that these data are *possible* mappings only and may not be the
# same as those used by actual products, nor may they be the best suited
# for all uses. For more information on the mappings between various code
# pages incorporating the repertoire of BIG5 and Unicode, consult the
# VENDORS mapping data.
#
# WARNING! It is currently impossible to provide round-trip compatibility
# between BIG5 and Unicode.
#
# A number of characters are not currently mapped because
# of conflicts with other mappings. They are as follows:
#
# BIG5 Description Comments
#
# 0xA15A SPACING UNDERSCORE duplicates A1C4
# 0xA1C3 SPACING HEAVY OVERSCORE not in Unicode
# 0xA1C5 SPACING HEAVY UNDERSCORE not in Unicode
# 0xA1FE LT DIAG UP RIGHT TO LOW LEFT duplicates A2AC
# 0xA240 LT DIAG UP LEFT TO LOW RIGHT duplicates A2AD
# 0xA2CC HANGZHOU NUMERAL TEN conflicts with A451 mapping
# 0xA2CE HANGZHOU NUMERAL THIRTY conflicts with A4CA mapping
#
# We currently map all of these characters to U+FFFD REPLACEMENT CHARACTER.
# It is also possible to map these characters to their duplicates, or to
# the user zone.
#
# Notes:
#
# 1. In addition to the above, there is some uncertainty about the
# mappings in the range C6A1 - C8FE, and F9DD - F9FE. The ETEN
# version of BIG5 organizes the former range differently, and adds
# additional characters in the latter range. The correct mappings
# these ranges need to be determined.
#
# 2. There is an uncertainty in the mapping of the Big Five character
# 0xA3BC. This character occurs within the Big Five block of tone marks
# for bopomofo and is intended to be the tone mark for the first tone in
# Mandarin Chinese. We have selected the mapping U+02C9 MODIFIER LETTER
# MACRON (Mandarin Chinese first tone) to reflect this semantic.
# However, because bopomofo uses the absense of a tone mark to indicate
# the first Mandarin tone, most implementations of Big Five represent
# this character with a blank space, and so a mapping such as U+2003 EM
# SPACE might be preferred.
#
# Format: Three tab-separated columns
# Column #1 is the BIG5 code (in hex as 0xXXXX)
# Column #2 is the Unicode (in hex as 0xXXXX)
# Column #3 is the Unicode name (follows a comment sign, '#')
# The official names for Unicode characters U+4E00
# to U+9FA5, inclusive, is "CJK UNIFIED IDEOGRAPH-XXXX",
# where XXXX is the code point. Including all these
# names in this file increases its size substantially
# and needlessly. The token "<CJK>" is used for the
# name of these characters. If necessary, it can be
# expanded algorithmically by a parser or editor.
#
# The entries are in BIG5 order
#
# Revision History:
#
# [v1.0, 2011 October 14]
# Updated terms of use to current wording.
# Updated contact information.
# No changes to the mapping data.
#
# [v0.0d3, 11 February 1994]
# First release.
#
# Use the Unicode reporting form <http://www.unicode.org/reporting.html>
# for any questions or comments or to report errors in the data.
#
A140 3000
A141 FF0C
A142 3001
A143 3002
A144 FF0E
A145 2022
A146 FF1B
A147 FF1A
A148 FF1F
A149 FF01
A14A FE30
A14B 2026
A14C 2025
A14D FE50
A14E FF64
A14F FE52
A150 00B7
A151 FE54
A152 FE55
A153 FE56
A154 FE57
A155 FF5C
A156 2013
A157 FE31
A158 2014
A159 FE33
A15A FFFD
A15B FE34
A15C FE4F
A15D FF08
A15E FF09
A15F FE35
A160 FE36
A161 FF5B
A162 FF5D
A163 FE37
A164 FE38
A165 3014
A166 3015
A167 FE39
A168 FE3A
A169 3010
A16A 3011
A16B FE3B
A16C FE3C
A16D 300A
A16E 300B
A16F FE3D
A170 FE3E
A171 3008
A172 3009
A173 FE3F
A174 FE40
A175 300C
A176 300D
A177 FE41
A178 FE42
A179 300E
A17A 300F
A17B FE43
A17C FE44
A17D FE59
A17E FE5A
A1A1 FE5B
A1A2 FE5C
A1A3 FE5D
A1A4 FE5E
A1A5 2018
A1A6 2019
A1A7 201C
A1A8 201D
A1A9 301D
A1AA 301E
A1AB 2035
A1AC 2032
A1AD FF03
A1AE FF06
A1AF FF0A
A1B0 203B
A1B1 00A7
A1B2 3003
A1B3 25CB
A1B4 25CF
A1B5 25B3
A1B6 25B2
A1B7 25CE
A1B8 2606
A1B9 2605
A1BA 25C7
A1BB 25C6
A1BC 25A1
A1BD 25A0
A1BE 25BD
A1BF 25BC
A1C0 32A3
A1C1 2105
A1C2 203E
A1C3 FFFD
A1C4 FF3F
A1C5 FFFD
A1C6 FE49
A1C7 FE4A
A1C8 FE4D
A1C9 FE4E
A1CA FE4B
A1CB FE4C
A1CC FE5F
A1CD FE60
A1CE FE61
A1CF FF0B
A1D0 FF0D
A1D1 00D7
A1D2 00F7
A1D3 00B1
A1D4 221A
A1D5 FF1C
A1D6 FF1E
A1D7 FF1D
A1D8 2266
A1D9 2267
A1DA 2260
A1DB 221E
A1DC 2252
A1DD 2261
A1DE FE62
A1DF FE63
A1E0 FE64
A1E1 FE65
A1E2 FE66
A1E3 223C
A1E4 2229
A1E5 222A
A1E6 22A5
A1E7 2220
A1E8 221F
A1E9 22BF
A1EA 33D2
A1EB 33D1
A1EC 222B
A1ED 222E
A1EE 2235
A1EF 2234
A1F0 2640
A1F1 2642
A1F2 2641
A1F3 2609
A1F4 2191
A1F5 2193
A1F6 2190
A1F7 2192
A1F8 2196
A1F9 2197
A1FA 2199
A1FB 2198
A1FC 2225
A1FD 2223
A1FE FFFD
A240 FFFD
A241 FF0F
A242 FF3C
A243 FF04
A244 00A5
A245 3012
A246 00A2
A247 00A3
A248 FF05
A249 FF20
A24A 2103
A24B 2109
A24C FE69
A24D FE6A
A24E FE6B
A24F 33D5
A250 339C
A251 339D
A252 339E
A253 33CE
A254 33A1
A255 338E
A256 338F
A257 33C4
A258 00B0
A259 5159
A25A 515B
A25B 515E
A25C 515D
A25D 5161
A25E 5163
A25F 55E7
A260 74E9
A261 7CCE
A262 2581
A263 2582
A264 2583
A265 2584
A266 2585
A267 2586
A268 2587
A269 2588
A26A 258F
A26B 258E
A26C 258D
A26D 258C
A26E 258B
A26F 258A
A270 2589
A271 253C
A272 2534
A273 252C
A274 2524
A275 251C
A276 2594
A277 2500
A278 2502
A279 2595
A27A 250C
A27B 2510
A27C 2514
A27D 2518
A27E 256D
A2A1 256E
A2A2 2570
A2A3 256F
A2A4 2550
A2A5 255E
A2A6 256A
A2A7 2561
A2A8 25E2
A2A9 25E3
A2AA 25E5
A2AB 25E4
A2AC 2571
A2AD 2572
A2AE 2573
A2AF FF10
A2B0 FF11
A2B1 FF12
A2B2 FF13
A2B3 FF14
A2B4 FF15
A2B5 FF16
A2B6 FF17
A2B7 FF18
A2B8 FF19
A2B9 2160
A2BA 2161
A2BB 2162
A2BC 2163
A2BD 2164
A2BE 2165
A2BF 2166
A2C0 2167
A2C1 2168
A2C2 2169
A2C3 3021
A2C4 3022
A2C5 3023
A2C6 3024
A2C7 3025
A2C8 3026
A2C9 3027
A2CA 3028
A2CB 3029
A2CC FFFD
A2CD 5344
A2CE FFFD
A2CF FF21
A2D0 FF22
A2D1 FF23
A2D2 FF24
A2D3 FF25
A2D4 FF26
A2D5 FF27
A2D6 FF28
A2D7 FF29
A2D8 FF2A
A2D9 FF2B
A2DA FF2C
A2DB FF2D
A2DC FF2E
A2DD FF2F
A2DE FF30
A2DF FF31
A2E0 FF32
A2E1 FF33
A2E2 FF34
A2E3 FF35
A2E4 FF36
A2E5 FF37
A2E6 FF38
A2E7 FF39
A2E8 FF3A
A2E9 FF41
A2EA FF42
A2EB FF43
A2EC FF44
A2ED FF45
A2EE FF46
A2EF FF47
A2F0 FF48
A2F1 FF49
A2F2 FF4A
A2F3 FF4B
A2F4 FF4C
A2F5 FF4D
A2F6 FF4E
A2F7 FF4F
A2F8 FF50
A2F9 FF51
A2FA FF52
A2FB FF53
A2FC FF54
A2FD FF55
A2FE FF56
A340 FF57
A341 FF58
A342 FF59
A343 FF5A
A344 0391
A345 0392
A346 0393
A347 0394
A348 0395
A349 0396
A34A 0397
A34B 0398
A34C 0399
A34D 039A
A34E 039B
A34F 039C
A350 039D
A351 039E
A352 039F
A353 03A0
A354 03A1
A355 03A3
A356 03A4
A357 03A5
A358 03A6
A359 03A7
A35A 03A8
A35B 03A9
A35C 03B1
A35D 03B2
A35E 03B3
A35F 03B4
A360 03B5
A361 03B6
A362 03B7
A363 03B8
A364 03B9
A365 03BA
A366 03BB
A367 03BC
A368 03BD
A369 03BE
A36A 03BF
A36B 03C0
A36C 03C1
A36D 03C3
A36E 03C4
A36F 03C5
A370 03C6
A371 03C7
A372 03C8
A373 03C9
A374 3105
A375 3106
A376 3107
A377 3108
A378 3109
A379 310A
A37A 310B
A37B 310C
A37C 310D
A37D 310E
A37E 310F
A3A1 3110
A3A2 3111
A3A3 3112
A3A4 3113
A3A5 3114
A3A6 3115
A3A7 3116
A3A8 3117
A3A9 3118
A3AA 3119
A3AB 311A
A3AC 311B
A3AD 311C
A3AE 311D
A3AF 311E
A3B0 311F
A3B1 3120
A3B2 3121
A3B3 3122
A3B4 3123
A3B5 3124
A3B6 3125
A3B7 3126
A3B8 3127
A3B9 3128
A3BA 3129
A3BB 02D9
A3BC 02C9
A3BD 02CA
A3BE 02C7
A3BF 02CB
A440 4E00
A441 4E59
A442 4E01
A443 4E03
A444 4E43
A445 4E5D
A446 4E86
A447 4E8C
A448 4EBA
A449 513F
A44A 5165
A44B 516B
A44C 51E0
A44D 5200
A44E 5201
A44F 529B
A450 5315
A451 5341
A452 535C
A453 53C8
A454 4E09
A455 4E0B
A456 4E08
A457 4E0A
A458 4E2B
A459 4E38
A45A 51E1
A45B 4E45
A45C 4E48
A45D 4E5F
A45E 4E5E
A45F 4E8E
A460 4EA1
A461 5140
A462 5203
A463 52FA
A464 5343
A465 53C9
A466 53E3
A467 571F
A468 58EB
A469 5915
A46A 5927
A46B 5973
A46C 5B50
A46D 5B51
A46E 5B53
A46F 5BF8
A470 5C0F
A471 5C22
A472 5C38
A473 5C71
A474 5DDD
A475 5DE5
A476 5DF1
A477 5DF2
A478 5DF3
A479 5DFE
A47A 5E72
A47B 5EFE
A47C 5F0B
A47D 5F13
A47E 624D
A4A1 4E11
A4A2 4E10
A4A3 4E0D
A4A4 4E2D
A4A5 4E30
A4A6 4E39
A4A7 4E4B
A4A8 5C39
A4A9 4E88
A4AA 4E91
A4AB 4E95
A4AC 4E92
A4AD 4E94
A4AE 4EA2
A4AF 4EC1
A4B0 4EC0
A4B1 4EC3
A4B2 4EC6
A4B3 4EC7
A4B4 4ECD
A4B5 4ECA
A4B6 4ECB
A4B7 4EC4
A4B8 5143
A4B9 5141
A4BA 5167
A4BB 516D
A4BC 516E
A4BD 516C
A4BE 5197
A4BF 51F6
A4C0 5206
A4C1 5207
A4C2 5208
A4C3 52FB
A4C4 52FE
A4C5 52FF
A4C6 5316
A4C7 5339
A4C8 5348
A4C9 5347
A4CA 5345
A4CB 535E
A4CC 5384
A4CD 53CB
A4CE 53CA
A4CF 53CD
A4D0 58EC
A4D1 5929
A4D2 592B
A4D3 592A
A4D4 592D
A4D5 5B54
A4D6 5C11
A4D7 5C24
A4D8 5C3A
A4D9 5C6F
A4DA 5DF4
A4DB 5E7B
A4DC 5EFF
A4DD 5F14
A4DE 5F15
A4DF 5FC3
A4E0 6208
A4E1 6236
A4E2 624B
A4E3 624E
A4E4 652F
A4E5 6587
A4E6 6597
A4E7 65A4
A4E8 65B9
A4E9 65E5
A4EA 66F0
A4EB 6708
A4EC 6728
A4ED 6B20
A4EE 6B62
A4EF 6B79
A4F0 6BCB
A4F1 6BD4
A4F2 6BDB
A4F3 6C0F
A4F4 6C34
A4F5 706B
A4F6 722A
A4F7 7236
A4F8 723B
A4F9 7247
A4FA 7259
A4FB 725B
A4FC 72AC
A4FD 738B
A4FE 4E19
A540 4E16
A541 4E15
A542 4E14
A543 4E18
A544 4E3B
A545 4E4D
A546 4E4F
A547 4E4E
A548 4EE5
A549 4ED8
A54A 4ED4
A54B 4ED5
A54C 4ED6
A54D 4ED7
A54E 4EE3
A54F 4EE4
A550 4ED9
A551 4EDE
A552 5145
A553 5144
A554 5189
A555 518A
A556 51AC
A557 51F9
A558 51FA
A559 51F8
A55A 520A
A55B 52A0
A55C 529F
A55D 5305
A55E 5306
A55F 5317
A560 531D
A561 4EDF
A562 534A
A563 5349
A564 5361
A565 5360
A566 536F
A567 536E
A568 53BB
A569 53EF
A56A 53E4
A56B 53F3
A56C 53EC
A56D 53EE
A56E 53E9
A56F 53E8
A570 53FC
A571 53F8
A572 53F5
A573 53EB
A574 53E6
A575 53EA
A576 53F2
A577 53F1
A578 53F0
A579 53E5
A57A 53ED
A57B 53FB
A57C 56DB
A57D 56DA
A57E 5916
A5A1 592E
A5A2 5931
A5A3 5974
A5A4 5976
A5A5 5B55
A5A6 5B83
A5A7 5C3C
A5A8 5DE8
A5A9 5DE7
A5AA 5DE6
A5AB 5E02
A5AC 5E03
A5AD 5E73
A5AE 5E7C
A5AF 5F01
A5B0 5F18
A5B1 5F17
A5B2 5FC5
A5B3 620A
A5B4 6253
A5B5 6254
A5B6 6252
A5B7 6251
A5B8 65A5
A5B9 65E6
A5BA 672E
A5BB 672C
A5BC 672A
A5BD 672B
A5BE 672D
A5BF 6B63
A5C0 6BCD
A5C1 6C11
A5C2 6C10
A5C3 6C38
A5C4 6C41
A5C5 6C40
A5C6 6C3E
A5C7 72AF
A5C8 7384
A5C9 7389
A5CA 74DC
A5CB 74E6
A5CC 7518
A5CD 751F
A5CE 7528
A5CF 7529
A5D0 7530
A5D1 7531
A5D2 7532
A5D3 7533
A5D4 758B
A5D5 767D
A5D6 76AE
A5D7 76BF
A5D8 76EE
A5D9 77DB
A5DA 77E2
A5DB 77F3
A5DC 793A
A5DD 79BE
A5DE 7A74
A5DF 7ACB
A5E0 4E1E
A5E1 4E1F
A5E2 4E52
A5E3 4E53
A5E4 4E69
A5E5 4E99
A5E6 4EA4
A5E7 4EA6
A5E8 4EA5
A5E9 4EFF
A5EA 4F09
A5EB 4F19
A5EC 4F0A
A5ED 4F15
A5EE 4F0D
A5EF 4F10
A5F0 4F11
A5F1 4F0F
A5F2 4EF2
A5F3 4EF6
A5F4 4EFB
A5F5 4EF0
A5F6 4EF3
A5F7 4EFD
A5F8 4F01
A5F9 4F0B
A5FA 5149
A5FB 5147
A5FC 5146
A5FD 5148
A5FE 5168
A640 5171
A641 518D
A642 51B0
A643 5217
A644 5211
A645 5212
A646 520E
A647 5216
A648 52A3
A649 5308
A64A 5321
A64B 5320
A64C 5370
A64D 5371
A64E 5409
A64F 540F
A650 540C
A651 540A
A652 5410
A653 5401
A654 540B
A655 5404
A656 5411
A657 540D
A658 5408
A659 5403
A65A 540E
A65B 5406
A65C 5412
A65D 56E0
A65E 56DE
A65F 56DD
A660 5733
A661 5730
A662 5728
A663 572D
A664 572C
A665 572F
A666 5729
A667 5919
A668 591A
A669 5937
A66A 5938
A66B 5984
A66C 5978
A66D 5983
A66E 597D
A66F 5979
A670 5982
A671 5981
A672 5B57
A673 5B58
A674 5B87
A675 5B88
A676 5B85
A677 5B89
A678 5BFA
A679 5C16
A67A 5C79
A67B 5DDE
A67C 5E06
A67D 5E76
A67E 5E74
A6A1 5F0F
A6A2 5F1B
A6A3 5FD9
A6A4 5FD6
A6A5 620E
A6A6 620C
A6A7 620D
A6A8 6210
A6A9 6263
A6AA 625B
A6AB 6258
A6AC 6536
A6AD 65E9
A6AE 65E8
A6AF 65EC
A6B0 65ED
A6B1 66F2
A6B2 66F3
A6B3 6709
A6B4 673D
A6B5 6734
A6B6 6731
A6B7 6735
A6B8 6B21
A6B9 6B64
A6BA 6B7B
A6BB 6C16
A6BC 6C5D
A6BD 6C57
A6BE 6C59
A6BF 6C5F
A6C0 6C60
A6C1 6C50
A6C2 6C55
A6C3 6C61
A6C4 6C5B
A6C5 6C4D
A6C6 6C4E
A6C7 7070
A6C8 725F
A6C9 725D
A6CA 767E
A6CB 7AF9
A6CC 7C73
A6CD 7CF8
A6CE 7F36
A6CF 7F8A
A6D0 7FBD
A6D1 8001
A6D2 8003
A6D3 800C
A6D4 8012
A6D5 8033
A6D6 807F
A6D7 8089
A6D8 808B
A6D9 808C
A6DA 81E3
A6DB 81EA
A6DC 81F3
A6DD 81FC
A6DE 820C
A6DF 821B
A6E0 821F
A6E1 826E
A6E2 8272
A6E3 827E
A6E4 866B
A6E5 8840
A6E6 884C
A6E7 8863
A6E8 897F
A6E9 9621
A6EA 4E32
A6EB 4EA8
A6EC 4F4D
A6ED 4F4F
A6EE 4F47
A6EF 4F57
A6F0 4F5E
A6F1 4F34
A6F2 4F5B
A6F3 4F55
A6F4 4F30
A6F5 4F50
A6F6 4F51
A6F7 4F3D
A6F8 4F3A
A6F9 4F38
A6FA 4F43
A6FB 4F54
A6FC 4F3C
A6FD 4F46
A6FE 4F63
A740 4F5C
A741 4F60
A742 4F2F
A743 4F4E
A744 4F36
A745 4F59
A746 4F5D
A747 4F48
A748 4F5A
A749 514C
A74A 514B
A74B 514D
A74C 5175
A74D 51B6
A74E 51B7
A74F 5225
A750 5224
A751 5229
A752 522A
A753 5228
A754 52AB
A755 52A9
A756 52AA
A757 52AC
A758 5323
A759 5373
A75A 5375
A75B 541D
A75C 542D
A75D 541E
A75E 543E
A75F 5426
A760 544E
A761 5427
A762 5446
A763 5443
A764 5433
A765 5448
A766 5442
A767 541B
A768 5429
A769 544A
A76A 5439
A76B 543B
A76C 5438
A76D 542E
A76E 5435
A76F 5436
A770 5420
A771 543C
A772 5440
A773 5431
A774 542B
A775 541F
A776 542C
A777 56EA
A778 56F0
A779 56E4
A77A 56EB
A77B 574A
A77C 5751
A77D 5740
A77E 574D
A7A1 5747
A7A2 574E
A7A3 573E
A7A4 5750
A7A5 574F
A7A6 573B
A7A7 58EF
A7A8 593E
A7A9 599D
A7AA 5992
A7AB 59A8
A7AC 599E
A7AD 59A3
A7AE 5999
A7AF 5996
A7B0 598D
A7B1 59A4
A7B2 5993
A7B3 598A
A7B4 59A5
A7B5 5B5D
A7B6 5B5C
A7B7 5B5A
A7B8 5B5B
A7B9 5B8C
A7BA 5B8B
A7BB 5B8F
A7BC 5C2C
A7BD 5C40
A7BE 5C41
A7BF 5C3F
A7C0 5C3E
A7C1 5C90
A7C2 5C91
A7C3 5C94
A7C4 5C8C
A7C5 5DEB
A7C6 5E0C
A7C7 5E8F
A7C8 5E87
A7C9 5E8A
A7CA 5EF7
A7CB 5F04
A7CC 5F1F
A7CD 5F64
A7CE 5F62
A7CF 5F77
A7D0 5F79
A7D1 5FD8
A7D2 5FCC
A7D3 5FD7
A7D4 5FCD
A7D5 5FF1
A7D6 5FEB
A7D7 5FF8
A7D8 5FEA
A7D9 6212
A7DA 6211
A7DB 6284
A7DC 6297
A7DD 6296
A7DE 6280
A7DF 6276
A7E0 6289
A7E1 626D
A7E2 628A
A7E3 627C
A7E4 627E
A7E5 6279
A7E6 6273
A7E7 6292
A7E8 626F
A7E9 6298
A7EA 626E
A7EB 6295
A7EC 6293
A7ED 6291
A7EE 6286
A7EF 6539
A7F0 653B
A7F1 6538
A7F2 65F1
A7F3 66F4
A7F4 675F
A7F5 674E
A7F6 674F
A7F7 6750
A7F8 6751
A7F9 675C
A7FA 6756
A7FB 675E
A7FC 6749
A7FD 6746
A7FE 6760
A840 6753
A841 6757
A842 6B65
A843 6BCF
A844 6C42
A845 6C5E
A846 6C99
A847 6C81
A848 6C88
A849 6C89
A84A 6C85
A84B 6C9B
A84C 6C6A
A84D 6C7A
A84E 6C90
A84F 6C70
A850 6C8C
A851 6C68
A852 6C96
A853 6C92
A854 6C7D
A855 6C83
A856 6C72
A857 6C7E
A858 6C74
A859 6C86
A85A 6C76
A85B 6C8D
A85C 6C94
A85D 6C98
A85E 6C82
A85F 7076
A860 707C
A861 707D
A862 7078
A863 7262
A864 7261
A865 7260
A866 72C4
A867 72C2
A868 7396
A869 752C
A86A 752B
A86B 7537
A86C 7538
A86D 7682
A86E 76EF
A86F 77E3
A870 79C1
A871 79C0
A872 79BF
A873 7A76
A874 7CFB
A875 7F55
A876 8096
A877 8093
A878 809D
A879 8098
A87A 809B
A87B 809A
A87C 80B2
A87D 826F
A87E 8292
A8A1 828B
A8A2 828D
A8A3 898B
A8A4 89D2
A8A5 8A00
A8A6 8C37
A8A7 8C46
A8A8 8C55
A8A9 8C9D
A8AA 8D64
A8AB 8D70
A8AC 8DB3
A8AD 8EAB
A8AE 8ECA
A8AF 8F9B
A8B0 8FB0
A8B1 8FC2
A8B2 8FC6
A8B3 8FC5
A8B4 8FC4
A8B5 5DE1
A8B6 9091
A8B7 90A2
A8B8 90AA
A8B9 90A6
A8BA 90A3
A8BB 9149
A8BC 91C6
A8BD 91CC
A8BE 9632
A8BF 962E
A8C0 9631
A8C1 962A
A8C2 962C
A8C3 4E26
A8C4 4E56
A8C5 4E73
A8C6 4E8B
A8C7 4E9B
A8C8 4E9E
A8C9 4EAB
A8CA 4EAC
A8CB 4F6F
A8CC 4F9D
A8CD 4F8D
A8CE 4F73
A8CF 4F7F
A8D0 4F6C
A8D1 4F9B
A8D2 4F8B
A8D3 4F86
A8D4 4F83
A8D5 4F70
A8D6 4F75
A8D7 4F88
A8D8 4F69
A8D9 4F7B
A8DA 4F96
A8DB 4F7E
A8DC 4F8F
A8DD 4F91
A8DE 4F7A
A8DF 5154
A8E0 5152
A8E1 5155
A8E2 5169
A8E3 5177
A8E4 5176
A8E5 5178
A8E6 51BD
A8E7 51FD
A8E8 523B
A8E9 5238
A8EA 5237
A8EB 523A
A8EC 5230
A8ED 522E
A8EE 5236
A8EF 5241
A8F0 52BE
A8F1 52BB
A8F2 5352
A8F3 5354
A8F4 5353
A8F5 5351
A8F6 5366
A8F7 5377
A8F8 5378
A8F9 5379
A8FA 53D6
A8FB 53D4
A8FC 53D7
A8FD 5473
A8FE 5475
A940 5496
A941 5478
A942 5495
A943 5480
A944 547B
A945 5477
A946 5484
A947 5492
A948 5486
A949 547C
A94A 5490
A94B 5471
A94C 5476
A94D 548C
A94E 549A
A94F 5462
A950 5468
A951 548B
A952 547D
A953 548E
A954 56FA
A955 5783
A956 5777
A957 576A
A958 5769
A959 5761
A95A 5766
A95B 5764
A95C 577C
A95D 591C
A95E 5949
A95F 5947
A960 5948
A961 5944
A962 5954
A963 59BE
A964 59BB
A965 59D4
A966 59B9
A967 59AE
A968 59D1
A969 59C6
A96A 59D0
A96B 59CD
A96C 59CB
A96D 59D3
A96E 59CA
A96F 59AF
A970 59B3
A971 59D2
A972 59C5
A973 5B5F
A974 5B64
A975 5B63
A976 5B97
A977 5B9A
A978 5B98
A979 5B9C
A97A 5B99
A97B 5B9B
A97C 5C1A
A97D 5C48
A97E 5C45
A9A1 5C46
A9A2 5CB7
A9A3 5CA1
A9A4 5CB8
A9A5 5CA9
A9A6 5CAB
A9A7 5CB1
A9A8 5CB3
A9A9 5E18
A9AA 5E1A
A9AB 5E16
A9AC 5E15
A9AD 5E1B
A9AE 5E11
A9AF 5E78
A9B0 5E9A
A9B1 5E97
A9B2 5E9C
A9B3 5E95
A9B4 5E96
A9B5 5EF6
A9B6 5F26
A9B7 5F27
A9B8 5F29
A9B9 5F80
A9BA 5F81
A9BB 5F7F
A9BC 5F7C
A9BD 5FDD
A9BE 5FE0
A9BF 5FFD
A9C0 5FF5
A9C1 5FFF
A9C2 600F
A9C3 6014
A9C4 602F
A9C5 6035
A9C6 6016
A9C7 602A
A9C8 6015
A9C9 6021
A9CA 6027
A9CB 6029
A9CC 602B
A9CD 601B
A9CE 6216
A9CF 6215
A9D0 623F
A9D1 623E
A9D2 6240
A9D3 627F
A9D4 62C9
A9D5 62CC
A9D6 62C4
A9D7 62BF
A9D8 62C2
A9D9 62B9
A9DA 62D2
A9DB 62DB
A9DC 62AB
A9DD 62D3
A9DE 62D4
A9DF 62CB
A9E0 62C8
A9E1 62A8
A9E2 62BD
A9E3 62BC
A9E4 62D0
A9E5 62D9
A9E6 62C7
A9E7 62CD
A9E8 62B5
A9E9 62DA
A9EA 62B1
A9EB 62D8
A9EC 62D6
A9ED 62D7
A9EE 62C6
A9EF 62AC
A9F0 62CE
A9F1 653E
A9F2 65A7
A9F3 65BC
A9F4 65FA
A9F5 6614
A9F6 6613
A9F7 660C
A9F8 6606
A9F9 6602
A9FA 660E
A9FB 6600
A9FC 660F
A9FD 6615
A9FE 660A
AA40 6607
AA41 670D
AA42 670B
AA43 676D
AA44 678B
AA45 6795
AA46 6771
AA47 679C
AA48 6773
AA49 6777
AA4A 6787
AA4B 679D
AA4C 6797
AA4D 676F
AA4E 6770
AA4F 677F
AA50 6789
AA51 677E
AA52 6790
AA53 6775
AA54 679A
AA55 6793
AA56 677C
AA57 676A
AA58 6772
AA59 6B23
AA5A 6B66
AA5B 6B67
AA5C 6B7F
AA5D 6C13
AA5E 6C1B
AA5F 6CE3
AA60 6CE8
AA61 6CF3
AA62 6CB1
AA63 6CCC
AA64 6CE5
AA65 6CB3
AA66 6CBD
AA67 6CBE
AA68 6CBC
AA69 6CE2
AA6A 6CAB
AA6B 6CD5
AA6C 6CD3
AA6D 6CB8
AA6E 6CC4
AA6F 6CB9
AA70 6CC1
AA71 6CAE
AA72 6CD7
AA73 6CC5
AA74 6CF1
AA75 6CBF
AA76 6CBB
AA77 6CE1
AA78 6CDB
AA79 6CCA
AA7A 6CAC
AA7B 6CEF
AA7C 6CDC
AA7D 6CD6
AA7E 6CE0
AAA1 7095
AAA2 708E
AAA3 7092
AAA4 708A
AAA5 7099
AAA6 722C
AAA7 722D
AAA8 7238
AAA9 7248
AAAA 7267
AAAB 7269
AAAC 72C0
AAAD 72CE
AAAE 72D9
AAAF 72D7
AAB0 72D0
AAB1 73A9
AAB2 73A8
AAB3 739F
AAB4 73AB
AAB5 73A5
AAB6 753D
AAB7 759D
AAB8 7599
AAB9 759A
AABA 7684
AABB 76C2
AABC 76F2
AABD 76F4
AABE 77E5
AABF 77FD
AAC0 793E
AAC1 7940
AAC2 7941
AAC3 79C9
AAC4 79C8
AAC5 7A7A
AAC6 7A79
AAC7 7AFA
AAC8 7CFE
AAC9 7F54
AACA 7F8C
AACB 7F8B
AACC 8005
AACD 80BA
AACE 80A5
AACF 80A2
AAD0 80B1
AAD1 80A1
AAD2 80AB
AAD3 80A9
AAD4 80B4
AAD5 80AA
AAD6 80AF
AAD7 81E5
AAD8 81FE
AAD9 820D
AADA 82B3
AADB 829D
AADC 8299
AADD 82AD
AADE 82BD
AADF 829F
AAE0 82B9
AAE1 82B1
AAE2 82AC
AAE3 82A5
AAE4 82AF
AAE5 82B8
AAE6 82A3
AAE7 82B0
AAE8 82BE
AAE9 82B7
AAEA 864E
AAEB 8671
AAEC 521D
AAED 8868
AAEE 8ECB
AAEF 8FCE
AAF0 8FD4
AAF1 8FD1
AAF2 90B5
AAF3 90B8
AAF4 90B1
AAF5 90B6
AAF6 91C7
AAF7 91D1
AAF8 9577
AAF9 9580
AAFA 961C
AAFB 9640
AAFC 963F
AAFD 963B
AAFE 9644
AB40 9642
AB41 96B9
AB42 96E8
AB43 9752
AB44 975E
AB45 4E9F
AB46 4EAD
AB47 4EAE
AB48 4FE1
AB49 4FB5
AB4A 4FAF
AB4B 4FBF
AB4C 4FE0
AB4D 4FD1
AB4E 4FCF
AB4F 4FDD
AB50 4FC3
AB51 4FB6
AB52 4FD8
AB53 4FDF
AB54 4FCA
AB55 4FD7
AB56 4FAE
AB57 4FD0
AB58 4FC4
AB59 4FC2
AB5A 4FDA
AB5B 4FCE
AB5C 4FDE
AB5D 4FB7
AB5E 5157
AB5F 5192
AB60 5191
AB61 51A0
AB62 524E
AB63 5243
AB64 524A
AB65 524D
AB66 524C
AB67 524B
AB68 5247
AB69 52C7
AB6A 52C9
AB6B 52C3
AB6C 52C1
AB6D 530D
AB6E 5357
AB6F 537B
AB70 539A
AB71 53DB
AB72 54AC
AB73 54C0
AB74 54A8
AB75 54CE
AB76 54C9
AB77 54B8
AB78 54A6
AB79 54B3
AB7A 54C7
AB7B 54C2
AB7C 54BD
AB7D 54AA
AB7E 54C1
ABA1 54C4
ABA2 54C8
ABA3 54AF
ABA4 54AB
ABA5 54B1
ABA6 54BB
ABA7 54A9
ABA8 54A7
ABA9 54BF
ABAA 56FF
ABAB 5782
ABAC 578B
ABAD 57A0
ABAE 57A3
ABAF 57A2
ABB0 57CE
ABB1 57AE
ABB2 5793
ABB3 5955
ABB4 5951
ABB5 594F
ABB6 594E
ABB7 5950
ABB8 59DC
ABB9 59D8
ABBA 59FF
ABBB 59E3
ABBC 59E8
ABBD 5A03
ABBE 59E5
ABBF 59EA
ABC0 59DA
ABC1 59E6
ABC2 5A01
ABC3 59FB
ABC4 5B69
ABC5 5BA3
ABC6 5BA6
ABC7 5BA4
ABC8 5BA2
ABC9 5BA5
ABCA 5C01
ABCB 5C4E
ABCC 5C4F
ABCD 5C4D
ABCE 5C4B
ABCF 5CD9
ABD0 5CD2
ABD1 5DF7
ABD2 5E1D
ABD3 5E25
ABD4 5E1F
ABD5 5E7D
ABD6 5EA0
ABD7 5EA6
ABD8 5EFA
ABD9 5F08
ABDA 5F2D
ABDB 5F65
ABDC 5F88
ABDD 5F85
ABDE 5F8A
ABDF 5F8B
ABE0 5F87
ABE1 5F8C
ABE2 5F89
ABE3 6012
ABE4 601D
ABE5 6020
ABE6 6025
ABE7 600E
ABE8 6028
ABE9 604D
ABEA 6070
ABEB 6068
ABEC 6062
ABED 6046
ABEE 6043
ABEF 606C
ABF0 606B
ABF1 606A
ABF2 6064
ABF3 6241
ABF4 62DC
ABF5 6316
ABF6 6309
ABF7 62FC
ABF8 62ED
ABF9 6301
ABFA 62EE
ABFB 62FD
ABFC 6307
ABFD 62F1
ABFE 62F7
AC40 62EF
AC41 62EC
AC42 62FE
AC43 62F4
AC44 6311
AC45 6302
AC46 653F
AC47 6545
AC48 65AB
AC49 65BD
AC4A 65E2
AC4B 6625
AC4C 662D
AC4D 6620
AC4E 6627
AC4F 662F
AC50 661F
AC51 6628
AC52 6631
AC53 6624
AC54 66F7
AC55 67FF
AC56 67D3
AC57 67F1
AC58 67D4
AC59 67D0
AC5A 67EC
AC5B 67B6
AC5C 67AF
AC5D 67F5
AC5E 67E9
AC5F 67EF
AC60 67C4
AC61 67D1
AC62 67B4
AC63 67DA
AC64 67E5
AC65 67B8
AC66 67CF
AC67 67DE
AC68 67F3
AC69 67B0
AC6A 67D9
AC6B 67E2
AC6C 67DD
AC6D 67D2
AC6E 6B6A
AC6F 6B83
AC70 6B86
AC71 6BB5
AC72 6BD2
AC73 6BD7
AC74 6C1F
AC75 6CC9
AC76 6D0B
AC77 6D32
AC78 6D2A
AC79 6D41
AC7A 6D25
AC7B 6D0C
AC7C 6D31
AC7D 6D1E
AC7E 6D17
ACA1 6D3B
ACA2 6D3D
ACA3 6D3E
ACA4 6D36
ACA5 6D1B
ACA6 6CF5
ACA7 6D39
ACA8 6D27
ACA9 6D38
ACAA 6D29
ACAB 6D2E
ACAC 6D35
ACAD 6D0E
ACAE 6D2B
ACAF 70AB
ACB0 70BA
ACB1 70B3
ACB2 70AC
ACB3 70AF
ACB4 70AD
ACB5 70B8
ACB6 70AE
ACB7 70A4
ACB8 7230
ACB9 7272
ACBA 726F
ACBB 7274
ACBC 72E9
ACBD 72E0
ACBE 72E1
ACBF 73B7
ACC0 73CA
ACC1 73BB
ACC2 73B2
ACC3 73CD
ACC4 73C0
ACC5 73B3
ACC6 751A
ACC7 752D
ACC8 754F
ACC9 754C
ACCA 754E
ACCB 754B
ACCC 75AB
ACCD 75A4
ACCE 75A5
ACCF 75A2
ACD0 75A3
ACD1 7678
ACD2 7686
ACD3 7687
ACD4 7688
ACD5 76C8
ACD6 76C6
ACD7 76C3
ACD8 76C5
ACD9 7701
ACDA 76F9
ACDB 76F8
ACDC 7709
ACDD 770B
ACDE 76FE
ACDF 76FC
ACE0 7707
ACE1 77DC
ACE2 7802
ACE3 7814
ACE4 780C
ACE5 780D
ACE6 7946
ACE7 7949
ACE8 7948
ACE9 7947
ACEA 79B9
ACEB 79BA
ACEC 79D1
ACED 79D2
ACEE 79CB
ACEF 7A7F
ACF0 7A81
ACF1 7AFF
ACF2 7AFD
ACF3 7C7D
ACF4 7D02
ACF5 7D05
ACF6 7D00
ACF7 7D09
ACF8 7D07
ACF9 7D04
ACFA 7D06
ACFB 7F38
ACFC 7F8E
ACFD 7FBF
ACFE 8004
AD40 8010
AD41 800D
AD42 8011
AD43 8036
AD44 80D6
AD45 80E5
AD46 80DA
AD47 80C3
AD48 80C4
AD49 80CC
AD4A 80E1
AD4B 80DB
AD4C 80CE
AD4D 80DE
AD4E 80E4
AD4F 80DD
AD50 81F4
AD51 8222
AD52 82E7
AD53 8303
AD54 8305
AD55 82E3
AD56 82DB
AD57 82E6
AD58 8304
AD59 82E5
AD5A 8302
AD5B 8309
AD5C 82D2
AD5D 82D7
AD5E 82F1
AD5F 8301
AD60 82DC
AD61 82D4
AD62 82D1
AD63 82DE
AD64 82D3
AD65 82DF
AD66 82EF
AD67 8306
AD68 8650
AD69 8679
AD6A 867B
AD6B 867A
AD6C 884D
AD6D 886B
AD6E 8981
AD6F 89D4
AD70 8A08
AD71 8A02
AD72 8A03
AD73 8C9E
AD74 8CA0
AD75 8D74
AD76 8D73
AD77 8DB4
AD78 8ECD
AD79 8ECC
AD7A 8FF0
AD7B 8FE6
AD7C 8FE2
AD7D 8FEA
AD7E 8FE5
ADA1 8FED
ADA2 8FEB
ADA3 8FE4
ADA4 8FE8
ADA5 90CA
ADA6 90CE
ADA7 90C1
ADA8 90C3
ADA9 914B
ADAA 914A
ADAB 91CD
ADAC 9582
ADAD 9650
ADAE 964B
ADAF 964C
ADB0 964D
ADB1 9762
ADB2 9769
ADB3 97CB
ADB4 97ED
ADB5 97F3
ADB6 9801
ADB7 98A8
ADB8 98DB
ADB9 98DF
ADBA 9996
ADBB 9999
ADBC 4E58
ADBD 4EB3
ADBE 500C
ADBF 500D
ADC0 5023
ADC1 4FEF
ADC2 5026
ADC3 5025
ADC4 4FF8
ADC5 5029
ADC6 5016
ADC7 5006
ADC8 503C
ADC9 501F
ADCA 501A
ADCB 5012
ADCC 5011
ADCD 4FFA
ADCE 5000
ADCF 5014
ADD0 5028
ADD1 4FF1
ADD2 5021
ADD3 500B
ADD4 5019
ADD5 5018
ADD6 4FF3
ADD7 4FEE
ADD8 502D
ADD9 502A
ADDA 4FFE
ADDB 502B
ADDC 5009
ADDD 517C
ADDE 51A4
ADDF 51A5
ADE0 51A2
ADE1 51CD
ADE2 51CC
ADE3 51C6
ADE4 51CB
ADE5 5256
ADE6 525C
ADE7 5254
ADE8 525B
ADE9 525D
ADEA 532A
ADEB 537F
ADEC 539F
ADED 539D
ADEE 53DF
ADEF 54E8
ADF0 5510
ADF1 5501
ADF2 5537
ADF3 54FC
ADF4 54E5
ADF5 54F2
ADF6 5506
ADF7 54FA
ADF8 5514
ADF9 54E9
ADFA 54ED
ADFB 54E1
ADFC 5509
ADFD 54EE
ADFE 54EA
AE40 54E6
AE41 5527
AE42 5507
AE43 54FD
AE44 550F
AE45 5703
AE46 5704
AE47 57C2
AE48 57D4
AE49 57CB
AE4A 57C3
AE4B 5809
AE4C 590F
AE4D 5957
AE4E 5958
AE4F 595A
AE50 5A11
AE51 5A18
AE52 5A1C
AE53 5A1F
AE54 5A1B
AE55 5A13
AE56 59EC
AE57 5A20
AE58 5A23
AE59 5A29
AE5A 5A25
AE5B 5A0C
AE5C 5A09
AE5D 5B6B
AE5E 5C58
AE5F 5BB0
AE60 5BB3
AE61 5BB6
AE62 5BB4
AE63 5BAE
AE64 5BB5
AE65 5BB9
AE66 5BB8
AE67 5C04
AE68 5C51
AE69 5C55
AE6A 5C50
AE6B 5CED
AE6C 5CFD
AE6D 5CFB
AE6E 5CEA
AE6F 5CE8
AE70 5CF0
AE71 5CF6
AE72 5D01
AE73 5CF4
AE74 5DEE
AE75 5E2D
AE76 5E2B
AE77 5EAB
AE78 5EAD
AE79 5EA7
AE7A 5F31
AE7B 5F92
AE7C 5F91
AE7D 5F90
AE7E 6059
AEA1 6063
AEA2 6065
AEA3 6050
AEA4 6055
AEA5 606D
AEA6 6069
AEA7 606F
AEA8 6084
AEA9 609F
AEAA 609A
AEAB 608D
AEAC 6094
AEAD 608C
AEAE 6085
AEAF 6096
AEB0 6247
AEB1 62F3
AEB2 6308
AEB3 62FF
AEB4 634E
AEB5 633E
AEB6 632F
AEB7 6355
AEB8 6342
AEB9 6346
AEBA 634F
AEBB 6349
AEBC 633A
AEBD 6350
AEBE 633D
AEBF 632A
AEC0 632B
AEC1 6328
AEC2 634D
AEC3 634C
AEC4 6548
AEC5 6549
AEC6 6599
AEC7 65C1
AEC8 65C5
AEC9 6642
AECA 6649
AECB 664F
AECC 6643
AECD 6652
AECE 664C
AECF 6645
AED0 6641
AED1 66F8
AED2 6714
AED3 6715
AED4 6717
AED5 6821
AED6 6838
AED7 6848
AED8 6846
AED9 6853
AEDA 6839
AEDB 6842
AEDC 6854
AEDD 6829
AEDE 68B3
AEDF 6817
AEE0 684C
AEE1 6851
AEE2 683D
AEE3 67F4
AEE4 6850
AEE5 6840
AEE6 683C
AEE7 6843
AEE8 682A
AEE9 6845
AEEA 6813
AEEB 6818
AEEC 6841
AEED 6B8A
AEEE 6B89
AEEF 6BB7
AEF0 6C23
AEF1 6C27
AEF2 6C28
AEF3 6C26
AEF4 6C24
AEF5 6CF0
AEF6 6D6A
AEF7 6D95
AEF8 6D88
AEF9 6D87
AEFA 6D66
AEFB 6D78
AEFC 6D77
AEFD 6D59
AEFE 6D93
AF40 6D6C
AF41 6D89
AF42 6D6E
AF43 6D5A
AF44 6D74
AF45 6D69
AF46 6D8C
AF47 6D8A
AF48 6D79
AF49 6D85
AF4A 6D65
AF4B 6D94
AF4C 70CA
AF4D 70D8
AF4E 70E4
AF4F 70D9
AF50 70C8
AF51 70CF
AF52 7239
AF53 7279
AF54 72FC
AF55 72F9
AF56 72FD
AF57 72F8
AF58 72F7
AF59 7386
AF5A 73ED
AF5B 7409
AF5C 73EE
AF5D 73E0
AF5E 73EA
AF5F 73DE
AF60 7554
AF61 755D
AF62 755C
AF63 755A
AF64 7559
AF65 75BE
AF66 75C5
AF67 75C7
AF68 75B2
AF69 75B3
AF6A 75BD
AF6B 75BC
AF6C 75B9
AF6D 75C2
AF6E 75B8
AF6F 768B
AF70 76B0
AF71 76CA
AF72 76CD
AF73 76CE
AF74 7729
AF75 771F
AF76 7720
AF77 7728
AF78 77E9
AF79 7830
AF7A 7827
AF7B 7838
AF7C 781D
AF7D 7834
AF7E 7837
AFA1 7825
AFA2 782D
AFA3 7820
AFA4 781F
AFA5 7832
AFA6 7955
AFA7 7950
AFA8 7960
AFA9 795F
AFAA 7956
AFAB 795E
AFAC 795D
AFAD 7957
AFAE 795A
AFAF 79E4
AFB0 79E3
AFB1 79E7
AFB2 79DF
AFB3 79E6
AFB4 79E9
AFB5 79D8
AFB6 7A84
AFB7 7A88
AFB8 7AD9
AFB9 7B06
AFBA 7B11
AFBB 7C89
AFBC 7D21
AFBD 7D17
AFBE 7D0B
AFBF 7D0A
AFC0 7D20
AFC1 7D22
AFC2 7D14
AFC3 7D10
AFC4 7D15
AFC5 7D1A
AFC6 7D1C
AFC7 7D0D
AFC8 7D19
AFC9 7D1B
AFCA 7F3A
AFCB 7F5F
AFCC 7F94
AFCD 7FC5
AFCE 7FC1
AFCF 8006
AFD0 8018
AFD1 8015
AFD2 8019
AFD3 8017
AFD4 803D
AFD5 803F
AFD6 80F1
AFD7 8102
AFD8 80F0
AFD9 8105
AFDA 80ED
AFDB 80F4
AFDC 8106
AFDD 80F8
AFDE 80F3
AFDF 8108
AFE0 80FD
AFE1 810A
AFE2 80FC
AFE3 80EF
AFE4 81ED
AFE5 81EC
AFE6 8200
AFE7 8210
AFE8 822A
AFE9 822B
AFEA 8228
AFEB 822C
AFEC 82BB
AFED 832B
AFEE 8352
AFEF 8354
AFF0 834A
AFF1 8338
AFF2 8350
AFF3 8349
AFF4 8335
AFF5 8334
AFF6 834F
AFF7 8332
AFF8 8339
AFF9 8336
AFFA 8317
AFFB 8340
AFFC 8331
AFFD 8328
AFFE 8343
B040 8654
B041 868A
B042 86AA
B043 8693
B044 86A4
B045 86A9
B046 868C
B047 86A3
B048 869C
B049 8870
B04A 8877
B04B 8881
B04C 8882
B04D 887D
B04E 8879
B04F 8A18
B050 8A10
B051 8A0E
B052 8A0C
B053 8A15
B054 8A0A
B055 8A17
B056 8A13
B057 8A16
B058 8A0F
B059 8A11
B05A 8C48
B05B 8C7A
B05C 8C79
B05D 8CA1
B05E 8CA2
B05F 8D77
B060 8EAC
B061 8ED2
B062 8ED4
B063 8ECF
B064 8FB1
B065 9001
B066 9006
B067 8FF7
B068 9000
B069 8FFA
B06A 8FF4
B06B 9003
B06C 8FFD
B06D 9005
B06E 8FF8
B06F 9095
B070 90E1
B071 90DD
B072 90E2
B073 9152
B074 914D
B075 914C
B076 91D8
B077 91DD
B078 91D7
B079 91DC
B07A 91D9
B07B 9583
B07C 9662
B07D 9663
B07E 9661
B0A1 965B
B0A2 965D
B0A3 9664
B0A4 9658
B0A5 965E
B0A6 96BB
B0A7 98E2
B0A8 99AC
B0A9 9AA8
B0AA 9AD8
B0AB 9B25
B0AC 9B32
B0AD 9B3C
B0AE 4E7E
B0AF 507A
B0B0 507D
B0B1 505C
B0B2 5047
B0B3 5043
B0B4 504C
B0B5 505A
B0B6 5049
B0B7 5065
B0B8 5076
B0B9 504E
B0BA 5055
B0BB 5075
B0BC 5074
B0BD 5077
B0BE 504F
B0BF 500F
B0C0 506F
B0C1 506D
B0C2 515C
B0C3 5195
B0C4 51F0
B0C5 526A
B0C6 526F
B0C7 52D2
B0C8 52D9
B0C9 52D8
B0CA 52D5
B0CB 5310
B0CC 530F
B0CD 5319
B0CE 533F
B0CF 5340
B0D0 533E
B0D1 53C3
B0D2 66FC
B0D3 5546
B0D4 556A
B0D5 5566
B0D6 5544
B0D7 555E
B0D8 5561
B0D9 5543
B0DA 554A
B0DB 5531
B0DC 5556
B0DD 554F
B0DE 5555
B0DF 552F
B0E0 5564
B0E1 5538
B0E2 552E
B0E3 555C
B0E4 552C
B0E5 5563
B0E6 5533
B0E7 5541
B0E8 5557
B0E9 5708
B0EA 570B
B0EB 5709
B0EC 57DF
B0ED 5805
B0EE 580A
B0EF 5806
B0F0 57E0
B0F1 57E4
B0F2 57FA
B0F3 5802
B0F4 5835
B0F5 57F7
B0F6 57F9
B0F7 5920
B0F8 5962
B0F9 5A36
B0FA 5A41
B0FB 5A49
B0FC 5A66
B0FD 5A6A
B0FE 5A40
B140 5A3C
B141 5A62
B142 5A5A
B143 5A46
B144 5A4A
B145 5B70
B146 5BC7
B147 5BC5
B148 5BC4
B149 5BC2
B14A 5BBF
B14B 5BC6
B14C 5C09
B14D 5C08
B14E 5C07
B14F 5C60
B150 5C5C
B151 5C5D
B152 5D07
B153 5D06
B154 5D0E
B155 5D1B
B156 5D16
B157 5D22
B158 5D11
B159 5D29
B15A 5D14
B15B 5D19
B15C 5D24
B15D 5D27
B15E 5D17
B15F 5DE2
B160 5E38
B161 5E36
B162 5E33
B163 5E37
B164 5EB7
B165 5EB8
B166 5EB6
B167 5EB5
B168 5EBE
B169 5F35
B16A 5F37
B16B 5F57
B16C 5F6C
B16D 5F69
B16E 5F6B
B16F 5F97
B170 5F99
B171 5F9E
B172 5F98
B173 5FA1
B174 5FA0
B175 5F9C
B176 607F
B177 60A3
B178 6089
B179 60A0
B17A 60A8
B17B 60CB
B17C 60B4
B17D 60E6
B17E 60BD
B1A1 60C5
B1A2 60BB
B1A3 60B5
B1A4 60DC
B1A5 60BC
B1A6 60D8
B1A7 60D5
B1A8 60C6
B1A9 60DF
B1AA 60B8
B1AB 60DA
B1AC 60C7
B1AD 621A
B1AE 621B
B1AF 6248
B1B0 63A0
B1B1 63A7
B1B2 6372
B1B3 6396
B1B4 63A2
B1B5 63A5
B1B6 6377
B1B7 6367
B1B8 6398
B1B9 63AA
B1BA 6371
B1BB 63A9
B1BC 6389
B1BD 6383
B1BE 639B
B1BF 636B
B1C0 63A8
B1C1 6384
B1C2 6388
B1C3 6399
B1C4 63A1
B1C5 63AC
B1C6 6392
B1C7 638F
B1C8 6380
B1C9 637B
B1CA 6369
B1CB 6368
B1CC 637A
B1CD 655D
B1CE 6556
B1CF 6551
B1D0 6559
B1D1 6557
B1D2 555F
B1D3 654F
B1D4 6558
B1D5 6555
B1D6 6554
B1D7 659C
B1D8 659B
B1D9 65AC
B1DA 65CF
B1DB 65CB
B1DC 65CC
B1DD 65CE
B1DE 665D
B1DF 665A
B1E0 6664
B1E1 6668
B1E2 6666
B1E3 665E
B1E4 66F9
B1E5 52D7
B1E6 671B
B1E7 6881
B1E8 68AF
B1E9 68A2
B1EA 6893
B1EB 68B5
B1EC 687F
B1ED 6876
B1EE 68B1
B1EF 68A7
B1F0 6897
B1F1 68B0
B1F2 6883
B1F3 68C4
B1F4 68AD
B1F5 6886
B1F6 6885
B1F7 6894
B1F8 689D
B1F9 68A8
B1FA 689F
B1FB 68A1
B1FC 6882
B1FD 6B32
B1FE 6BBA
B240 6BEB
B241 6BEC
B242 6C2B
B243 6D8E
B244 6DBC
B245 6DF3
B246 6DD9
B247 6DB2
B248 6DE1
B249 6DCC
B24A 6DE4
B24B 6DFB
B24C 6DFA
B24D 6E05
B24E 6DC7
B24F 6DCB
B250 6DAF
B251 6DD1
B252 6DAE
B253 6DDE
B254 6DF9
B255 6DB8
B256 6DF7
B257 6DF5
B258 6DC5
B259 6DD2
B25A 6E1A
B25B 6DB5
B25C 6DDA
B25D 6DEB
B25E 6DD8
B25F 6DEA
B260 6DF1
B261 6DEE
B262 6DE8
B263 6DC6
B264 6DC4
B265 6DAA
B266 6DEC
B267 6DBF
B268 6DE6
B269 70F9
B26A 7109
B26B 710A
B26C 70FD
B26D 70EF
B26E 723D
B26F 727D
B270 7281
B271 731C
B272 731B
B273 7316
B274 7313
B275 7319
B276 7387
B277 7405
B278 740A
B279 7403
B27A 7406
B27B 73FE
B27C 740D
B27D 74E0
B27E 74F6
B2A1 74F7
B2A2 751C
B2A3 7522
B2A4 7565
B2A5 7566
B2A6 7562
B2A7 7570
B2A8 758F
B2A9 75D4
B2AA 75D5
B2AB 75B5
B2AC 75CA
B2AD 75CD
B2AE 768E
B2AF 76D4
B2B0 76D2
B2B1 76DB
B2B2 7737
B2B3 773E
B2B4 773C
B2B5 7736
B2B6 7738
B2B7 773A
B2B8 786B
B2B9 7843
B2BA 784E
B2BB 7965
B2BC 7968
B2BD 796D
B2BE 79FB
B2BF 7A92
B2C0 7A95
B2C1 7B20
B2C2 7B28
B2C3 7B1B
B2C4 7B2C
B2C5 7B26
B2C6 7B19
B2C7 7B1E
B2C8 7B2E
B2C9 7C92
B2CA 7C97
B2CB 7C95
B2CC 7D46
B2CD 7D43
B2CE 7D71
B2CF 7D2E
B2D0 7D39
B2D1 7D3C
B2D2 7D40
B2D3 7D30
B2D4 7D33
B2D5 7D44
B2D6 7D2F
B2D7 7D42
B2D8 7D32
B2D9 7D31
B2DA 7F3D
B2DB 7F9E
B2DC 7F9A
B2DD 7FCC
B2DE 7FCE
B2DF 7FD2
B2E0 801C
B2E1 804A
B2E2 8046
B2E3 812F
B2E4 8116
B2E5 8123
B2E6 812B
B2E7 8129
B2E8 8130
B2E9 8124
B2EA 8202
B2EB 8235
B2EC 8237
B2ED 8236
B2EE 8239
B2EF 838E
B2F0 839E
B2F1 8398
B2F2 8378
B2F3 83A2
B2F4 8396
B2F5 83BD
B2F6 83AB
B2F7 8392
B2F8 838A
B2F9 8393
B2FA 8389
B2FB 83A0
B2FC 8377
B2FD 837B
B2FE 837C
B340 8386
B341 83A7
B342 8655
B343 5F6A
B344 86C7
B345 86C0
B346 86B6
B347 86C4
B348 86B5
B349 86C6
B34A 86CB
B34B 86B1
B34C 86AF
B34D 86C9
B34E 8853
B34F 889E
B350 8888
B351 88AB
B352 8892
B353 8896
B354 888D
B355 888B
B356 8993
B357 898F
B358 8A2A
B359 8A1D
B35A 8A23
B35B 8A25
B35C 8A31
B35D 8A2D
B35E 8A1F
B35F 8A1B
B360 8A22
B361 8C49
B362 8C5A
B363 8CA9
B364 8CAC
B365 8CAB
B366 8CA8
B367 8CAA
B368 8CA7
B369 8D67
B36A 8D66
B36B 8DBE
B36C 8DBA
B36D 8EDB
B36E 8EDF
B36F 9019
B370 900D
B371 901A
B372 9017
B373 9023
B374 901F
B375 901D
B376 9010
B377 9015
B378 901E
B379 9020
B37A 900F
B37B 9022
B37C 9016
B37D 901B
B37E 9014
B3A1 90E8
B3A2 90ED
B3A3 90FD
B3A4 9157
B3A5 91CE
B3A6 91F5
B3A7 91E6
B3A8 91E3
B3A9 91E7
B3AA 91ED
B3AB 91E9
B3AC 9589
B3AD 966A
B3AE 9675
B3AF 9673
B3B0 9678
B3B1 9670
B3B2 9674
B3B3 9676
B3B4 9677
B3B5 966C
B3B6 96C0
B3B7 96EA
B3B8 96E9
B3B9 7AE0
B3BA 7ADF
B3BB 9802
B3BC 9803
B3BD 9B5A
B3BE 9CE5
B3BF 9E75
B3C0 9E7F
B3C1 9EA5
B3C2 9EBB
B3C3 50A2
B3C4 508D
B3C5 5085
B3C6 5099
B3C7 5091
B3C8 5080
B3C9 5096
B3CA 5098
B3CB 509A
B3CC 6700
B3CD 51F1
B3CE 5272
B3CF 5274
B3D0 5275
B3D1 5269
B3D2 52DE
B3D3 52DD
B3D4 52DB
B3D5 535A
B3D6 53A5
B3D7 557B
B3D8 5580
B3D9 55A7
B3DA 557C
B3DB 558A
B3DC 559D
B3DD 5598
B3DE 5582
B3DF 559C
B3E0 55AA
B3E1 5594
B3E2 5587
B3E3 558B
B3E4 5583
B3E5 55B3
B3E6 55AE
B3E7 559F
B3E8 553E
B3E9 55B2
B3EA 559A
B3EB 55BB
B3EC 55AC
B3ED 55B1
B3EE 557E
B3EF 5589
B3F0 55AB
B3F1 5599
B3F2 570D
B3F3 582F
B3F4 582A
B3F5 5834
B3F6 5824
B3F7 5830
B3F8 5831
B3F9 5821
B3FA 581D
B3FB 5820
B3FC 58F9
B3FD 58FA
B3FE 5960
B440 5A77
B441 5A9A
B442 5A7F
B443 5A92
B444 5A9B
B445 5AA7
B446 5B73
B447 5B71
B448 5BD2
B449 5BCC
B44A 5BD3
B44B 5BD0
B44C 5C0A
B44D 5C0B
B44E 5C31
B44F 5D4C
B450 5D50
B451 5D34
B452 5D47
B453 5DFD
B454 5E45
B455 5E3D
B456 5E40
B457 5E43
B458 5E7E
B459 5ECA
B45A 5EC1
B45B 5EC2
B45C 5EC4
B45D 5F3C
B45E 5F6D
B45F 5FA9
B460 5FAA
B461 5FA8
B462 60D1
B463 60E1
B464 60B2
B465 60B6
B466 60E0
B467 611C
B468 6123
B469 60FA
B46A 6115
B46B 60F0
B46C 60FB
B46D 60F4
B46E 6168
B46F 60F1
B470 610E
B471 60F6
B472 6109
B473 6100
B474 6112
B475 621F
B476 6249
B477 63A3
B478 638C
B479 63CF
B47A 63C0
B47B 63E9
B47C 63C9
B47D 63C6
B47E 63CD
B4A1 63D2
B4A2 63E3
B4A3 63D0
B4A4 63E1
B4A5 63D6
B4A6 63ED
B4A7 63EE
B4A8 6376
B4A9 63F4
B4AA 63EA
B4AB 63DB
B4AC 6452
B4AD 63DA
B4AE 63F9
B4AF 655E
B4B0 6566
B4B1 6562
B4B2 6563
B4B3 6591
B4B4 6590
B4B5 65AF
B4B6 666E
B4B7 6670
B4B8 6674
B4B9 6676
B4BA 666F
B4BB 6691
B4BC 667A
B4BD 667E
B4BE 6677
B4BF 66FE
B4C0 66FF
B4C1 671F
B4C2 671D
B4C3 68FA
B4C4 68D5
B4C5 68E0
B4C6 68D8
B4C7 68D7
B4C8 6905
B4C9 68DF
B4CA 68F5
B4CB 68EE
B4CC 68E7
B4CD 68F9
B4CE 68D2
B4CF 68F2
B4D0 68E3
B4D1 68CB
B4D2 68CD
B4D3 690D
B4D4 6912
B4D5 690E
B4D6 68C9
B4D7 68DA
B4D8 696E
B4D9 68FB
B4DA 6B3E
B4DB 6B3A
B4DC 6B3D
B4DD 6B98
B4DE 6B96
B4DF 6BBC
B4E0 6BEF
B4E1 6C2E
B4E2 6C2F
B4E3 6C2C
B4E4 6E2F
B4E5 6E38
B4E6 6E54
B4E7 6E21
B4E8 6E32
B4E9 6E67
B4EA 6E4A
B4EB 6E20
B4EC 6E25
B4ED 6E23
B4EE 6E1B
B4EF 6E5B
B4F0 6E58
B4F1 6E24
B4F2 6E56
B4F3 6E6E
B4F4 6E2D
B4F5 6E26
B4F6 6E6F
B4F7 6E34
B4F8 6E4D
B4F9 6E3A
B4FA 6E2C
B4FB 6E43
B4FC 6E1D
B4FD 6E3E
B4FE 6ECB
B540 6E89
B541 6E19
B542 6E4E
B543 6E63
B544 6E44
B545 6E72
B546 6E69
B547 6E5F
B548 7119
B549 711A
B54A 7126
B54B 7130
B54C 7121
B54D 7136
B54E 716E
B54F 711C
B550 724C
B551 7284
B552 7280
B553 7336
B554 7325
B555 7334
B556 7329
B557 743A
B558 742A
B559 7433
B55A 7422
B55B 7425
B55C 7435
B55D 7436
B55E 7434
B55F 742F
B560 741B
B561 7426
B562 7428
B563 7525
B564 7526
B565 756B
B566 756A
B567 75E2
B568 75DB
B569 75E3
B56A 75D9
B56B 75D8
B56C 75DE
B56D 75E0
B56E 767B
B56F 767C
B570 7696
B571 7693
B572 76B4
B573 76DC
B574 774F
B575 77ED
B576 785D
B577 786C
B578 786F
B579 7A0D
B57A 7A08
B57B 7A0B
B57C 7A05
B57D 7A00
B57E 7A98
B5A1 7A97
B5A2 7A96
B5A3 7AE5
B5A4 7AE3
B5A5 7B49
B5A6 7B56
B5A7 7B46
B5A8 7B50
B5A9 7B52
B5AA 7B54
B5AB 7B4D
B5AC 7B4B
B5AD 7B4F
B5AE 7B51
B5AF 7C9F
B5B0 7CA5
B5B1 7D5E
B5B2 7D50
B5B3 7D68
B5B4 7D55
B5B5 7D2B
B5B6 7D6E
B5B7 7D72
B5B8 7D61
B5B9 7D66
B5BA 7D62
B5BB 7D70
B5BC 7D73
B5BD 5584
B5BE 7FD4
B5BF 7FD5
B5C0 800B
B5C1 8052
B5C2 8085
B5C3 8155
B5C4 8154
B5C5 814B
B5C6 8151
B5C7 814E
B5C8 8139
B5C9 8146
B5CA 813E
B5CB 814C
B5CC 8153
B5CD 8174
B5CE 8212
B5CF 821C
B5D0 83E9
B5D1 8403
B5D2 83F8
B5D3 840D
B5D4 83E0
B5D5 83C5
B5D6 840B
B5D7 83C1
B5D8 83EF
B5D9 83F1
B5DA 83F4
B5DB 8457
B5DC 840A
B5DD 83F0
B5DE 840C
B5DF 83CC
B5E0 83FD
B5E1 83F2
B5E2 83CA
B5E3 8438
B5E4 840E
B5E5 8404
B5E6 83DC
B5E7 8407
B5E8 83D4
B5E9 83DF
B5EA 865B
B5EB 86DF
B5EC 86D9
B5ED 86ED
B5EE 86D4
B5EF 86DB
B5F0 86E4
B5F1 86D0
B5F2 86DE
B5F3 8857
B5F4 88C1
B5F5 88C2
B5F6 88B1
B5F7 8983
B5F8 8996
B5F9 8A3B
B5FA 8A60
B5FB 8A55
B5FC 8A5E
B5FD 8A3C
B5FE 8A41
B640 8A54
B641 8A5B
B642 8A50
B643 8A46
B644 8A34
B645 8A3A
B646 8A36
B647 8A56
B648 8C61
B649 8C82
B64A 8CAF
B64B 8CBC
B64C 8CB3
B64D 8CBD
B64E 8CC1
B64F 8CBB
B650 8CC0
B651 8CB4
B652 8CB7
B653 8CB6
B654 8CBF
B655 8CB8
B656 8D8A
B657 8D85
B658 8D81
B659 8DCE
B65A 8DDD
B65B 8DCB
B65C 8DDA
B65D 8DD1
B65E 8DCC
B65F 8DDB
B660 8DC6
B661 8EFB
B662 8EF8
B663 8EFC
B664 8F9C
B665 902E
B666 9035
B667 9031
B668 9038
B669 9032
B66A 9036
B66B 9102
B66C 90F5
B66D 9109
B66E 90FE
B66F 9163
B670 9165
B671 91CF
B672 9214
B673 9215
B674 9223
B675 9209
B676 921E
B677 920D
B678 9210
B679 9207
B67A 9211
B67B 9594
B67C 958F
B67D 958B
B67E 9591
B6A1 9593
B6A2 9592
B6A3 958E
B6A4 968A
B6A5 968E
B6A6 968B
B6A7 967D
B6A8 9685
B6A9 9686
B6AA 968D
B6AB 9672
B6AC 9684
B6AD 96C1
B6AE 96C5
B6AF 96C4
B6B0 96C6
B6B1 96C7
B6B2 96EF
B6B3 96F2
B6B4 97CC
B6B5 9805
B6B6 9806
B6B7 9808
B6B8 98E7
B6B9 98EA
B6BA 98EF
B6BB 98E9
B6BC 98F2
B6BD 98ED
B6BE 99AE
B6BF 99AD
B6C0 9EC3
B6C1 9ECD
B6C2 9ED1
B6C3 4E82
B6C4 50AD
B6C5 50B5
B6C6 50B2
B6C7 50B3
B6C8 50C5
B6C9 50BE
B6CA 50AC
B6CB 50B7
B6CC 50BB
B6CD 50AF
B6CE 50C7
B6CF 527F
B6D0 5277
B6D1 527D
B6D2 52DF
B6D3 52E6
B6D4 52E4
B6D5 52E2
B6D6 52E3
B6D7 532F
B6D8 55DF
B6D9 55E8
B6DA 55D3
B6DB 55E6
B6DC 55CE
B6DD 55DC
B6DE 55C7
B6DF 55D1
B6E0 55E3
B6E1 55E4
B6E2 55EF
B6E3 55DA
B6E4 55E1
B6E5 55C5
B6E6 55C6
B6E7 55E5
B6E8 55C9
B6E9 5712
B6EA 5713
B6EB 585E
B6EC 5851
B6ED 5858
B6EE 5857
B6EF 585A
B6F0 5854
B6F1 586B
B6F2 584C
B6F3 586D
B6F4 584A
B6F5 5862
B6F6 5852
B6F7 584B
B6F8 5967
B6F9 5AC1
B6FA 5AC9
B6FB 5ACC
B6FC 5ABE
B6FD 5ABD
B6FE 5ABC
B740 5AB3
B741 5AC2
B742 5AB2
B743 5D69
B744 5D6F
B745 5E4C
B746 5E79
B747 5EC9
B748 5EC8
B749 5F12
B74A 5F59
B74B 5FAC
B74C 5FAE
B74D 611A
B74E 610F
B74F 6148
B750 611F
B751 60F3
B752 611B
B753 60F9
B754 6101
B755 6108
B756 614E
B757 614C
B758 6144
B759 614D
B75A 613E
B75B 6134
B75C 6127
B75D 610D
B75E 6106
B75F 6137
B760 6221
B761 6222
B762 6413
B763 643E
B764 641E
B765 642A
B766 642D
B767 643D
B768 642C
B769 640F
B76A 641C
B76B 6414
B76C 640D
B76D 6436
B76E 6416
B76F 6417
B770 6406
B771 656C
B772 659F
B773 65B0
B774 6697
B775 6689
B776 6687
B777 6688
B778 6696
B779 6684
B77A 6698
B77B 668D
B77C 6703
B77D 6994
B77E 696D
B7A1 695A
B7A2 6977
B7A3 6960
B7A4 6954
B7A5 6975
B7A6 6930
B7A7 6982
B7A8 694A
B7A9 6968
B7AA 696B
B7AB 695E
B7AC 6953
B7AD 6979
B7AE 6986
B7AF 695D
B7B0 6963
B7B1 695B
B7B2 6B47
B7B3 6B72
B7B4 6BC0
B7B5 6BBF
B7B6 6BD3
B7B7 6BFD
B7B8 6EA2
B7B9 6EAF
B7BA 6ED3
B7BB 6EB6
B7BC 6EC2
B7BD 6E90
B7BE 6E9D
B7BF 6EC7
B7C0 6EC5
B7C1 6EA5
B7C2 6E98
B7C3 6EBC
B7C4 6EBA
B7C5 6EAB
B7C6 6ED1
B7C7 6E96
B7C8 6E9C
B7C9 6EC4
B7CA 6ED4
B7CB 6EAA
B7CC 6EA7
B7CD 6EB4
B7CE 714E
B7CF 7159
B7D0 7169
B7D1 7164
B7D2 7149
B7D3 7167
B7D4 715C
B7D5 716C
B7D6 7166
B7D7 714C
B7D8 7165
B7D9 715E
B7DA 7146
B7DB 7168
B7DC 7156
B7DD 723A
B7DE 7252
B7DF 7337
B7E0 7345
B7E1 733F
B7E2 733E
B7E3 746F
B7E4 745A
B7E5 7455
B7E6 745F
B7E7 745E
B7E8 7441
B7E9 743F
B7EA 7459
B7EB 745B
B7EC 745C
B7ED 7576
B7EE 7578
B7EF 7600
B7F0 75F0
B7F1 7601
B7F2 75F2
B7F3 75F1
B7F4 75FA
B7F5 75FF
B7F6 75F4
B7F7 75F3
B7F8 76DE
B7F9 76DF
B7FA 775B
B7FB 776B
B7FC 7766
B7FD 775E
B7FE 7763
B840 7779
B841 776A
B842 776C
B843 775C
B844 7765
B845 7768
B846 7762
B847 77EE
B848 788E
B849 78B0
B84A 7897
B84B 7898
B84C 788C
B84D 7889
B84E 787C
B84F 7891
B850 7893
B851 787F
B852 797A
B853 797F
B854 7981
B855 842C
B856 79BD
B857 7A1C
B858 7A1A
B859 7A20
B85A 7A14
B85B 7A1F
B85C 7A1E
B85D 7A9F
B85E 7AA0
B85F 7B77
B860 7BC0
B861 7B60
B862 7B6E
B863 7B67
B864 7CB1
B865 7CB3
B866 7CB5
B867 7D93
B868 7D79
B869 7D91
B86A 7D81
B86B 7D8F
B86C 7D5B
B86D 7F6E
B86E 7F69
B86F 7F6A
B870 7F72
B871 7FA9
B872 7FA8
B873 7FA4
B874 8056
B875 8058
B876 8086
B877 8084
B878 8171
B879 8170
B87A 8178
B87B 8165
B87C 816E
B87D 8173
B87E 816B
B8A1 8179
B8A2 817A
B8A3 8166
B8A4 8205
B8A5 8247
B8A6 8482
B8A7 8477
B8A8 843D
B8A9 8431
B8AA 8475
B8AB 8466
B8AC 846B
B8AD 8449
B8AE 846C
B8AF 845B
B8B0 843C
B8B1 8435
B8B2 8461
B8B3 8463
B8B4 8469
B8B5 846D
B8B6 8446
B8B7 865E
B8B8 865C
B8B9 865F
B8BA 86F9
B8BB 8713
B8BC 8708
B8BD 8707
B8BE 8700
B8BF 86FE
B8C0 86FB
B8C1 8702
B8C2 8703
B8C3 8706
B8C4 870A
B8C5 8859
B8C6 88DF
B8C7 88D4
B8C8 88D9
B8C9 88DC
B8CA 88D8
B8CB 88DD
B8CC 88E1
B8CD 88CA
B8CE 88D5
B8CF 88D2
B8D0 899C
B8D1 89E3
B8D2 8A6B
B8D3 8A72
B8D4 8A73
B8D5 8A66
B8D6 8A69
B8D7 8A70
B8D8 8A87
B8D9 8A7C
B8DA 8A63
B8DB 8AA0
B8DC 8A71
B8DD 8A85
B8DE 8A6D
B8DF 8A62
B8E0 8A6E
B8E1 8A6C
B8E2 8A79
B8E3 8A7B
B8E4 8A3E
B8E5 8A68
B8E6 8C62
B8E7 8C8A
B8E8 8C89
B8E9 8CCA
B8EA 8CC7
B8EB 8CC8
B8EC 8CC4
B8ED 8CB2
B8EE 8CC3
B8EF 8CC2
B8F0 8CC5
B8F1 8DE1
B8F2 8DDF
B8F3 8DE8
B8F4 8DEF
B8F5 8DF3
B8F6 8DFA
B8F7 8DEA
B8F8 8DE4
B8F9 8DE6
B8FA 8EB2
B8FB 8F03
B8FC 8F09
B8FD 8EFE
B8FE 8F0A
B940 8F9F
B941 8FB2
B942 904B
B943 904A
B944 9053
B945 9042
B946 9054
B947 903C
B948 9055
B949 9050
B94A 9047
B94B 904F
B94C 904E
B94D 904D
B94E 9051
B94F 903E
B950 9041
B951 9112
B952 9117
B953 916C
B954 916A
B955 9169
B956 91C9
B957 9237
B958 9257
B959 9238
B95A 923D
B95B 9240
B95C 923E
B95D 925B
B95E 924B
B95F 9264
B960 9251
B961 9234
B962 9249
B963 924D
B964 9245
B965 9239
B966 923F
B967 925A
B968 9598
B969 9698
B96A 9694
B96B 9695
B96C 96CD
B96D 96CB
B96E 96C9
B96F 96CA
B970 96F7
B971 96FB
B972 96F9
B973 96F6
B974 9756
B975 9774
B976 9776
B977 9810
B978 9811
B979 9813
B97A 980A
B97B 9812
B97C 980C
B97D 98FC
B97E 98F4
B9A1 98FD
B9A2 98FE
B9A3 99B3
B9A4 99B1
B9A5 99B4
B9A6 9AE1
B9A7 9CE9
B9A8 9E82
B9A9 9F0E
B9AA 9F13
B9AB 9F20
B9AC 50E7
B9AD 50EE
B9AE 50E5
B9AF 50D6
B9B0 50ED
B9B1 50DA
B9B2 50D5
B9B3 50CF
B9B4 50D1
B9B5 50F1
B9B6 50CE
B9B7 50E9
B9B8 5162
B9B9 51F3
B9BA 5283
B9BB 5282
B9BC 5331
B9BD 53AD
B9BE 55FE
B9BF 5600
B9C0 561B
B9C1 5617
B9C2 55FD
B9C3 5614
B9C4 5606
B9C5 5609
B9C6 560D
B9C7 560E
B9C8 55F7
B9C9 5616
B9CA 561F
B9CB 5608
B9CC 5610
B9CD 55F6
B9CE 5718
B9CF 5716
B9D0 5875
B9D1 587E
B9D2 5883
B9D3 5893
B9D4 588A
B9D5 5879
B9D6 5885
B9D7 587D
B9D8 58FD
B9D9 5925
B9DA 5922
B9DB 5924
B9DC 596A
B9DD 5969
B9DE 5AE1
B9DF 5AE6
B9E0 5AE9
B9E1 5AD7
B9E2 5AD6
B9E3 5AD8
B9E4 5AE3
B9E5 5B75
B9E6 5BDE
B9E7 5BE7
B9E8 5BE1
B9E9 5BE5
B9EA 5BE6
B9EB 5BE8
B9EC 5BE2
B9ED 5BE4
B9EE 5BDF
B9EF 5C0D
B9F0 5C62
B9F1 5D84
B9F2 5D87
B9F3 5E5B
B9F4 5E63
B9F5 5E55
B9F6 5E57
B9F7 5E54
B9F8 5ED3
B9F9 5ED6
B9FA 5F0A
B9FB 5F46
B9FC 5F70
B9FD 5FB9
B9FE 6147
BA40 613F
BA41 614B
BA42 6177
BA43 6162
BA44 6163
BA45 615F
BA46 615A
BA47 6158
BA48 6175
BA49 622A
BA4A 6487
BA4B 6458
BA4C 6454
BA4D 64A4
BA4E 6478
BA4F 645F
BA50 647A
BA51 6451
BA52 6467
BA53 6434
BA54 646D
BA55 647B
BA56 6572
BA57 65A1
BA58 65D7
BA59 65D6
BA5A 66A2
BA5B 66A8
BA5C 669D
BA5D 699C
BA5E 69A8
BA5F 6995
BA60 69C1
BA61 69AE
BA62 69D3
BA63 69CB
BA64 699B
BA65 69B7
BA66 69BB
BA67 69AB
BA68 69B4
BA69 69D0
BA6A 69CD
BA6B 69AD
BA6C 69CC
BA6D 69A6
BA6E 69C3
BA6F 69A3
BA70 6B49
BA71 6B4C
BA72 6C33
BA73 6F33
BA74 6F14
BA75 6EFE
BA76 6F13
BA77 6EF4
BA78 6F29
BA79 6F3E
BA7A 6F20
BA7B 6F2C
BA7C 6F0F
BA7D 6F02
BA7E 6F22
BAA1 6EFF
BAA2 6EEF
BAA3 6F06
BAA4 6F31
BAA5 6F38
BAA6 6F32
BAA7 6F23
BAA8 6F15
BAA9 6F2B
BAAA 6F2F
BAAB 6F88
BAAC 6F2A
BAAD 6EEC
BAAE 6F01
BAAF 6EF2
BAB0 6ECC
BAB1 6EF7
BAB2 7194
BAB3 7199
BAB4 717D
BAB5 718A
BAB6 7184
BAB7 7192
BAB8 723E
BAB9 7292
BABA 7296
BABB 7344
BABC 7350
BABD 7464
BABE 7463
BABF 746A
BAC0 7470
BAC1 746D
BAC2 7504
BAC3 7591
BAC4 7627
BAC5 760D
BAC6 760B
BAC7 7609
BAC8 7613
BAC9 76E1
BACA 76E3
BACB 7784
BACC 777D
BACD 777F
BACE 7761
BACF 78C1
BAD0 789F
BAD1 78A7
BAD2 78B3
BAD3 78A9
BAD4 78A3
BAD5 798E
BAD6 798F
BAD7 798D
BAD8 7A2E
BAD9 7A31
BADA 7AAA
BADB 7AA9
BADC 7AED
BADD 7AEF
BADE 7BA1
BADF 7B95
BAE0 7B8B
BAE1 7B75
BAE2 7B97
BAE3 7B9D
BAE4 7B94
BAE5 7B8F
BAE6 7BB8
BAE7 7B87
BAE8 7B84
BAE9 7CB9
BAEA 7CBD
BAEB 7CBE
BAEC 7DBB
BAED 7DB0
BAEE 7D9C
BAEF 7DBD
BAF0 7DBE
BAF1 7DA0
BAF2 7DCA
BAF3 7DB4
BAF4 7DB2
BAF5 7DB1
BAF6 7DBA
BAF7 7DA2
BAF8 7DBF
BAF9 7DB5
BAFA 7DB8
BAFB 7DAD
BAFC 7DD2
BAFD 7DC7
BAFE 7DAC
BB40 7F70
BB41 7FE0
BB42 7FE1
BB43 7FDF
BB44 805E
BB45 805A
BB46 8087
BB47 8150
BB48 8180
BB49 818F
BB4A 8188
BB4B 818A
BB4C 817F
BB4D 8182
BB4E 81E7
BB4F 81FA
BB50 8207
BB51 8214
BB52 821E
BB53 824B
BB54 84C9
BB55 84BF
BB56 84C6
BB57 84C4
BB58 8499
BB59 849E
BB5A 84B2
BB5B 849C
BB5C 84CB
BB5D 84B8
BB5E 84C0
BB5F 84D3
BB60 8490
BB61 84BC
BB62 84D1
BB63 84CA
BB64 873F
BB65 871C
BB66 873B
BB67 8722
BB68 8725
BB69 8734
BB6A 8718
BB6B 8755
BB6C 8737
BB6D 8729
BB6E 88F3
BB6F 8902
BB70 88F4
BB71 88F9
BB72 88F8
BB73 88FD
BB74 88E8
BB75 891A
BB76 88EF
BB77 8AA6
BB78 8A8C
BB79 8A9E
BB7A 8AA3
BB7B 8A8D
BB7C 8AA1
BB7D 8A93
BB7E 8AA4
BBA1 8AAA
BBA2 8AA5
BBA3 8AA8
BBA4 8A98
BBA5 8A91
BBA6 8A9A
BBA7 8AA7
BBA8 8C6A
BBA9 8C8D
BBAA 8C8C
BBAB 8CD3
BBAC 8CD1
BBAD 8CD2
BBAE 8D6B
BBAF 8D99
BBB0 8D95
BBB1 8DFC
BBB2 8F14
BBB3 8F12
BBB4 8F15
BBB5 8F13
BBB6 8FA3
BBB7 9060
BBB8 9058
BBB9 905C
BBBA 9063
BBBB 9059
BBBC 905E
BBBD 9062
BBBE 905D
BBBF 905B
BBC0 9119
BBC1 9118
BBC2 911E
BBC3 9175
BBC4 9178
BBC5 9177
BBC6 9174
BBC7 9278
BBC8 9280
BBC9 9285
BBCA 9298
BBCB 9296
BBCC 927B
BBCD 9293
BBCE 929C
BBCF 92A8
BBD0 927C
BBD1 9291
BBD2 95A1
BBD3 95A8
BBD4 95A9
BBD5 95A3
BBD6 95A5
BBD7 95A4
BBD8 9699
BBD9 969C
BBDA 969B
BBDB 96CC
BBDC 96D2
BBDD 9700
BBDE 977C
BBDF 9785
BBE0 97F6
BBE1 9817
BBE2 9818
BBE3 98AF
BBE4 98B1
BBE5 9903
BBE6 9905
BBE7 990C
BBE8 9909
BBE9 99C1
BBEA 9AAF
BBEB 9AB0
BBEC 9AE6
BBED 9B41
BBEE 9B42
BBEF 9CF4
BBF0 9CF6
BBF1 9CF3
BBF2 9EBC
BBF3 9F3B
BBF4 9F4A
BBF5 5104
BBF6 5100
BBF7 50FB
BBF8 50F5
BBF9 50F9
BBFA 5102
BBFB 5108
BBFC 5109
BBFD 5105
BBFE 51DC
BC40 5287
BC41 5288
BC42 5289
BC43 528D
BC44 528A
BC45 52F0
BC46 53B2
BC47 562E
BC48 563B
BC49 5639
BC4A 5632
BC4B 563F
BC4C 5634
BC4D 5629
BC4E 5653
BC4F 564E
BC50 5657
BC51 5674
BC52 5636
BC53 562F
BC54 5630
BC55 5880
BC56 589F
BC57 589E
BC58 58B3
BC59 589C
BC5A 58AE
BC5B 58A9
BC5C 58A6
BC5D 596D
BC5E 5B09
BC5F 5AFB
BC60 5B0B
BC61 5AF5
BC62 5B0C
BC63 5B08
BC64 5BEE
BC65 5BEC
BC66 5BE9
BC67 5BEB
BC68 5C64
BC69 5C65
BC6A 5D9D
BC6B 5D94
BC6C 5E62
BC6D 5E5F
BC6E 5E61
BC6F 5EE2
BC70 5EDA
BC71 5EDF
BC72 5EDD
BC73 5EE3
BC74 5EE0
BC75 5F48
BC76 5F71
BC77 5FB7
BC78 5FB5
BC79 6176
BC7A 6167
BC7B 616E
BC7C 615D
BC7D 6155
BC7E 6182
BCA1 617C
BCA2 6170
BCA3 616B
BCA4 617E
BCA5 61A7
BCA6 6190
BCA7 61AB
BCA8 618E
BCA9 61AC
BCAA 619A
BCAB 61A4
BCAC 6194
BCAD 61AE
BCAE 622E
BCAF 6469
BCB0 646F
BCB1 6479
BCB2 649E
BCB3 64B2
BCB4 6488
BCB5 6490
BCB6 64B0
BCB7 64A5
BCB8 6493
BCB9 6495
BCBA 64A9
BCBB 6492
BCBC 64AE
BCBD 64AD
BCBE 64AB
BCBF 649A
BCC0 64AC
BCC1 6499
BCC2 64A2
BCC3 64B3
BCC4 6575
BCC5 6577
BCC6 6578
BCC7 66AE
BCC8 66AB
BCC9 66B4
BCCA 66B1
BCCB 6A23
BCCC 6A1F
BCCD 69E8
BCCE 6A01
BCCF 6A1E
BCD0 6A19
BCD1 69FD
BCD2 6A21
BCD3 6A13
BCD4 6A0A
BCD5 69F3
BCD6 6A02
BCD7 6A05
BCD8 69ED
BCD9 6A11
BCDA 6B50
BCDB 6B4E
BCDC 6BA4
BCDD 6BC5
BCDE 6BC6
BCDF 6F3F
BCE0 6F7C
BCE1 6F84
BCE2 6F51
BCE3 6F66
BCE4 6F54
BCE5 6F86
BCE6 6F6D
BCE7 6F5B
BCE8 6F78
BCE9 6F6E
BCEA 6F8E
BCEB 6F7A
BCEC 6F70
BCED 6F64
BCEE 6F97
BCEF 6F58
BCF0 6ED5
BCF1 6F6F
BCF2 6F60
BCF3 6F5F
BCF4 719F
BCF5 71AC
BCF6 71B1
BCF7 71A8
BCF8 7256
BCF9 729B
BCFA 734E
BCFB 7357
BCFC 7469
BCFD 748B
BCFE 7483
BD40 747E
BD41 7480
BD42 757F
BD43 7620
BD44 7629
BD45 761F
BD46 7624
BD47 7626
BD48 7621
BD49 7622
BD4A 769A
BD4B 76BA
BD4C 76E4
BD4D 778E
BD4E 7787
BD4F 778C
BD50 7791
BD51 778B
BD52 78CB
BD53 78C5
BD54 78BA
BD55 78CA
BD56 78BE
BD57 78D5
BD58 78BC
BD59 78D0
BD5A 7A3F
BD5B 7A3C
BD5C 7A40
BD5D 7A3D
BD5E 7A37
BD5F 7A3B
BD60 7AAF
BD61 7AAE
BD62 7BAD
BD63 7BB1
BD64 7BC4
BD65 7BB4
BD66 7BC6
BD67 7BC7
BD68 7BC1
BD69 7BA0
BD6A 7BCC
BD6B 7CCA
BD6C 7DE0
BD6D 7DF4
BD6E 7DEF
BD6F 7DFB
BD70 7DD8
BD71 7DEC
BD72 7DDD
BD73 7DE8
BD74 7DE3
BD75 7DDA
BD76 7DDE
BD77 7DE9
BD78 7D9E
BD79 7DD9
BD7A 7DF2
BD7B 7DF9
BD7C 7F75
BD7D 7F77
BD7E 7FAF
BDA1 7FE9
BDA2 8026
BDA3 819B
BDA4 819C
BDA5 819D
BDA6 81A0
BDA7 819A
BDA8 8198
BDA9 8517
BDAA 853D
BDAB 851A
BDAC 84EE
BDAD 852C
BDAE 852D
BDAF 8513
BDB0 8511
BDB1 8523
BDB2 8521
BDB3 8514
BDB4 84EC
BDB5 8525
BDB6 84FF
BDB7 8506
BDB8 8782
BDB9 8774
BDBA 8776
BDBB 8760
BDBC 8766
BDBD 8778
BDBE 8768
BDBF 8759
BDC0 8757
BDC1 874C
BDC2 8753
BDC3 885B
BDC4 885D
BDC5 8910
BDC6 8907
BDC7 8912
BDC8 8913
BDC9 8915
BDCA 890A
BDCB 8ABC
BDCC 8AD2
BDCD 8AC7
BDCE 8AC4
BDCF 8A95
BDD0 8ACB
BDD1 8AF8
BDD2 8AB2
BDD3 8AC9
BDD4 8AC2
BDD5 8ABF
BDD6 8AB0
BDD7 8AD6
BDD8 8ACD
BDD9 8AB6
BDDA 8AB9
BDDB 8ADB
BDDC 8C4C
BDDD 8C4E
BDDE 8C6C
BDDF 8CE0
BDE0 8CDE
BDE1 8CE6
BDE2 8CE4
BDE3 8CEC
BDE4 8CED
BDE5 8CE2
BDE6 8CE3
BDE7 8CDC
BDE8 8CEA
BDE9 8CE1
BDEA 8D6D
BDEB 8D9F
BDEC 8DA3
BDED 8E2B
BDEE 8E10
BDEF 8E1D
BDF0 8E22
BDF1 8E0F
BDF2 8E29
BDF3 8E1F
BDF4 8E21
BDF5 8E1E
BDF6 8EBA
BDF7 8F1D
BDF8 8F1B
BDF9 8F1F
BDFA 8F29
BDFB 8F26
BDFC 8F2A
BDFD 8F1C
BDFE 8F1E
BE40 8F25
BE41 9069
BE42 906E
BE43 9068
BE44 906D
BE45 9077
BE46 9130
BE47 912D
BE48 9127
BE49 9131
BE4A 9187
BE4B 9189
BE4C 918B
BE4D 9183
BE4E 92C5
BE4F 92BB
BE50 92B7
BE51 92EA
BE52 92AC
BE53 92E4
BE54 92C1
BE55 92B3
BE56 92BC
BE57 92D2
BE58 92C7
BE59 92F0
BE5A 92B2
BE5B 95AD
BE5C 95B1
BE5D 9704
BE5E 9706
BE5F 9707
BE60 9709
BE61 9760
BE62 978D
BE63 978B
BE64 978F
BE65 9821
BE66 982B
BE67 981C
BE68 98B3
BE69 990A
BE6A 9913
BE6B 9912
BE6C 9918
BE6D 99DD
BE6E 99D0
BE6F 99DF
BE70 99DB
BE71 99D1
BE72 99D5
BE73 99D2
BE74 99D9
BE75 9AB7
BE76 9AEE
BE77 9AEF
BE78 9B27
BE79 9B45
BE7A 9B44
BE7B 9B77
BE7C 9B6F
BE7D 9D06
BE7E 9D09
BEA1 9D03
BEA2 9EA9
BEA3 9EBE
BEA4 9ECE
BEA5 58A8
BEA6 9F52
BEA7 5112
BEA8 5118
BEA9 5114
BEAA 5110
BEAB 5115
BEAC 5180
BEAD 51AA
BEAE 51DD
BEAF 5291
BEB0 5293
BEB1 52F3
BEB2 5659
BEB3 566B
BEB4 5679
BEB5 5669
BEB6 5664
BEB7 5678
BEB8 566A
BEB9 5668
BEBA 5665
BEBB 5671
BEBC 566F
BEBD 566C
BEBE 5662
BEBF 5676
BEC0 58C1
BEC1 58BE
BEC2 58C7
BEC3 58C5
BEC4 596E
BEC5 5B1D
BEC6 5B34
BEC7 5B78
BEC8 5BF0
BEC9 5C0E
BECA 5F4A
BECB 61B2
BECC 6191
BECD 61A9
BECE 618A
BECF 61CD
BED0 61B6
BED1 61BE
BED2 61CA
BED3 61C8
BED4 6230
BED5 64C5
BED6 64C1
BED7 64CB
BED8 64BB
BED9 64BC
BEDA 64DA
BEDB 64C4
BEDC 64C7
BEDD 64C2
BEDE 64CD
BEDF 64BF
BEE0 64D2
BEE1 64D4
BEE2 64BE
BEE3 6574
BEE4 66C6
BEE5 66C9
BEE6 66B9
BEE7 66C4
BEE8 66C7
BEE9 66B8
BEEA 6A3D
BEEB 6A38
BEEC 6A3A
BEED 6A59
BEEE 6A6B
BEEF 6A58
BEF0 6A39
BEF1 6A44
BEF2 6A62
BEF3 6A61
BEF4 6A4B
BEF5 6A47
BEF6 6A35
BEF7 6A5F
BEF8 6A48
BEF9 6B59
BEFA 6B77
BEFB 6C05
BEFC 6FC2
BEFD 6FB1
BEFE 6FA1
BF40 6FC3
BF41 6FA4
BF42 6FC1
BF43 6FA7
BF44 6FB3
BF45 6FC0
BF46 6FB9
BF47 6FB6
BF48 6FA6
BF49 6FA0
BF4A 6FB4
BF4B 71BE
BF4C 71C9
BF4D 71D0
BF4E 71D2
BF4F 71C8
BF50 71D5
BF51 71B9
BF52 71CE
BF53 71D9
BF54 71DC
BF55 71C3
BF56 71C4
BF57 7368
BF58 749C
BF59 74A3
BF5A 7498
BF5B 749F
BF5C 749E
BF5D 74E2
BF5E 750C
BF5F 750D
BF60 7634
BF61 7638
BF62 763A
BF63 76E7
BF64 76E5
BF65 77A0
BF66 779E
BF67 779F
BF68 77A5
BF69 78E8
BF6A 78DA
BF6B 78EC
BF6C 78E7
BF6D 79A6
BF6E 7A4D
BF6F 7A4E
BF70 7A46
BF71 7A4C
BF72 7A4B
BF73 7ABA
BF74 7BD9
BF75 7C11
BF76 7BC9
BF77 7BE4
BF78 7BDB
BF79 7BE1
BF7A 7BE9
BF7B 7BE6
BF7C 7CD5
BF7D 7CD6
BF7E 7E0A
BFA1 7E11
BFA2 7E08
BFA3 7E1B
BFA4 7E23
BFA5 7E1E
BFA6 7E1D
BFA7 7E09
BFA8 7E10
BFA9 7F79
BFAA 7FB2
BFAB 7FF0
BFAC 7FF1
BFAD 7FEE
BFAE 8028
BFAF 81B3
BFB0 81A9
BFB1 81A8
BFB2 81FB
BFB3 8208
BFB4 8258
BFB5 8259
BFB6 854A
BFB7 8559
BFB8 8548
BFB9 8568
BFBA 8569
BFBB 8543
BFBC 8549
BFBD 856D
BFBE 856A
BFBF 855E
BFC0 8783
BFC1 879F
BFC2 879E
BFC3 87A2
BFC4 878D
BFC5 8861
BFC6 892A
BFC7 8932
BFC8 8925
BFC9 892B
BFCA 8921
BFCB 89AA
BFCC 89A6
BFCD 8AE6
BFCE 8AFA
BFCF 8AEB
BFD0 8AF1
BFD1 8B00
BFD2 8ADC
BFD3 8AE7
BFD4 8AEE
BFD5 8AFE
BFD6 8B01
BFD7 8B02
BFD8 8AF7
BFD9 8AED
BFDA 8AF3
BFDB 8AF6
BFDC 8AFC
BFDD 8C6B
BFDE 8C6D
BFDF 8C93
BFE0 8CF4
BFE1 8E44
BFE2 8E31
BFE3 8E34
BFE4 8E42
BFE5 8E39
BFE6 8E35
BFE7 8F3B
BFE8 8F2F
BFE9 8F38
BFEA 8F33
BFEB 8FA8
BFEC 8FA6
BFED 9075
BFEE 9074
BFEF 9078
BFF0 9072
BFF1 907C
BFF2 907A
BFF3 9134
BFF4 9192
BFF5 9320
BFF6 9336
BFF7 92F8
BFF8 9333
BFF9 932F
BFFA 9322
BFFB 92FC
BFFC 932B
BFFD 9304
BFFE 931A
C040 9310
C041 9326
C042 9321
C043 9315
C044 932E
C045 9319
C046 95BB
C047 96A7
C048 96A8
C049 96AA
C04A 96D5
C04B 970E
C04C 9711
C04D 9716
C04E 970D
C04F 9713
C050 970F
C051 975B
C052 975C
C053 9766
C054 9798
C055 9830
C056 9838
C057 983B
C058 9837
C059 982D
C05A 9839
C05B 9824
C05C 9910
C05D 9928
C05E 991E
C05F 991B
C060 9921
C061 991A
C062 99ED
C063 99E2
C064 99F1
C065 9AB8
C066 9ABC
C067 9AFB
C068 9AED
C069 9B28
C06A 9B91
C06B 9D15
C06C 9D23
C06D 9D26
C06E 9D28
C06F 9D12
C070 9D1B
C071 9ED8
C072 9ED4
C073 9F8D
C074 9F9C
C075 512A
C076 511F
C077 5121
C078 5132
C079 52F5
C07A 568E
C07B 5680
C07C 5690
C07D 5685
C07E 5687
C0A1 568F
C0A2 58D5
C0A3 58D3
C0A4 58D1
C0A5 58CE
C0A6 5B30
C0A7 5B2A
C0A8 5B24
C0A9 5B7A
C0AA 5C37
C0AB 5C68
C0AC 5DBC
C0AD 5DBA
C0AE 5DBD
C0AF 5DB8
C0B0 5E6B
C0B1 5F4C
C0B2 5FBD
C0B3 61C9
C0B4 61C2
C0B5 61C7
C0B6 61E6
C0B7 61CB
C0B8 6232
C0B9 6234
C0BA 64CE
C0BB 64CA
C0BC 64D8
C0BD 64E0
C0BE 64F0
C0BF 64E6
C0C0 64EC
C0C1 64F1
C0C2 64E2
C0C3 64ED
C0C4 6582
C0C5 6583
C0C6 66D9
C0C7 66D6
C0C8 6A80
C0C9 6A94
C0CA 6A84
C0CB 6AA2
C0CC 6A9C
C0CD 6ADB
C0CE 6AA3
C0CF 6A7E
C0D0 6A97
C0D1 6A90
C0D2 6AA0
C0D3 6B5C
C0D4 6BAE
C0D5 6BDA
C0D6 6C08
C0D7 6FD8
C0D8 6FF1
C0D9 6FDF
C0DA 6FE0
C0DB 6FDB
C0DC 6FE4
C0DD 6FEB
C0DE 6FEF
C0DF 6F80
C0E0 6FEC
C0E1 6FE1
C0E2 6FE9
C0E3 6FD5
C0E4 6FEE
C0E5 6FF0
C0E6 71E7
C0E7 71DF
C0E8 71EE
C0E9 71E6
C0EA 71E5
C0EB 71ED
C0EC 71EC
C0ED 71F4
C0EE 71E0
C0EF 7235
C0F0 7246
C0F1 7370
C0F2 7372
C0F3 74A9
C0F4 74B0
C0F5 74A6
C0F6 74A8
C0F7 7646
C0F8 7642
C0F9 764C
C0FA 76EA
C0FB 77B3
C0FC 77AA
C0FD 77B0
C0FE 77AC
C140 77A7
C141 77AD
C142 77EF
C143 78F7
C144 78FA
C145 78F4
C146 78EF
C147 7901
C148 79A7
C149 79AA
C14A 7A57
C14B 7ABF
C14C 7C07
C14D 7C0D
C14E 7BFE
C14F 7BF7
C150 7C0C
C151 7BE0
C152 7CE0
C153 7CDC
C154 7CDE
C155 7CE2
C156 7CDF
C157 7CD9
C158 7CDD
C159 7E2E
C15A 7E3E
C15B 7E46
C15C 7E37
C15D 7E32
C15E 7E43
C15F 7E2B
C160 7E3D
C161 7E31
C162 7E45
C163 7E41
C164 7E34
C165 7E39
C166 7E48
C167 7E35
C168 7E3F
C169 7E2F
C16A 7F44
C16B 7FF3
C16C 7FFC
C16D 8071
C16E 8072
C16F 8070
C170 806F
C171 8073
C172 81C6
C173 81C3
C174 81BA
C175 81C2
C176 81C0
C177 81BF
C178 81BD
C179 81C9
C17A 81BE
C17B 81E8
C17C 8209
C17D 8271
C17E 85AA
C1A1 8584
C1A2 857E
C1A3 859C
C1A4 8591
C1A5 8594
C1A6 85AF
C1A7 859B
C1A8 8587
C1A9 85A8
C1AA 858A
C1AB 8667
C1AC 87C0
C1AD 87D1
C1AE 87B3
C1AF 87D2
C1B0 87C6
C1B1 87AB
C1B2 87BB
C1B3 87BA
C1B4 87C8
C1B5 87CB
C1B6 893B
C1B7 8936
C1B8 8944
C1B9 8938
C1BA 893D
C1BB 89AC
C1BC 8B0E
C1BD 8B17
C1BE 8B19
C1BF 8B1B
C1C0 8B0A
C1C1 8B20
C1C2 8B1D
C1C3 8B04
C1C4 8B10
C1C5 8C41
C1C6 8C3F
C1C7 8C73
C1C8 8CFA
C1C9 8CFD
C1CA 8CFC
C1CB 8CF8
C1CC 8CFB
C1CD 8DA8
C1CE 8E49
C1CF 8E4B
C1D0 8E48
C1D1 8E4A
C1D2 8F44
C1D3 8F3E
C1D4 8F42
C1D5 8F45
C1D6 8F3F
C1D7 907F
C1D8 907D
C1D9 9084
C1DA 9081
C1DB 9082
C1DC 9080
C1DD 9139
C1DE 91A3
C1DF 919E
C1E0 919C
C1E1 934D
C1E2 9382
C1E3 9328
C1E4 9375
C1E5 934A
C1E6 9365
C1E7 934B
C1E8 9318
C1E9 937E
C1EA 936C
C1EB 935B
C1EC 9370
C1ED 935A
C1EE 9354
C1EF 95CA
C1F0 95CB
C1F1 95CC
C1F2 95C8
C1F3 95C6
C1F4 96B1
C1F5 96B8
C1F6 96D6
C1F7 971C
C1F8 971E
C1F9 97A0
C1FA 97D3
C1FB 9846
C1FC 98B6
C1FD 9935
C1FE 9A01
C240 99FF
C241 9BAE
C242 9BAB
C243 9BAA
C244 9BAD
C245 9D3B
C246 9D3F
C247 9E8B
C248 9ECF
C249 9EDE
C24A 9EDC
C24B 9EDD
C24C 9EDB
C24D 9F3E
C24E 9F4B
C24F 53E2
C250 5695
C251 56AE
C252 58D9
C253 58D8
C254 5B38
C255 5F5D
C256 61E3
C257 6233
C258 64F4
C259 64F2
C25A 64FE
C25B 6506
C25C 64FA
C25D 64FB
C25E 64F7
C25F 65B7
C260 66DC
C261 6726
C262 6AB3
C263 6AAC
C264 6AC3
C265 6ABB
C266 6AB8
C267 6AC2
C268 6AAE
C269 6AAF
C26A 6B5F
C26B 6B78
C26C 6BAF
C26D 7009
C26E 700B
C26F 6FFE
C270 7006
C271 6FFA
C272 7011
C273 700F
C274 71FB
C275 71FC
C276 71FE
C277 71F8
C278 7377
C279 7375
C27A 74A7
C27B 74BF
C27C 7515
C27D 7656
C27E 7658
C2A1 7652
C2A2 77BD
C2A3 77BF
C2A4 77BB
C2A5 77BC
C2A6 790E
C2A7 79AE
C2A8 7A61
C2A9 7A62
C2AA 7A60
C2AB 7AC4
C2AC 7AC5
C2AD 7C2B
C2AE 7C27
C2AF 7C2A
C2B0 7C1E
C2B1 7C23
C2B2 7C21
C2B3 7CE7
C2B4 7E54
C2B5 7E55
C2B6 7E5E
C2B7 7E5A
C2B8 7E61
C2B9 7E52
C2BA 7E59
C2BB 7F48
C2BC 7FF9
C2BD 7FFB
C2BE 8077
C2BF 8076
C2C0 81CD
C2C1 81CF
C2C2 820A
C2C3 85CF
C2C4 85A9
C2C5 85CD
C2C6 85D0
C2C7 85C9
C2C8 85B0
C2C9 85BA
C2CA 85B9
C2CB 85A6
C2CC 87EF
C2CD 87EC
C2CE 87F2
C2CF 87E0
C2D0 8986
C2D1 89B2
C2D2 89F4
C2D3 8B28
C2D4 8B39
C2D5 8B2C
C2D6 8B2B
C2D7 8C50
C2D8 8D05
C2D9 8E59
C2DA 8E63
C2DB 8E66
C2DC 8E64
C2DD 8E5F
C2DE 8E55
C2DF 8EC0
C2E0 8F49
C2E1 8F4D
C2E2 9087
C2E3 9083
C2E4 9088
C2E5 91AB
C2E6 91AC
C2E7 91D0
C2E8 9394
C2E9 938A
C2EA 9396
C2EB 93A2
C2EC 93B3
C2ED 93AE
C2EE 93AC
C2EF 93B0
C2F0 9398
C2F1 939A
C2F2 9397
C2F3 95D4
C2F4 95D6
C2F5 95D0
C2F6 95D5
C2F7 96E2
C2F8 96DC
C2F9 96D9
C2FA 96DB
C2FB 96DE
C2FC 9724
C2FD 97A3
C2FE 97A6
C340 97AD
C341 97F9
C342 984D
C343 984F
C344 984C
C345 984E
C346 9853
C347 98BA
C348 993E
C349 993F
C34A 993D
C34B 992E
C34C 99A5
C34D 9A0E
C34E 9AC1
C34F 9B03
C350 9B06
C351 9B4F
C352 9B4E
C353 9B4D
C354 9BCA
C355 9BC9
C356 9BFD
C357 9BC8
C358 9BC0
C359 9D51
C35A 9D5D
C35B 9D60
C35C 9EE0
C35D 9F15
C35E 9F2C
C35F 5133
C360 56A5
C361 58DE
C362 58DF
C363 58E2
C364 5BF5
C365 9F90
C366 5EEC
C367 61F2
C368 61F7
C369 61F6
C36A 61F5
C36B 6500
C36C 650F
C36D 66E0
C36E 66DD
C36F 6AE5
C370 6ADD
C371 6ADA
C372 6AD3
C373 701B
C374 701F
C375 7028
C376 701A
C377 701D
C378 7015
C379 7018
C37A 7206
C37B 720D
C37C 7258
C37D 72A2
C37E 7378
C3A1 737A
C3A2 74BD
C3A3 74CA
C3A4 74E3
C3A5 7587
C3A6 7586
C3A7 765F
C3A8 7661
C3A9 77C7
C3AA 7919
C3AB 79B1
C3AC 7A6B
C3AD 7A69
C3AE 7C3E
C3AF 7C3F
C3B0 7C38
C3B1 7C3D
C3B2 7C37
C3B3 7C40
C3B4 7E6B
C3B5 7E6D
C3B6 7E79
C3B7 7E69
C3B8 7E6A
C3B9 7F85
C3BA 7E73
C3BB 7FB6
C3BC 7FB9
C3BD 7FB8
C3BE 81D8
C3BF 85E9
C3C0 85DD
C3C1 85EA
C3C2 85D5
C3C3 85E4
C3C4 85E5
C3C5 85F7
C3C6 87FB
C3C7 8805
C3C8 880D
C3C9 87F9
C3CA 87FE
C3CB 8960
C3CC 895F
C3CD 8956
C3CE 895E
C3CF 8B41
C3D0 8B5C
C3D1 8B58
C3D2 8B49
C3D3 8B5A
C3D4 8B4E
C3D5 8B4F
C3D6 8B46
C3D7 8B59
C3D8 8D08
C3D9 8D0A
C3DA 8E7C
C3DB 8E72
C3DC 8E87
C3DD 8E76
C3DE 8E6C
C3DF 8E7A
C3E0 8E74
C3E1 8F54
C3E2 8F4E
C3E3 8FAD
C3E4 908A
C3E5 908B
C3E6 91B1
C3E7 91AE
C3E8 93E1
C3E9 93D1
C3EA 93DF
C3EB 93C3
C3EC 93C8
C3ED 93DC
C3EE 93DD
C3EF 93D6
C3F0 93E2
C3F1 93CD
C3F2 93D8
C3F3 93E4
C3F4 93D7
C3F5 93E8
C3F6 95DC
C3F7 96B4
C3F8 96E3
C3F9 972A
C3FA 9727
C3FB 9761
C3FC 97DC
C3FD 97FB
C3FE 985E
C440 9858
C441 985B
C442 98BC
C443 9945
C444 9949
C445 9A16
C446 9A19
C447 9B0D
C448 9BE8
C449 9BE7
C44A 9BD6
C44B 9BDB
C44C 9D89
C44D 9D61
C44E 9D72
C44F 9D6A
C450 9D6C
C451 9E92
C452 9E97
C453 9E93
C454 9EB4
C455 52F8
C456 56A8
C457 56B7
C458 56B6
C459 56B4
C45A 56BC
C45B 58E4
C45C 5B40
C45D 5B43
C45E 5B7D
C45F 5BF6
C460 5DC9
C461 61F8
C462 61FA
C463 6518
C464 6514
C465 6519
C466 66E6
C467 6727
C468 6AEC
C469 703E
C46A 7030
C46B 7032
C46C 7210
C46D 737B
C46E 74CF
C46F 7662
C470 7665
C471 7926
C472 792A
C473 792C
C474 792B
C475 7AC7
C476 7AF6
C477 7C4C
C478 7C43
C479 7C4D
C47A 7CEF
C47B 7CF0
C47C 8FAE
C47D 7E7D
C47E 7E7C
C4A1 7E82
C4A2 7F4C
C4A3 8000
C4A4 81DA
C4A5 8266
C4A6 85FB
C4A7 85F9
C4A8 8611
C4A9 85FA
C4AA 8606
C4AB 860B
C4AC 8607
C4AD 860A
C4AE 8814
C4AF 8815
C4B0 8964
C4B1 89BA
C4B2 89F8
C4B3 8B70
C4B4 8B6C
C4B5 8B66
C4B6 8B6F
C4B7 8B5F
C4B8 8B6B
C4B9 8D0F
C4BA 8D0D
C4BB 8E89
C4BC 8E81
C4BD 8E85
C4BE 8E82
C4BF 91B4
C4C0 91CB
C4C1 9418
C4C2 9403
C4C3 93FD
C4C4 95E1
C4C5 9730
C4C6 98C4
C4C7 9952
C4C8 9951
C4C9 99A8
C4CA 9A2B
C4CB 9A30
C4CC 9A37
C4CD 9A35
C4CE 9C13
C4CF 9C0D
C4D0 9E79
C4D1 9EB5
C4D2 9EE8
C4D3 9F2F
C4D4 9F5F
C4D5 9F63
C4D6 9F61
C4D7 5137
C4D8 5138
C4D9 56C1
C4DA 56C0
C4DB 56C2
C4DC 5914
C4DD 5C6C
C4DE 5DCD
C4DF 61FC
C4E0 61FE
C4E1 651D
C4E2 651C
C4E3 6595
C4E4 66E9
C4E5 6AFB
C4E6 6B04
C4E7 6AFA
C4E8 6BB2
C4E9 704C
C4EA 721B
C4EB 72A7
C4EC 74D6
C4ED 74D4
C4EE 7669
C4EF 77D3
C4F0 7C50
C4F1 7E8F
C4F2 7E8C
C4F3 7FBC
C4F4 8617
C4F5 862D
C4F6 861A
C4F7 8823
C4F8 8822
C4F9 8821
C4FA 881F
C4FB 896A
C4FC 896C
C4FD 89BD
C4FE 8B74
C540 8B77
C541 8B7D
C542 8D13
C543 8E8A
C544 8E8D
C545 8E8B
C546 8F5F
C547 8FAF
C548 91BA
C549 942E
C54A 9433
C54B 9435
C54C 943A
C54D 9438
C54E 9432
C54F 942B
C550 95E2
C551 9738
C552 9739
C553 9732
C554 97FF
C555 9867
C556 9865
C557 9957
C558 9A45
C559 9A43
C55A 9A40
C55B 9A3E
C55C 9ACF
C55D 9B54
C55E 9B51
C55F 9C2D
C560 9C25
C561 9DAF
C562 9DB4
C563 9DC2
C564 9DB8
C565 9E9D
C566 9EEF
C567 9F19
C568 9F5C
C569 9F66
C56A 9F67
C56B 513C
C56C 513B
C56D 56C8
C56E 56CA
C56F 56C9
C570 5B7F
C571 5DD4
C572 5DD2
C573 5F4E
C574 61FF
C575 6524
C576 6B0A
C577 6B61
C578 7051
C579 7058
C57A 7380
C57B 74E4
C57C 758A
C57D 766E
C57E 766C
C5A1 79B3
C5A2 7C60
C5A3 7C5F
C5A4 807E
C5A5 807D
C5A6 81DF
C5A7 8972
C5A8 896F
C5A9 89FC
C5AA 8B80
C5AB 8D16
C5AC 8D17
C5AD 8E91
C5AE 8E93
C5AF 8F61
C5B0 9148
C5B1 9444
C5B2 9451
C5B3 9452
C5B4 973D
C5B5 973E
C5B6 97C3
C5B7 97C1
C5B8 986B
C5B9 9955
C5BA 9A55
C5BB 9A4D
C5BC 9AD2
C5BD 9B1A
C5BE 9C49
C5BF 9C31
C5C0 9C3E
C5C1 9C3B
C5C2 9DD3
C5C3 9DD7
C5C4 9F34
C5C5 9F6C
C5C6 9F6A
C5C7 9F94
C5C8 56CC
C5C9 5DD6
C5CA 6200
C5CB 6523
C5CC 652B
C5CD 652A
C5CE 66EC
C5CF 6B10
C5D0 74DA
C5D1 7ACA
C5D2 7C64
C5D3 7C63
C5D4 7C65
C5D5 7E93
C5D6 7E96
C5D7 7E94
C5D8 81E2
C5D9 8638
C5DA 863F
C5DB 8831
C5DC 8B8A
C5DD 9090
C5DE 908F
C5DF 9463
C5E0 9460
C5E1 9464
C5E2 9768
C5E3 986F
C5E4 995C
C5E5 9A5A
C5E6 9A5B
C5E7 9A57
C5E8 9AD3
C5E9 9AD4
C5EA 9AD1
C5EB 9C54
C5EC 9C57
C5ED 9C56
C5EE 9DE5
C5EF 9E9F
C5F0 9EF4
C5F1 56D1
C5F2 58E9
C5F3 652C
C5F4 705E
C5F5 7671
C5F6 7672
C5F7 77D7
C5F8 7F50
C5F9 7F88
C5FA 8836
C5FB 8839
C5FC 8862
C5FD 8B93
C5FE 8B92
C640 8B96
C641 8277
C642 8D1B
C643 91C0
C644 946A
C645 9742
C646 9748
C647 9744
C648 97C6
C649 9870
C64A 9A5F
C64B 9B22
C64C 9B58
C64D 9C5F
C64E 9DF9
C64F 9DFA
C650 9E7C
C651 9E7D
C652 9F07
C653 9F77
C654 9F72
C655 5EF3
C656 6B16
C657 7063
C658 7C6C
C659 7C6E
C65A 883B
C65B 89C0
C65C 8EA1
C65D 91C1
C65E 9472
C65F 9470
C660 9871
C661 995E
C662 9AD6
C663 9B23
C664 9ECC
C665 7064
C666 77DA
C667 8B9A
C668 9477
C669 97C9
C66A 9A62
C66B 9A65
C66C 7E9C
C66D 8B9C
C66E 8EAA
C66F 91C5
C670 947D
C671 947E
C672 947C
C673 9C77
C674 9C78
C675 9EF7
C676 8C54
C677 947F
C678 9E1A
C679 7228
C67A 9A6A
C67B 9B31
C67C 9E1B
C67D 9E1E
C67E 7C72
C6A1 30FE
C6A2 309D
C6A3 309E
C6A4 3005
C6A5 3041
C6A6 3042
C6A7 3043
C6A8 3044
C6A9 3045
C6AA 3046
C6AB 3047
C6AC 3048
C6AD 3049
C6AE 304A
C6AF 304B
C6B0 304C
C6B1 304D
C6B2 304E
C6B3 304F
C6B4 3050
C6B5 3051
C6B6 3052
C6B7 3053
C6B8 3054
C6B9 3055
C6BA 3056
C6BB 3057
C6BC 3058
C6BD 3059
C6BE 305A
C6BF 305B
C6C0 305C
C6C1 305D
C6C2 305E
C6C3 305F
C6C4 3060
C6C5 3061
C6C6 3062
C6C7 3063
C6C8 3064
C6C9 3065
C6CA 3066
C6CB 3067
C6CC 3068
C6CD 3069
C6CE 306A
C6CF 306B
C6D0 306C
C6D1 306D
C6D2 306E
C6D3 306F
C6D4 3070
C6D5 3071
C6D6 3072
C6D7 3073
C6D8 3074
C6D9 3075
C6DA 3076
C6DB 3077
C6DC 3078
C6DD 3079
C6DE 307A
C6DF 307B
C6E0 307C
C6E1 307D
C6E2 307E
C6E3 307F
C6E4 3080
C6E5 3081
C6E6 3082
C6E7 3083
C6E8 3084
C6E9 3085
C6EA 3086
C6EB 3087
C6EC 3088
C6ED 3089
C6EE 308A
C6EF 308B
C6F0 308C
C6F1 308D
C6F2 308E
C6F3 308F
C6F4 3090
C6F5 3091
C6F6 3092
C6F7 3093
C6F8 30A1
C6F9 30A2
C6FA 30A3
C6FB 30A4
C6FC 30A5
C6FD 30A6
C6FE 30A7
C740 30A8
C741 30A9
C742 30AA
C743 30AB
C744 30AC
C745 30AD
C746 30AE
C747 30AF
C748 30B0
C749 30B1
C74A 30B2
C74B 30B3
C74C 30B4
C74D 30B5
C74E 30B6
C74F 30B7
C750 30B8
C751 30B9
C752 30BA
C753 30BB
C754 30BC
C755 30BD
C756 30BE
C757 30BF
C758 30C0
C759 30C1
C75A 30C2
C75B 30C3
C75C 30C4
C75D 30C5
C75E 30C6
C75F 30C7
C760 30C8
C761 30C9
C762 30CA
C763 30CB
C764 30CC
C765 30CD
C766 30CE
C767 30CF
C768 30D0
C769 30D1
C76A 30D2
C76B 30D3
C76C 30D4
C76D 30D5
C76E 30D6
C76F 30D7
C770 30D8
C771 30D9
C772 30DA
C773 30DB
C774 30DC
C775 30DD
C776 30DE
C777 30DF
C778 30E0
C779 30E1
C77A 30E2
C77B 30E3
C77C 30E4
C77D 30E5
C77E 30E6
C7A1 30E7
C7A2 30E8
C7A3 30E9
C7A4 30EA
C7A5 30EB
C7A6 30EC
C7A7 30ED
C7A8 30EE
C7A9 30EF
C7AA 30F0
C7AB 30F1
C7AC 30F2
C7AD 30F3
C7AE 30F4
C7AF 30F5
C7B0 30F6
C7B1 0414
C7B2 0415
C7B3 0401
C7B4 0416
C7B5 0417
C7B6 0418
C7B7 0419
C7B8 041A
C7B9 041B
C7BA 041C
C7BB 0423
C7BC 0424
C7BD 0425
C7BE 0426
C7BF 0427
C7C0 0428
C7C1 0429
C7C2 042A
C7C3 042B
C7C4 042C
C7C5 042D
C7C6 042E
C7C7 042F
C7C8 0430
C7C9 0431
C7CA 0432
C7CB 0433
C7CC 0434
C7CD 0435
C7CE 0451
C7CF 0436
C7D0 0437
C7D1 0438
C7D2 0439
C7D3 043A
C7D4 043B
C7D5 043C
C7D6 043D
C7D7 043E
C7D8 043F
C7D9 0440
C7DA 0441
C7DB 0442
C7DC 0443
C7DD 0444
C7DE 0445
C7DF 0446
C7E0 0447
C7E1 0448
C7E2 0449
C7E3 044A
C7E4 044B
C7E5 044C
C7E6 044D
C7E7 044E
C7E8 044F
C7E9 2460
C7EA 2461
C7EB 2462
C7EC 2463
C7ED 2464
C7EE 2465
C7EF 2466
C7F0 2467
C7F1 2468
C7F2 2469
C7F3 2474
C7F4 2475
C7F5 2476
C7F6 2477
C7F7 2478
C7F8 2479
C7F9 247A
C7FA 247B
C7FB 247C
C7FC 247D
C940 4E42
C941 4E5C
C942 51F5
C943 531A
C944 5382
C945 4E07
C946 4E0C
C947 4E47
C948 4E8D
C949 56D7
C94A FA0C
C94B 5C6E
C94C 5F73
C94D 4E0F
C94E 5187
C94F 4E0E
C950 4E2E
C951 4E93
C952 4EC2
C953 4EC9
C954 4EC8
C955 5198
C956 52FC
C957 536C
C958 53B9
C959 5720
C95A 5903
C95B 592C
C95C 5C10
C95D 5DFF
C95E 65E1
C95F 6BB3
C960 6BCC
C961 6C14
C962 723F
C963 4E31
C964 4E3C
C965 4EE8
C966 4EDC
C967 4EE9
C968 4EE1
C969 4EDD
C96A 4EDA
C96B 520C
C96C 531C
C96D 534C
C96E 5722
C96F 5723
C970 5917
C971 592F
C972 5B81
C973 5B84
C974 5C12
C975 5C3B
C976 5C74
C977 5C73
C978 5E04
C979 5E80
C97A 5E82
C97B 5FC9
C97C 6209
C97D 6250
C97E 6C15
C9A1 6C36
C9A2 6C43
C9A3 6C3F
C9A4 6C3B
C9A5 72AE
C9A6 72B0
C9A7 738A
C9A8 79B8
C9A9 808A
C9AA 961E
C9AB 4F0E
C9AC 4F18
C9AD 4F2C
C9AE 4EF5
C9AF 4F14
C9B0 4EF1
C9B1 4F00
C9B2 4EF7
C9B3 4F08
C9B4 4F1D
C9B5 4F02
C9B6 4F05
C9B7 4F22
C9B8 4F13
C9B9 4F04
C9BA 4EF4
C9BB 4F12
C9BC 51B1
C9BD 5213
C9BE 5209
C9BF 5210
C9C0 52A6
C9C1 5322
C9C2 531F
C9C3 534D
C9C4 538A
C9C5 5407
C9C6 56E1
C9C7 56DF
C9C8 572E
C9C9 572A
C9CA 5734
C9CB 593C
C9CC 5980
C9CD 597C
C9CE 5985
C9CF 597B
C9D0 597E
C9D1 5977
C9D2 597F
C9D3 5B56
C9D4 5C15
C9D5 5C25
C9D6 5C7C
C9D7 5C7A
C9D8 5C7B
C9D9 5C7E
C9DA 5DDF
C9DB 5E75
C9DC 5E84
C9DD 5F02
C9DE 5F1A
C9DF 5F74
C9E0 5FD5
C9E1 5FD4
C9E2 5FCF
C9E3 625C
C9E4 625E
C9E5 6264
C9E6 6261
C9E7 6266
C9E8 6262
C9E9 6259
C9EA 6260
C9EB 625A
C9EC 6265
C9ED 65EF
C9EE 65EE
C9EF 673E
C9F0 6739
C9F1 6738
C9F2 673B
C9F3 673A
C9F4 673F
C9F5 673C
C9F6 6733
C9F7 6C18
C9F8 6C46
C9F9 6C52
C9FA 6C5C
C9FB 6C4F
C9FC 6C4A
C9FD 6C54
C9FE 6C4B
CA40 6C4C
CA41 7071
CA42 725E
CA43 72B4
CA44 72B5
CA45 738E
CA46 752A
CA47 767F
CA48 7A75
CA49 7F51
CA4A 8278
CA4B 827C
CA4C 8280
CA4D 827D
CA4E 827F
CA4F 864D
CA50 897E
CA51 9099
CA52 9097
CA53 9098
CA54 909B
CA55 9094
CA56 9622
CA57 9624
CA58 9620
CA59 9623
CA5A 4F56
CA5B 4F3B
CA5C 4F62
CA5D 4F49
CA5E 4F53
CA5F 4F64
CA60 4F3E
CA61 4F67
CA62 4F52
CA63 4F5F
CA64 4F41
CA65 4F58
CA66 4F2D
CA67 4F33
CA68 4F3F
CA69 4F61
CA6A 518F
CA6B 51B9
CA6C 521C
CA6D 521E
CA6E 5221
CA6F 52AD
CA70 52AE
CA71 5309
CA72 5363
CA73 5372
CA74 538E
CA75 538F
CA76 5430
CA77 5437
CA78 542A
CA79 5454
CA7A 5445
CA7B 5419
CA7C 541C
CA7D 5425
CA7E 5418
CAA1 543D
CAA2 544F
CAA3 5441
CAA4 5428
CAA5 5424
CAA6 5447
CAA7 56EE
CAA8 56E7
CAA9 56E5
CAAA 5741
CAAB 5745
CAAC 574C
CAAD 5749
CAAE 574B
CAAF 5752
CAB0 5906
CAB1 5940
CAB2 59A6
CAB3 5998
CAB4 59A0
CAB5 5997
CAB6 598E
CAB7 59A2
CAB8 5990
CAB9 598F
CABA 59A7
CABB 59A1
CABC 5B8E
CABD 5B92
CABE 5C28
CABF 5C2A
CAC0 5C8D
CAC1 5C8F
CAC2 5C88
CAC3 5C8B
CAC4 5C89
CAC5 5C92
CAC6 5C8A
CAC7 5C86
CAC8 5C93
CAC9 5C95
CACA 5DE0
CACB 5E0A
CACC 5E0E
CACD 5E8B
CACE 5E89
CACF 5E8C
CAD0 5E88
CAD1 5E8D
CAD2 5F05
CAD3 5F1D
CAD4 5F78
CAD5 5F76
CAD6 5FD2
CAD7 5FD1
CAD8 5FD0
CAD9 5FED
CADA 5FE8
CADB 5FEE
CADC 5FF3
CADD 5FE1
CADE 5FE4
CADF 5FE3
CAE0 5FFA
CAE1 5FEF
CAE2 5FF7
CAE3 5FFB
CAE4 6000
CAE5 5FF4
CAE6 623A
CAE7 6283
CAE8 628C
CAE9 628E
CAEA 628F
CAEB 6294
CAEC 6287
CAED 6271
CAEE 627B
CAEF 627A
CAF0 6270
CAF1 6281
CAF2 6288
CAF3 6277
CAF4 627D
CAF5 6272
CAF6 6274
CAF7 6537
CAF8 65F0
CAF9 65F4
CAFA 65F3
CAFB 65F2
CAFC 65F5
CAFD 6745
CAFE 6747
CB40 6759
CB41 6755
CB42 674C
CB43 6748
CB44 675D
CB45 674D
CB46 675A
CB47 674B
CB48 6BD0
CB49 6C19
CB4A 6C1A
CB4B 6C78
CB4C 6C67
CB4D 6C6B
CB4E 6C84
CB4F 6C8B
CB50 6C8F
CB51 6C71
CB52 6C6F
CB53 6C69
CB54 6C9A
CB55 6C6D
CB56 6C87
CB57 6C95
CB58 6C9C
CB59 6C66
CB5A 6C73
CB5B 6C65
CB5C 6C7B
CB5D 6C8E
CB5E 7074
CB5F 707A
CB60 7263
CB61 72BF
CB62 72BD
CB63 72C3
CB64 72C6
CB65 72C1
CB66 72BA
CB67 72C5
CB68 7395
CB69 7397
CB6A 7393
CB6B 7394
CB6C 7392
CB6D 753A
CB6E 7539
CB6F 7594
CB70 7595
CB71 7681
CB72 793D
CB73 8034
CB74 8095
CB75 8099
CB76 8090
CB77 8092
CB78 809C
CB79 8290
CB7A 828F
CB7B 8285
CB7C 828E
CB7D 8291
CB7E 8293
CBA1 828A
CBA2 8283
CBA3 8284
CBA4 8C78
CBA5 8FC9
CBA6 8FBF
CBA7 909F
CBA8 90A1
CBA9 90A5
CBAA 909E
CBAB 90A7
CBAC 90A0
CBAD 9630
CBAE 9628
CBAF 962F
CBB0 962D
CBB1 4E33
CBB2 4F98
CBB3 4F7C
CBB4 4F85
CBB5 4F7D
CBB6 4F80
CBB7 4F87
CBB8 4F76
CBB9 4F74
CBBA 4F89
CBBB 4F84
CBBC 4F77
CBBD 4F4C
CBBE 4F97
CBBF 4F6A
CBC0 4F9A
CBC1 4F79
CBC2 4F81
CBC3 4F78
CBC4 4F90
CBC5 4F9C
CBC6 4F94
CBC7 4F9E
CBC8 4F92
CBC9 4F82
CBCA 4F95
CBCB 4F6B
CBCC 4F6E
CBCD 519E
CBCE 51BC
CBCF 51BE
CBD0 5235
CBD1 5232
CBD2 5233
CBD3 5246
CBD4 5231
CBD5 52BC
CBD6 530A
CBD7 530B
CBD8 533C
CBD9 5392
CBDA 5394
CBDB 5487
CBDC 547F
CBDD 5481
CBDE 5491
CBDF 5482
CBE0 5488
CBE1 546B
CBE2 547A
CBE3 547E
CBE4 5465
CBE5 546C
CBE6 5474
CBE7 5466
CBE8 548D
CBE9 546F
CBEA 5461
CBEB 5460
CBEC 5498
CBED 5463
CBEE 5467
CBEF 5464
CBF0 56F7
CBF1 56F9
CBF2 576F
CBF3 5772
CBF4 576D
CBF5 576B
CBF6 5771
CBF7 5770
CBF8 5776
CBF9 5780
CBFA 5775
CBFB 577B
CBFC 5773
CBFD 5774
CBFE 5762
CC40 5768
CC41 577D
CC42 590C
CC43 5945
CC44 59B5
CC45 59BA
CC46 59CF
CC47 59CE
CC48 59B2
CC49 59CC
CC4A 59C1
CC4B 59B6
CC4C 59BC
CC4D 59C3
CC4E 59D6
CC4F 59B1
CC50 59BD
CC51 59C0
CC52 59C8
CC53 59B4
CC54 59C7
CC55 5B62
CC56 5B65
CC57 5B93
CC58 5B95
CC59 5C44
CC5A 5C47
CC5B 5CAE
CC5C 5CA4
CC5D 5CA0
CC5E 5CB5
CC5F 5CAF
CC60 5CA8
CC61 5CAC
CC62 5C9F
CC63 5CA3
CC64 5CAD
CC65 5CA2
CC66 5CAA
CC67 5CA7
CC68 5C9D
CC69 5CA5
CC6A 5CB6
CC6B 5CB0
CC6C 5CA6
CC6D 5E17
CC6E 5E14
CC6F 5E19
CC70 5F28
CC71 5F22
CC72 5F23
CC73 5F24
CC74 5F54
CC75 5F82
CC76 5F7E
CC77 5F7D
CC78 5FDE
CC79 5FE5
CC7A 602D
CC7B 6026
CC7C 6019
CC7D 6032
CC7E 600B
CCA1 6034
CCA2 600A
CCA3 6017
CCA4 6033
CCA5 601A
CCA6 601E
CCA7 602C
CCA8 6022
CCA9 600D
CCAA 6010
CCAB 602E
CCAC 6013
CCAD 6011
CCAE 600C
CCAF 6009
CCB0 601C
CCB1 6214
CCB2 623D
CCB3 62AD
CCB4 62B4
CCB5 62D1
CCB6 62BE
CCB7 62AA
CCB8 62B6
CCB9 62CA
CCBA 62AE
CCBB 62B3
CCBC 62AF
CCBD 62BB
CCBE 62A9
CCBF 62B0
CCC0 62B8
CCC1 653D
CCC2 65A8
CCC3 65BB
CCC4 6609
CCC5 65FC
CCC6 6604
CCC7 6612
CCC8 6608
CCC9 65FB
CCCA 6603
CCCB 660B
CCCC 660D
CCCD 6605
CCCE 65FD
CCCF 6611
CCD0 6610
CCD1 66F6
CCD2 670A
CCD3 6785
CCD4 676C
CCD5 678E
CCD6 6792
CCD7 6776
CCD8 677B
CCD9 6798
CCDA 6786
CCDB 6784
CCDC 6774
CCDD 678D
CCDE 678C
CCDF 677A
CCE0 679F
CCE1 6791
CCE2 6799
CCE3 6783
CCE4 677D
CCE5 6781
CCE6 6778
CCE7 6779
CCE8 6794
CCE9 6B25
CCEA 6B80
CCEB 6B7E
CCEC 6BDE
CCED 6C1D
CCEE 6C93
CCEF 6CEC
CCF0 6CEB
CCF1 6CEE
CCF2 6CD9
CCF3 6CB6
CCF4 6CD4
CCF5 6CAD
CCF6 6CE7
CCF7 6CB7
CCF8 6CD0
CCF9 6CC2
CCFA 6CBA
CCFB 6CC3
CCFC 6CC6
CCFD 6CED
CCFE 6CF2
CD40 6CD2
CD41 6CDD
CD42 6CB4
CD43 6C8A
CD44 6C9D
CD45 6C80
CD46 6CDE
CD47 6CC0
CD48 6D30
CD49 6CCD
CD4A 6CC7
CD4B 6CB0
CD4C 6CF9
CD4D 6CCF
CD4E 6CE9
CD4F 6CD1
CD50 7094
CD51 7098
CD52 7085
CD53 7093
CD54 7086
CD55 7084
CD56 7091
CD57 7096
CD58 7082
CD59 709A
CD5A 7083
CD5B 726A
CD5C 72D6
CD5D 72CB
CD5E 72D8
CD5F 72C9
CD60 72DC
CD61 72D2
CD62 72D4
CD63 72DA
CD64 72CC
CD65 72D1
CD66 73A4
CD67 73A1
CD68 73AD
CD69 73A6
CD6A 73A2
CD6B 73A0
CD6C 73AC
CD6D 739D
CD6E 74DD
CD6F 74E8
CD70 753F
CD71 7540
CD72 753E
CD73 758C
CD74 7598
CD75 76AF
CD76 76F3
CD77 76F1
CD78 76F0
CD79 76F5
CD7A 77F8
CD7B 77FC
CD7C 77F9
CD7D 77FB
CD7E 77FA
CDA1 77F7
CDA2 7942
CDA3 793F
CDA4 79C5
CDA5 7A78
CDA6 7A7B
CDA7 7AFB
CDA8 7C75
CDA9 7CFD
CDAA 8035
CDAB 808F
CDAC 80AE
CDAD 80A3
CDAE 80B8
CDAF 80B5
CDB0 80AD
CDB1 8220
CDB2 82A0
CDB3 82C0
CDB4 82AB
CDB5 829A
CDB6 8298
CDB7 829B
CDB8 82B5
CDB9 82A7
CDBA 82AE
CDBB 82BC
CDBC 829E
CDBD 82BA
CDBE 82B4
CDBF 82A8
CDC0 82A1
CDC1 82A9
CDC2 82C2
CDC3 82A4
CDC4 82C3
CDC5 82B6
CDC6 82A2
CDC7 8670
CDC8 866F
CDC9 866D
CDCA 866E
CDCB 8C56
CDCC 8FD2
CDCD 8FCB
CDCE 8FD3
CDCF 8FCD
CDD0 8FD6
CDD1 8FD5
CDD2 8FD7
CDD3 90B2
CDD4 90B4
CDD5 90AF
CDD6 90B3
CDD7 90B0
CDD8 9639
CDD9 963D
CDDA 963C
CDDB 963A
CDDC 9643
CDDD 4FCD
CDDE 4FC5
CDDF 4FD3
CDE0 4FB2
CDE1 4FC9
CDE2 4FCB
CDE3 4FC1
CDE4 4FD4
CDE5 4FDC
CDE6 4FD9
CDE7 4FBB
CDE8 4FB3
CDE9 4FDB
CDEA 4FC7
CDEB 4FD6
CDEC 4FBA
CDED 4FC0
CDEE 4FB9
CDEF 4FEC
CDF0 5244
CDF1 5249
CDF2 52C0
CDF3 52C2
CDF4 533D
CDF5 537C
CDF6 5397
CDF7 5396
CDF8 5399
CDF9 5398
CDFA 54BA
CDFB 54A1
CDFC 54AD
CDFD 54A5
CDFE 54CF
CE40 54C3
CE41 830D
CE42 54B7
CE43 54AE
CE44 54D6
CE45 54B6
CE46 54C5
CE47 54C6
CE48 54A0
CE49 5470
CE4A 54BC
CE4B 54A2
CE4C 54BE
CE4D 5472
CE4E 54DE
CE4F 54B0
CE50 57B5
CE51 579E
CE52 579F
CE53 57A4
CE54 578C
CE55 5797
CE56 579D
CE57 579B
CE58 5794
CE59 5798
CE5A 578F
CE5B 5799
CE5C 57A5
CE5D 579A
CE5E 5795
CE5F 58F4
CE60 590D
CE61 5953
CE62 59E1
CE63 59DE
CE64 59EE
CE65 5A00
CE66 59F1
CE67 59DD
CE68 59FA
CE69 59FD
CE6A 59FC
CE6B 59F6
CE6C 59E4
CE6D 59F2
CE6E 59F7
CE6F 59DB
CE70 59E9
CE71 59F3
CE72 59F5
CE73 59E0
CE74 59FE
CE75 59F4
CE76 59ED
CE77 5BA8
CE78 5C4C
CE79 5CD0
CE7A 5CD8
CE7B 5CCC
CE7C 5CD7
CE7D 5CCB
CE7E 5CDB
CEA1 5CDE
CEA2 5CDA
CEA3 5CC9
CEA4 5CC7
CEA5 5CCA
CEA6 5CD6
CEA7 5CD3
CEA8 5CD4
CEA9 5CCF
CEAA 5CC8
CEAB 5CC6
CEAC 5CCE
CEAD 5CDF
CEAE 5CF8
CEAF 5DF9
CEB0 5E21
CEB1 5E22
CEB2 5E23
CEB3 5E20
CEB4 5E24
CEB5 5EB0
CEB6 5EA4
CEB7 5EA2
CEB8 5E9B
CEB9 5EA3
CEBA 5EA5
CEBB 5F07
CEBC 5F2E
CEBD 5F56
CEBE 5F86
CEBF 6037
CEC0 6039
CEC1 6054
CEC2 6072
CEC3 605E
CEC4 6045
CEC5 6053
CEC6 6047
CEC7 6049
CEC8 605B
CEC9 604C
CECA 6040
CECB 6042
CECC 605F
CECD 6024
CECE 6044
CECF 6058
CED0 6066
CED1 606E
CED2 6242
CED3 6243
CED4 62CF
CED5 630D
CED6 630B
CED7 62F5
CED8 630E
CED9 6303
CEDA 62EB
CEDB 62F9
CEDC 630F
CEDD 630C
CEDE 62F8
CEDF 62F6
CEE0 6300
CEE1 6313
CEE2 6314
CEE3 62FA
CEE4 6315
CEE5 62FB
CEE6 62F0
CEE7 6541
CEE8 6543
CEE9 65AA
CEEA 65BF
CEEB 6636
CEEC 6621
CEED 6632
CEEE 6635
CEEF 661C
CEF0 6626
CEF1 6622
CEF2 6633
CEF3 662B
CEF4 663A
CEF5 661D
CEF6 6634
CEF7 6639
CEF8 662E
CEF9 670F
CEFA 6710
CEFB 67C1
CEFC 67F2
CEFD 67C8
CEFE 67BA
CF40 67DC
CF41 67BB
CF42 67F8
CF43 67D8
CF44 67C0
CF45 67B7
CF46 67C5
CF47 67EB
CF48 67E4
CF49 67DF
CF4A 67B5
CF4B 67CD
CF4C 67B3
CF4D 67F7
CF4E 67F6
CF4F 67EE
CF50 67E3
CF51 67C2
CF52 67B9
CF53 67CE
CF54 67E7
CF55 67F0
CF56 67B2
CF57 67FC
CF58 67C6
CF59 67ED
CF5A 67CC
CF5B 67AE
CF5C 67E6
CF5D 67DB
CF5E 67FA
CF5F 67C9
CF60 67CA
CF61 67C3
CF62 67EA
CF63 67CB
CF64 6B28
CF65 6B82
CF66 6B84
CF67 6BB6
CF68 6BD6
CF69 6BD8
CF6A 6BE0
CF6B 6C20
CF6C 6C21
CF6D 6D28
CF6E 6D34
CF6F 6D2D
CF70 6D1F
CF71 6D3C
CF72 6D3F
CF73 6D12
CF74 6D0A
CF75 6CDA
CF76 6D33
CF77 6D04
CF78 6D19
CF79 6D3A
CF7A 6D1A
CF7B 6D11
CF7C 6D00
CF7D 6D1D
CF7E 6D42
CFA1 6D01
CFA2 6D18
CFA3 6D37
CFA4 6D03
CFA5 6D0F
CFA6 6D40
CFA7 6D07
CFA8 6D20
CFA9 6D2C
CFAA 6D08
CFAB 6D22
CFAC 6D09
CFAD 6D10
CFAE 70B7
CFAF 709F
CFB0 70BE
CFB1 70B1
CFB2 70B0
CFB3 70A1
CFB4 70B4
CFB5 70B5
CFB6 70A9
CFB7 7241
CFB8 7249
CFB9 724A
CFBA 726C
CFBB 7270
CFBC 7273
CFBD 726E
CFBE 72CA
CFBF 72E4
CFC0 72E8
CFC1 72EB
CFC2 72DF
CFC3 72EA
CFC4 72E6
CFC5 72E3
CFC6 7385
CFC7 73CC
CFC8 73C2
CFC9 73C8
CFCA 73C5
CFCB 73B9
CFCC 73B6
CFCD 73B5
CFCE 73B4
CFCF 73EB
CFD0 73BF
CFD1 73C7
CFD2 73BE
CFD3 73C3
CFD4 73C6
CFD5 73B8
CFD6 73CB
CFD7 74EC
CFD8 74EE
CFD9 752E
CFDA 7547
CFDB 7548
CFDC 75A7
CFDD 75AA
CFDE 7679
CFDF 76C4
CFE0 7708
CFE1 7703
CFE2 7704
CFE3 7705
CFE4 770A
CFE5 76F7
CFE6 76FB
CFE7 76FA
CFE8 77E7
CFE9 77E8
CFEA 7806
CFEB 7811
CFEC 7812
CFED 7805
CFEE 7810
CFEF 780F
CFF0 780E
CFF1 7809
CFF2 7803
CFF3 7813
CFF4 794A
CFF5 794C
CFF6 794B
CFF7 7945
CFF8 7944
CFF9 79D5
CFFA 79CD
CFFB 79CF
CFFC 79D6
CFFD 79CE
CFFE 7A80
D040 7A7E
D041 7AD1
D042 7B00
D043 7B01
D044 7C7A
D045 7C78
D046 7C79
D047 7C7F
D048 7C80
D049 7C81
D04A 7D03
D04B 7D08
D04C 7D01
D04D 7F58
D04E 7F91
D04F 7F8D
D050 7FBE
D051 8007
D052 800E
D053 800F
D054 8014
D055 8037
D056 80D8
D057 80C7
D058 80E0
D059 80D1
D05A 80C8
D05B 80C2
D05C 80D0
D05D 80C5
D05E 80E3
D05F 80D9
D060 80DC
D061 80CA
D062 80D5
D063 80C9
D064 80CF
D065 80D7
D066 80E6
D067 80CD
D068 81FF
D069 8221
D06A 8294
D06B 82D9
D06C 82FE
D06D 82F9
D06E 8307
D06F 82E8
D070 8300
D071 82D5
D072 833A
D073 82EB
D074 82D6
D075 82F4
D076 82EC
D077 82E1
D078 82F2
D079 82F5
D07A 830C
D07B 82FB
D07C 82F6
D07D 82F0
D07E 82EA
D0A1 82E4
D0A2 82E0
D0A3 82FA
D0A4 82F3
D0A5 82ED
D0A6 8677
D0A7 8674
D0A8 867C
D0A9 8673
D0AA 8841
D0AB 884E
D0AC 8867
D0AD 886A
D0AE 8869
D0AF 89D3
D0B0 8A04
D0B1 8A07
D0B2 8D72
D0B3 8FE3
D0B4 8FE1
D0B5 8FEE
D0B6 8FE0
D0B7 90F1
D0B8 90BD
D0B9 90BF
D0BA 90D5
D0BB 90C5
D0BC 90BE
D0BD 90C7
D0BE 90CB
D0BF 90C8
D0C0 91D4
D0C1 91D3
D0C2 9654
D0C3 964F
D0C4 9651
D0C5 9653
D0C6 964A
D0C7 964E
D0C8 501E
D0C9 5005
D0CA 5007
D0CB 5013
D0CC 5022
D0CD 5030
D0CE 501B
D0CF 4FF5
D0D0 4FF4
D0D1 5033
D0D2 5037
D0D3 502C
D0D4 4FF6
D0D5 4FF7
D0D6 5017
D0D7 501C
D0D8 5020
D0D9 5027
D0DA 5035
D0DB 502F
D0DC 5031
D0DD 500E
D0DE 515A
D0DF 5194
D0E0 5193
D0E1 51CA
D0E2 51C4
D0E3 51C5
D0E4 51C8
D0E5 51CE
D0E6 5261
D0E7 525A
D0E8 5252
D0E9 525E
D0EA 525F
D0EB 5255
D0EC 5262
D0ED 52CD
D0EE 530E
D0EF 539E
D0F0 5526
D0F1 54E2
D0F2 5517
D0F3 5512
D0F4 54E7
D0F5 54F3
D0F6 54E4
D0F7 551A
D0F8 54FF
D0F9 5504
D0FA 5508
D0FB 54EB
D0FC 5511
D0FD 5505
D0FE 54F1
D140 550A
D141 54FB
D142 54F7
D143 54F8
D144 54E0
D145 550E
D146 5503
D147 550B
D148 5701
D149 5702
D14A 57CC
D14B 5832
D14C 57D5
D14D 57D2
D14E 57BA
D14F 57C6
D150 57BD
D151 57BC
D152 57B8
D153 57B6
D154 57BF
D155 57C7
D156 57D0
D157 57B9
D158 57C1
D159 590E
D15A 594A
D15B 5A19
D15C 5A16
D15D 5A2D
D15E 5A2E
D15F 5A15
D160 5A0F
D161 5A17
D162 5A0A
D163 5A1E
D164 5A33
D165 5B6C
D166 5BA7
D167 5BAD
D168 5BAC
D169 5C03
D16A 5C56
D16B 5C54
D16C 5CEC
D16D 5CFF
D16E 5CEE
D16F 5CF1
D170 5CF7
D171 5D00
D172 5CF9
D173 5E29
D174 5E28
D175 5EA8
D176 5EAE
D177 5EAA
D178 5EAC
D179 5F33
D17A 5F30
D17B 5F67
D17C 605D
D17D 605A
D17E 6067
D1A1 6041
D1A2 60A2
D1A3 6088
D1A4 6080
D1A5 6092
D1A6 6081
D1A7 609D
D1A8 6083
D1A9 6095
D1AA 609B
D1AB 6097
D1AC 6087
D1AD 609C
D1AE 608E
D1AF 6219
D1B0 6246
D1B1 62F2
D1B2 6310
D1B3 6356
D1B4 632C
D1B5 6344
D1B6 6345
D1B7 6336
D1B8 6343
D1B9 63E4
D1BA 6339
D1BB 634B
D1BC 634A
D1BD 633C
D1BE 6329
D1BF 6341
D1C0 6334
D1C1 6358
D1C2 6354
D1C3 6359
D1C4 632D
D1C5 6347
D1C6 6333
D1C7 635A
D1C8 6351
D1C9 6338
D1CA 6357
D1CB 6340
D1CC 6348
D1CD 654A
D1CE 6546
D1CF 65C6
D1D0 65C3
D1D1 65C4
D1D2 65C2
D1D3 664A
D1D4 665F
D1D5 6647
D1D6 6651
D1D7 6712
D1D8 6713
D1D9 681F
D1DA 681A
D1DB 6849
D1DC 6832
D1DD 6833
D1DE 683B
D1DF 684B
D1E0 684F
D1E1 6816
D1E2 6831
D1E3 681C
D1E4 6835
D1E5 682B
D1E6 682D
D1E7 682F
D1E8 684E
D1E9 6844
D1EA 6834
D1EB 681D
D1EC 6812
D1ED 6814
D1EE 6826
D1EF 6828
D1F0 682E
D1F1 684D
D1F2 683A
D1F3 6825
D1F4 6820
D1F5 6B2C
D1F6 6B2F
D1F7 6B2D
D1F8 6B31
D1F9 6B34
D1FA 6B6D
D1FB 8082
D1FC 6B88
D1FD 6BE6
D1FE 6BE4
D240 6BE8
D241 6BE3
D242 6BE2
D243 6BE7
D244 6C25
D245 6D7A
D246 6D63
D247 6D64
D248 6D76
D249 6D0D
D24A 6D61
D24B 6D92
D24C 6D58
D24D 6D62
D24E 6D6D
D24F 6D6F
D250 6D91
D251 6D8D
D252 6DEF
D253 6D7F
D254 6D86
D255 6D5E
D256 6D67
D257 6D60
D258 6D97
D259 6D70
D25A 6D7C
D25B 6D5F
D25C 6D82
D25D 6D98
D25E 6D2F
D25F 6D68
D260 6D8B
D261 6D7E
D262 6D80
D263 6D84
D264 6D16
D265 6D83
D266 6D7B
D267 6D7D
D268 6D75
D269 6D90
D26A 70DC
D26B 70D3
D26C 70D1
D26D 70DD
D26E 70CB
D26F 7F39
D270 70E2
D271 70D7
D272 70D2
D273 70DE
D274 70E0
D275 70D4
D276 70CD
D277 70C5
D278 70C6
D279 70C7
D27A 70DA
D27B 70CE
D27C 70E1
D27D 7242
D27E 7278
D2A1 7277
D2A2 7276
D2A3 7300
D2A4 72FA
D2A5 72F4
D2A6 72FE
D2A7 72F6
D2A8 72F3
D2A9 72FB
D2AA 7301
D2AB 73D3
D2AC 73D9
D2AD 73E5
D2AE 73D6
D2AF 73BC
D2B0 73E7
D2B1 73E3
D2B2 73E9
D2B3 73DC
D2B4 73D2
D2B5 73DB
D2B6 73D4
D2B7 73DD
D2B8 73DA
D2B9 73D7
D2BA 73D8
D2BB 73E8
D2BC 74DE
D2BD 74DF
D2BE 74F4
D2BF 74F5
D2C0 7521
D2C1 755B
D2C2 755F
D2C3 75B0
D2C4 75C1
D2C5 75BB
D2C6 75C4
D2C7 75C0
D2C8 75BF
D2C9 75B6
D2CA 75BA
D2CB 768A
D2CC 76C9
D2CD 771D
D2CE 771B
D2CF 7710
D2D0 7713
D2D1 7712
D2D2 7723
D2D3 7711
D2D4 7715
D2D5 7719
D2D6 771A
D2D7 7722
D2D8 7727
D2D9 7823
D2DA 782C
D2DB 7822
D2DC 7835
D2DD 782F
D2DE 7828
D2DF 782E
D2E0 782B
D2E1 7821
D2E2 7829
D2E3 7833
D2E4 782A
D2E5 7831
D2E6 7954
D2E7 795B
D2E8 794F
D2E9 795C
D2EA 7953
D2EB 7952
D2EC 7951
D2ED 79EB
D2EE 79EC
D2EF 79E0
D2F0 79EE
D2F1 79ED
D2F2 79EA
D2F3 79DC
D2F4 79DE
D2F5 79DD
D2F6 7A86
D2F7 7A89
D2F8 7A85
D2F9 7A8B
D2FA 7A8C
D2FB 7A8A
D2FC 7A87
D2FD 7AD8
D2FE 7B10
D340 7B04
D341 7B13
D342 7B05
D343 7B0F
D344 7B08
D345 7B0A
D346 7B0E
D347 7B09
D348 7B12
D349 7C84
D34A 7C91
D34B 7C8A
D34C 7C8C
D34D 7C88
D34E 7C8D
D34F 7C85
D350 7D1E
D351 7D1D
D352 7D11
D353 7D0E
D354 7D18
D355 7D16
D356 7D13
D357 7D1F
D358 7D12
D359 7D0F
D35A 7D0C
D35B 7F5C
D35C 7F61
D35D 7F5E
D35E 7F60
D35F 7F5D
D360 7F5B
D361 7F96
D362 7F92
D363 7FC3
D364 7FC2
D365 7FC0
D366 8016
D367 803E
D368 8039
D369 80FA
D36A 80F2
D36B 80F9
D36C 80F5
D36D 8101
D36E 80FB
D36F 8100
D370 8201
D371 822F
D372 8225
D373 8333
D374 832D
D375 8344
D376 8319
D377 8351
D378 8325
D379 8356
D37A 833F
D37B 8341
D37C 8326
D37D 831C
D37E 8322
D3A1 8342
D3A2 834E
D3A3 831B
D3A4 832A
D3A5 8308
D3A6 833C
D3A7 834D
D3A8 8316
D3A9 8324
D3AA 8320
D3AB 8337
D3AC 832F
D3AD 8329
D3AE 8347
D3AF 8345
D3B0 834C
D3B1 8353
D3B2 831E
D3B3 832C
D3B4 834B
D3B5 8327
D3B6 8348
D3B7 8653
D3B8 8652
D3B9 86A2
D3BA 86A8
D3BB 8696
D3BC 868D
D3BD 8691
D3BE 869E
D3BF 8687
D3C0 8697
D3C1 8686
D3C2 868B
D3C3 869A
D3C4 8685
D3C5 86A5
D3C6 8699
D3C7 86A1
D3C8 86A7
D3C9 8695
D3CA 8698
D3CB 868E
D3CC 869D
D3CD 8690
D3CE 8694
D3CF 8843
D3D0 8844
D3D1 886D
D3D2 8875
D3D3 8876
D3D4 8872
D3D5 8880
D3D6 8871
D3D7 887F
D3D8 886F
D3D9 8883
D3DA 887E
D3DB 8874
D3DC 887C
D3DD 8A12
D3DE 8C47
D3DF 8C57
D3E0 8C7B
D3E1 8CA4
D3E2 8CA3
D3E3 8D76
D3E4 8D78
D3E5 8DB5
D3E6 8DB7
D3E7 8DB6
D3E8 8ED1
D3E9 8ED3
D3EA 8FFE
D3EB 8FF5
D3EC 9002
D3ED 8FFF
D3EE 8FFB
D3EF 9004
D3F0 8FFC
D3F1 8FF6
D3F2 90D6
D3F3 90E0
D3F4 90D9
D3F5 90DA
D3F6 90E3
D3F7 90DF
D3F8 90E5
D3F9 90D8
D3FA 90DB
D3FB 90D7
D3FC 90DC
D3FD 90E4
D3FE 9150
D440 914E
D441 914F
D442 91D5
D443 91E2
D444 91DA
D445 965C
D446 965F
D447 96BC
D448 98E3
D449 9ADF
D44A 9B2F
D44B 4E7F
D44C 5070
D44D 506A
D44E 5061
D44F 505E
D450 5060
D451 5053
D452 504B
D453 505D
D454 5072
D455 5048
D456 504D
D457 5041
D458 505B
D459 504A
D45A 5062
D45B 5015
D45C 5045
D45D 505F
D45E 5069
D45F 506B
D460 5063
D461 5064
D462 5046
D463 5040
D464 506E
D465 5073
D466 5057
D467 5051
D468 51D0
D469 526B
D46A 526D
D46B 526C
D46C 526E
D46D 52D6
D46E 52D3
D46F 532D
D470 539C
D471 5575
D472 5576
D473 553C
D474 554D
D475 5550
D476 5534
D477 552A
D478 5551
D479 5562
D47A 5536
D47B 5535
D47C 5530
D47D 5552
D47E 5545
D4A1 550C
D4A2 5532
D4A3 5565
D4A4 554E
D4A5 5539
D4A6 5548
D4A7 552D
D4A8 553B
D4A9 5540
D4AA 554B
D4AB 570A
D4AC 5707
D4AD 57FB
D4AE 5814
D4AF 57E2
D4B0 57F6
D4B1 57DC
D4B2 57F4
D4B3 5800
D4B4 57ED
D4B5 57FD
D4B6 5808
D4B7 57F8
D4B8 580B
D4B9 57F3
D4BA 57CF
D4BB 5807
D4BC 57EE
D4BD 57E3
D4BE 57F2
D4BF 57E5
D4C0 57EC
D4C1 57E1
D4C2 580E
D4C3 57FC
D4C4 5810
D4C5 57E7
D4C6 5801
D4C7 580C
D4C8 57F1
D4C9 57E9
D4CA 57F0
D4CB 580D
D4CC 5804
D4CD 595C
D4CE 5A60
D4CF 5A58
D4D0 5A55
D4D1 5A67
D4D2 5A5E
D4D3 5A38
D4D4 5A35
D4D5 5A6D
D4D6 5A50
D4D7 5A5F
D4D8 5A65
D4D9 5A6C
D4DA 5A53
D4DB 5A64
D4DC 5A57
D4DD 5A43
D4DE 5A5D
D4DF 5A52
D4E0 5A44
D4E1 5A5B
D4E2 5A48
D4E3 5A8E
D4E4 5A3E
D4E5 5A4D
D4E6 5A39
D4E7 5A4C
D4E8 5A70
D4E9 5A69
D4EA 5A47
D4EB 5A51
D4EC 5A56
D4ED 5A42
D4EE 5A5C
D4EF 5B72
D4F0 5B6E
D4F1 5BC1
D4F2 5BC0
D4F3 5C59
D4F4 5D1E
D4F5 5D0B
D4F6 5D1D
D4F7 5D1A
D4F8 5D20
D4F9 5D0C
D4FA 5D28
D4FB 5D0D
D4FC 5D26
D4FD 5D25
D4FE 5D0F
D540 5D30
D541 5D12
D542 5D23
D543 5D1F
D544 5D2E
D545 5E3E
D546 5E34
D547 5EB1
D548 5EB4
D549 5EB9
D54A 5EB2
D54B 5EB3
D54C 5F36
D54D 5F38
D54E 5F9B
D54F 5F96
D550 5F9F
D551 608A
D552 6090
D553 6086
D554 60BE
D555 60B0
D556 60BA
D557 60D3
D558 60D4
D559 60CF
D55A 60E4
D55B 60D9
D55C 60DD
D55D 60C8
D55E 60B1
D55F 60DB
D560 60B7
D561 60CA
D562 60BF
D563 60C3
D564 60CD
D565 60C0
D566 6332
D567 6365
D568 638A
D569 6382
D56A 637D
D56B 63BD
D56C 639E
D56D 63AD
D56E 639D
D56F 6397
D570 63AB
D571 638E
D572 636F
D573 6387
D574 6390
D575 636E
D576 63AF
D577 6375
D578 639C
D579 636D
D57A 63AE
D57B 637C
D57C 63A4
D57D 633B
D57E 639F
D5A1 6378
D5A2 6385
D5A3 6381
D5A4 6391
D5A5 638D
D5A6 6370
D5A7 6553
D5A8 65CD
D5A9 6665
D5AA 6661
D5AB 665B
D5AC 6659
D5AD 665C
D5AE 6662
D5AF 6718
D5B0 6879
D5B1 6887
D5B2 6890
D5B3 689C
D5B4 686D
D5B5 686E
D5B6 68AE
D5B7 68AB
D5B8 6956
D5B9 686F
D5BA 68A3
D5BB 68AC
D5BC 68A9
D5BD 6875
D5BE 6874
D5BF 68B2
D5C0 688F
D5C1 6877
D5C2 6892
D5C3 687C
D5C4 686B
D5C5 6872
D5C6 68AA
D5C7 6880
D5C8 6871
D5C9 687E
D5CA 689B
D5CB 6896
D5CC 688B
D5CD 68A0
D5CE 6889
D5CF 68A4
D5D0 6878
D5D1 687B
D5D2 6891
D5D3 688C
D5D4 688A
D5D5 687D
D5D6 6B36
D5D7 6B33
D5D8 6B37
D5D9 6B38
D5DA 6B91
D5DB 6B8F
D5DC 6B8D
D5DD 6B8E
D5DE 6B8C
D5DF 6C2A
D5E0 6DC0
D5E1 6DAB
D5E2 6DB4
D5E3 6DB3
D5E4 6E74
D5E5 6DAC
D5E6 6DE9
D5E7 6DE2
D5E8 6DB7
D5E9 6DF6
D5EA 6DD4
D5EB 6E00
D5EC 6DC8
D5ED 6DE0
D5EE 6DDF
D5EF 6DD6
D5F0 6DBE
D5F1 6DE5
D5F2 6DDC
D5F3 6DDD
D5F4 6DDB
D5F5 6DF4
D5F6 6DCA
D5F7 6DBD
D5F8 6DED
D5F9 6DF0
D5FA 6DBA
D5FB 6DD5
D5FC 6DC2
D5FD 6DCF
D5FE 6DC9
D640 6DD0
D641 6DF2
D642 6DD3
D643 6DFD
D644 6DD7
D645 6DCD
D646 6DE3
D647 6DBB
D648 70FA
D649 710D
D64A 70F7
D64B 7117
D64C 70F4
D64D 710C
D64E 70F0
D64F 7104
D650 70F3
D651 7110
D652 70FC
D653 70FF
D654 7106
D655 7113
D656 7100
D657 70F8
D658 70F6
D659 710B
D65A 7102
D65B 710E
D65C 727E
D65D 727B
D65E 727C
D65F 727F
D660 731D
D661 7317
D662 7307
D663 7311
D664 7318
D665 730A
D666 7308
D667 72FF
D668 730F
D669 731E
D66A 7388
D66B 73F6
D66C 73F8
D66D 73F5
D66E 7404
D66F 7401
D670 73FD
D671 7407
D672 7400
D673 73FA
D674 73FC
D675 73FF
D676 740C
D677 740B
D678 73F4
D679 7408
D67A 7564
D67B 7563
D67C 75CE
D67D 75D2
D67E 75CF
D6A1 75CB
D6A2 75CC
D6A3 75D1
D6A4 75D0
D6A5 768F
D6A6 7689
D6A7 76D3
D6A8 7739
D6A9 772F
D6AA 772D
D6AB 7731
D6AC 7732
D6AD 7734
D6AE 7733
D6AF 773D
D6B0 7725
D6B1 773B
D6B2 7735
D6B3 7848
D6B4 7852
D6B5 7849
D6B6 784D
D6B7 784A
D6B8 784C
D6B9 7826
D6BA 7845
D6BB 7850
D6BC 7964
D6BD 7967
D6BE 7969
D6BF 796A
D6C0 7963
D6C1 796B
D6C2 7961
D6C3 79BB
D6C4 79FA
D6C5 79F8
D6C6 79F6
D6C7 79F7
D6C8 7A8F
D6C9 7A94
D6CA 7A90
D6CB 7B35
D6CC 7B47
D6CD 7B34
D6CE 7B25
D6CF 7B30
D6D0 7B22
D6D1 7B24
D6D2 7B33
D6D3 7B18
D6D4 7B2A
D6D5 7B1D
D6D6 7B31
D6D7 7B2B
D6D8 7B2D
D6D9 7B2F
D6DA 7B32
D6DB 7B38
D6DC 7B1A
D6DD 7B23
D6DE 7C94
D6DF 7C98
D6E0 7C96
D6E1 7CA3
D6E2 7D35
D6E3 7D3D
D6E4 7D38
D6E5 7D36
D6E6 7D3A
D6E7 7D45
D6E8 7D2C
D6E9 7D29
D6EA 7D41
D6EB 7D47
D6EC 7D3E
D6ED 7D3F
D6EE 7D4A
D6EF 7D3B
D6F0 7D28
D6F1 7F63
D6F2 7F95
D6F3 7F9C
D6F4 7F9D
D6F5 7F9B
D6F6 7FCA
D6F7 7FCB
D6F8 7FCD
D6F9 7FD0
D6FA 7FD1
D6FB 7FC7
D6FC 7FCF
D6FD 7FC9
D6FE 801F
D740 801E
D741 801B
D742 8047
D743 8043
D744 8048
D745 8118
D746 8125
D747 8119
D748 811B
D749 812D
D74A 811F
D74B 812C
D74C 811E
D74D 8121
D74E 8115
D74F 8127
D750 811D
D751 8122
D752 8211
D753 8238
D754 8233
D755 823A
D756 8234
D757 8232
D758 8274
D759 8390
D75A 83A3
D75B 83A8
D75C 838D
D75D 837A
D75E 8373
D75F 83A4
D760 8374
D761 838F
D762 8381
D763 8395
D764 8399
D765 8375
D766 8394
D767 83A9
D768 837D
D769 8383
D76A 838C
D76B 839D
D76C 839B
D76D 83AA
D76E 838B
D76F 837E
D770 83A5
D771 83AF
D772 8388
D773 8397
D774 83B0
D775 837F
D776 83A6
D777 8387
D778 83AE
D779 8376
D77A 839A
D77B 8659
D77C 8656
D77D 86BF
D77E 86B7
D7A1 86C2
D7A2 86C1
D7A3 86C5
D7A4 86BA
D7A5 86B0
D7A6 86C8
D7A7 86B9
D7A8 86B3
D7A9 86B8
D7AA 86CC
D7AB 86B4
D7AC 86BB
D7AD 86BC
D7AE 86C3
D7AF 86BD
D7B0 86BE
D7B1 8852
D7B2 8889
D7B3 8895
D7B4 88A8
D7B5 88A2
D7B6 88AA
D7B7 889A
D7B8 8891
D7B9 88A1
D7BA 889F
D7BB 8898
D7BC 88A7
D7BD 8899
D7BE 889B
D7BF 8897
D7C0 88A4
D7C1 88AC
D7C2 888C
D7C3 8893
D7C4 888E
D7C5 8982
D7C6 89D6
D7C7 89D9
D7C8 89D5
D7C9 8A30
D7CA 8A27
D7CB 8A2C
D7CC 8A1E
D7CD 8C39
D7CE 8C3B
D7CF 8C5C
D7D0 8C5D
D7D1 8C7D
D7D2 8CA5
D7D3 8D7D
D7D4 8D7B
D7D5 8D79
D7D6 8DBC
D7D7 8DC2
D7D8 8DB9
D7D9 8DBF
D7DA 8DC1
D7DB 8ED8
D7DC 8EDE
D7DD 8EDD
D7DE 8EDC
D7DF 8ED7
D7E0 8EE0
D7E1 8EE1
D7E2 9024
D7E3 900B
D7E4 9011
D7E5 901C
D7E6 900C
D7E7 9021
D7E8 90EF
D7E9 90EA
D7EA 90F0
D7EB 90F4
D7EC 90F2
D7ED 90F3
D7EE 90D4
D7EF 90EB
D7F0 90EC
D7F1 90E9
D7F2 9156
D7F3 9158
D7F4 915A
D7F5 9153
D7F6 9155
D7F7 91EC
D7F8 91F4
D7F9 91F1
D7FA 91F3
D7FB 91F8
D7FC 91E4
D7FD 91F9
D7FE 91EA
D840 91EB
D841 91F7
D842 91E8
D843 91EE
D844 957A
D845 9586
D846 9588
D847 967C
D848 966D
D849 966B
D84A 9671
D84B 966F
D84C 96BF
D84D 976A
D84E 9804
D84F 98E5
D850 9997
D851 509B
D852 5095
D853 5094
D854 509E
D855 508B
D856 50A3
D857 5083
D858 508C
D859 508E
D85A 509D
D85B 5068
D85C 509C
D85D 5092
D85E 5082
D85F 5087
D860 515F
D861 51D4
D862 5312
D863 5311
D864 53A4
D865 53A7
D866 5591
D867 55A8
D868 55A5
D869 55AD
D86A 5577
D86B 5645
D86C 55A2
D86D 5593
D86E 5588
D86F 558F
D870 55B5
D871 5581
D872 55A3
D873 5592
D874 55A4
D875 557D
D876 558C
D877 55A6
D878 557F
D879 5595
D87A 55A1
D87B 558E
D87C 570C
D87D 5829
D87E 5837
D8A1 5819
D8A2 581E
D8A3 5827
D8A4 5823
D8A5 5828
D8A6 57F5
D8A7 5848
D8A8 5825
D8A9 581C
D8AA 581B
D8AB 5833
D8AC 583F
D8AD 5836
D8AE 582E
D8AF 5839
D8B0 5838
D8B1 582D
D8B2 582C
D8B3 583B
D8B4 5961
D8B5 5AAF
D8B6 5A94
D8B7 5A9F
D8B8 5A7A
D8B9 5AA2
D8BA 5A9E
D8BB 5A78
D8BC 5AA6
D8BD 5A7C
D8BE 5AA5
D8BF 5AAC
D8C0 5A95
D8C1 5AAE
D8C2 5A37
D8C3 5A84
D8C4 5A8A
D8C5 5A97
D8C6 5A83
D8C7 5A8B
D8C8 5AA9
D8C9 5A7B
D8CA 5A7D
D8CB 5A8C
D8CC 5A9C
D8CD 5A8F
D8CE 5A93
D8CF 5A9D
D8D0 5BEA
D8D1 5BCD
D8D2 5BCB
D8D3 5BD4
D8D4 5BD1
D8D5 5BCA
D8D6 5BCE
D8D7 5C0C
D8D8 5C30
D8D9 5D37
D8DA 5D43
D8DB 5D6B
D8DC 5D41
D8DD 5D4B
D8DE 5D3F
D8DF 5D35
D8E0 5D51
D8E1 5D4E
D8E2 5D55
D8E3 5D33
D8E4 5D3A
D8E5 5D52
D8E6 5D3D
D8E7 5D31
D8E8 5D59
D8E9 5D42
D8EA 5D39
D8EB 5D49
D8EC 5D38
D8ED 5D3C
D8EE 5D32
D8EF 5D36
D8F0 5D40
D8F1 5D45
D8F2 5E44
D8F3 5E41
D8F4 5F58
D8F5 5FA6
D8F6 5FA5
D8F7 5FAB
D8F8 60C9
D8F9 60B9
D8FA 60CC
D8FB 60E2
D8FC 60CE
D8FD 60C4
D8FE 6114
D940 60F2
D941 610A
D942 6116
D943 6105
D944 60F5
D945 6113
D946 60F8
D947 60FC
D948 60FE
D949 60C1
D94A 6103
D94B 6118
D94C 611D
D94D 6110
D94E 60FF
D94F 6104
D950 610B
D951 624A
D952 6394
D953 63B1
D954 63B0
D955 63CE
D956 63E5
D957 63E8
D958 63EF
D959 63C3
D95A 649D
D95B 63F3
D95C 63CA
D95D 63E0
D95E 63F6
D95F 63D5
D960 63F2
D961 63F5
D962 6461
D963 63DF
D964 63BE
D965 63DD
D966 63DC
D967 63C4
D968 63D8
D969 63D3
D96A 63C2
D96B 63C7
D96C 63CC
D96D 63CB
D96E 63C8
D96F 63F0
D970 63D7
D971 63D9
D972 6532
D973 6567
D974 656A
D975 6564
D976 655C
D977 6568
D978 6565
D979 658C
D97A 659D
D97B 659E
D97C 65AE
D97D 65D0
D97E 65D2
D9A1 667C
D9A2 666C
D9A3 667B
D9A4 6680
D9A5 6671
D9A6 6679
D9A7 666A
D9A8 6672
D9A9 6701
D9AA 690C
D9AB 68D3
D9AC 6904
D9AD 68DC
D9AE 692A
D9AF 68EC
D9B0 68EA
D9B1 68F1
D9B2 690F
D9B3 68D6
D9B4 68F7
D9B5 68EB
D9B6 68E4
D9B7 68F6
D9B8 6913
D9B9 6910
D9BA 68F3
D9BB 68E1
D9BC 6907
D9BD 68CC
D9BE 6908
D9BF 6970
D9C0 68B4
D9C1 6911
D9C2 68EF
D9C3 68C6
D9C4 6914
D9C5 68F8
D9C6 68D0
D9C7 68FD
D9C8 68FC
D9C9 68E8
D9CA 690B
D9CB 690A
D9CC 6917
D9CD 68CE
D9CE 68C8
D9CF 68DD
D9D0 68DE
D9D1 68E6
D9D2 68F4
D9D3 68D1
D9D4 6906
D9D5 68D4
D9D6 68E9
D9D7 6915
D9D8 6925
D9D9 68C7
D9DA 6B39
D9DB 6B3B
D9DC 6B3F
D9DD 6B3C
D9DE 6B94
D9DF 6B97
D9E0 6B99
D9E1 6B95
D9E2 6BBD
D9E3 6BF0
D9E4 6BF2
D9E5 6BF3
D9E6 6C30
D9E7 6DFC
D9E8 6E46
D9E9 6E47
D9EA 6E1F
D9EB 6E49
D9EC 6E88
D9ED 6E3C
D9EE 6E3D
D9EF 6E45
D9F0 6E62
D9F1 6E2B
D9F2 6E3F
D9F3 6E41
D9F4 6E5D
D9F5 6E73
D9F6 6E1C
D9F7 6E33
D9F8 6E4B
D9F9 6E40
D9FA 6E51
D9FB 6E3B
D9FC 6E03
D9FD 6E2E
D9FE 6E5E
DA40 6E68
DA41 6E5C
DA42 6E61
DA43 6E31
DA44 6E28
DA45 6E60
DA46 6E71
DA47 6E6B
DA48 6E39
DA49 6E22
DA4A 6E30
DA4B 6E53
DA4C 6E65
DA4D 6E27
DA4E 6E78
DA4F 6E64
DA50 6E77
DA51 6E55
DA52 6E79
DA53 6E52
DA54 6E66
DA55 6E35
DA56 6E36
DA57 6E5A
DA58 7120
DA59 711E
DA5A 712F
DA5B 70FB
DA5C 712E
DA5D 7131
DA5E 7123
DA5F 7125
DA60 7122
DA61 7132
DA62 711F
DA63 7128
DA64 713A
DA65 711B
DA66 724B
DA67 725A
DA68 7288
DA69 7289
DA6A 7286
DA6B 7285
DA6C 728B
DA6D 7312
DA6E 730B
DA6F 7330
DA70 7322
DA71 7331
DA72 7333
DA73 7327
DA74 7332
DA75 732D
DA76 7326
DA77 7323
DA78 7335
DA79 730C
DA7A 742E
DA7B 742C
DA7C 7430
DA7D 742B
DA7E 7416
DAA1 741A
DAA2 7421
DAA3 742D
DAA4 7431
DAA5 7424
DAA6 7423
DAA7 741D
DAA8 7429
DAA9 7420
DAAA 7432
DAAB 74FB
DAAC 752F
DAAD 756F
DAAE 756C
DAAF 75E7
DAB0 75DA
DAB1 75E1
DAB2 75E6
DAB3 75DD
DAB4 75DF
DAB5 75E4
DAB6 75D7
DAB7 7695
DAB8 7692
DAB9 76DA
DABA 7746
DABB 7747
DABC 7744
DABD 774D
DABE 7745
DABF 774A
DAC0 774E
DAC1 774B
DAC2 774C
DAC3 77DE
DAC4 77EC
DAC5 7860
DAC6 7864
DAC7 7865
DAC8 785C
DAC9 786D
DACA 7871
DACB 786A
DACC 786E
DACD 7870
DACE 7869
DACF 7868
DAD0 785E
DAD1 7862
DAD2 7974
DAD3 7973
DAD4 7972
DAD5 7970
DAD6 7A02
DAD7 7A0A
DAD8 7A03
DAD9 7A0C
DADA 7A04
DADB 7A99
DADC 7AE6
DADD 7AE4
DADE 7B4A
DADF 7B3B
DAE0 7B44
DAE1 7B48
DAE2 7B4C
DAE3 7B4E
DAE4 7B40
DAE5 7B58
DAE6 7B45
DAE7 7CA2
DAE8 7C9E
DAE9 7CA8
DAEA 7CA1
DAEB 7D58
DAEC 7D6F
DAED 7D63
DAEE 7D53
DAEF 7D56
DAF0 7D67
DAF1 7D6A
DAF2 7D4F
DAF3 7D6D
DAF4 7D5C
DAF5 7D6B
DAF6 7D52
DAF7 7D54
DAF8 7D69
DAF9 7D51
DAFA 7D5F
DAFB 7D4E
DAFC 7F3E
DAFD 7F3F
DAFE 7F65
DB40 7F66
DB41 7FA2
DB42 7FA0
DB43 7FA1
DB44 7FD7
DB45 8051
DB46 804F
DB47 8050
DB48 80FE
DB49 80D4
DB4A 8143
DB4B 814A
DB4C 8152
DB4D 814F
DB4E 8147
DB4F 813D
DB50 814D
DB51 813A
DB52 81E6
DB53 81EE
DB54 81F7
DB55 81F8
DB56 81F9
DB57 8204
DB58 823C
DB59 823D
DB5A 823F
DB5B 8275
DB5C 833B
DB5D 83CF
DB5E 83F9
DB5F 8423
DB60 83C0
DB61 83E8
DB62 8412
DB63 83E7
DB64 83E4
DB65 83FC
DB66 83F6
DB67 8410
DB68 83C6
DB69 83C8
DB6A 83EB
DB6B 83E3
DB6C 83BF
DB6D 8401
DB6E 83DD
DB6F 83E5
DB70 83D8
DB71 83FF
DB72 83E1
DB73 83CB
DB74 83CE
DB75 83D6
DB76 83F5
DB77 83C9
DB78 8409
DB79 840F
DB7A 83DE
DB7B 8411
DB7C 8406
DB7D 83C2
DB7E 83F3
DBA1 83D5
DBA2 83FA
DBA3 83C7
DBA4 83D1
DBA5 83EA
DBA6 8413
DBA7 83C3
DBA8 83EC
DBA9 83EE
DBAA 83C4
DBAB 83FB
DBAC 83D7
DBAD 83E2
DBAE 841B
DBAF 83DB
DBB0 83FE
DBB1 86D8
DBB2 86E2
DBB3 86E6
DBB4 86D3
DBB5 86E3
DBB6 86DA
DBB7 86EA
DBB8 86DD
DBB9 86EB
DBBA 86DC
DBBB 86EC
DBBC 86E9
DBBD 86D7
DBBE 86E8
DBBF 86D1
DBC0 8848
DBC1 8856
DBC2 8855
DBC3 88BA
DBC4 88D7
DBC5 88B9
DBC6 88B8
DBC7 88C0
DBC8 88BE
DBC9 88B6
DBCA 88BC
DBCB 88B7
DBCC 88BD
DBCD 88B2
DBCE 8901
DBCF 88C9
DBD0 8995
DBD1 8998
DBD2 8997
DBD3 89DD
DBD4 89DA
DBD5 89DB
DBD6 8A4E
DBD7 8A4D
DBD8 8A39
DBD9 8A59
DBDA 8A40
DBDB 8A57
DBDC 8A58
DBDD 8A44
DBDE 8A45
DBDF 8A52
DBE0 8A48
DBE1 8A51
DBE2 8A4A
DBE3 8A4C
DBE4 8A4F
DBE5 8C5F
DBE6 8C81
DBE7 8C80
DBE8 8CBA
DBE9 8CBE
DBEA 8CB0
DBEB 8CB9
DBEC 8CB5
DBED 8D84
DBEE 8D80
DBEF 8D89
DBF0 8DD8
DBF1 8DD3
DBF2 8DCD
DBF3 8DC7
DBF4 8DD6
DBF5 8DDC
DBF6 8DCF
DBF7 8DD5
DBF8 8DD9
DBF9 8DC8
DBFA 8DD7
DBFB 8DC5
DBFC 8EEF
DBFD 8EF7
DBFE 8EFA
DC40 8EF9
DC41 8EE6
DC42 8EEE
DC43 8EE5
DC44 8EF5
DC45 8EE7
DC46 8EE8
DC47 8EF6
DC48 8EEB
DC49 8EF1
DC4A 8EEC
DC4B 8EF4
DC4C 8EE9
DC4D 902D
DC4E 9034
DC4F 902F
DC50 9106
DC51 912C
DC52 9104
DC53 90FF
DC54 90FC
DC55 9108
DC56 90F9
DC57 90FB
DC58 9101
DC59 9100
DC5A 9107
DC5B 9105
DC5C 9103
DC5D 9161
DC5E 9164
DC5F 915F
DC60 9162
DC61 9160
DC62 9201
DC63 920A
DC64 9225
DC65 9203
DC66 921A
DC67 9226
DC68 920F
DC69 920C
DC6A 9200
DC6B 9212
DC6C 91FF
DC6D 91FD
DC6E 9206
DC6F 9204
DC70 9227
DC71 9202
DC72 921C
DC73 9224
DC74 9219
DC75 9217
DC76 9205
DC77 9216
DC78 957B
DC79 958D
DC7A 958C
DC7B 9590
DC7C 9687
DC7D 967E
DC7E 9688
DCA1 9689
DCA2 9683
DCA3 9680
DCA4 96C2
DCA5 96C8
DCA6 96C3
DCA7 96F1
DCA8 96F0
DCA9 976C
DCAA 9770
DCAB 976E
DCAC 9807
DCAD 98A9
DCAE 98EB
DCAF 9CE6
DCB0 9EF9
DCB1 4E83
DCB2 4E84
DCB3 4EB6
DCB4 50BD
DCB5 50BF
DCB6 50C6
DCB7 50AE
DCB8 50C4
DCB9 50CA
DCBA 50B4
DCBB 50C8
DCBC 50C2
DCBD 50B0
DCBE 50C1
DCBF 50BA
DCC0 50B1
DCC1 50CB
DCC2 50C9
DCC3 50B6
DCC4 50B8
DCC5 51D7
DCC6 527A
DCC7 5278
DCC8 527B
DCC9 527C
DCCA 55C3
DCCB 55DB
DCCC 55CC
DCCD 55D0
DCCE 55CB
DCCF 55CA
DCD0 55DD
DCD1 55C0
DCD2 55D4
DCD3 55C4
DCD4 55E9
DCD5 55BF
DCD6 55D2
DCD7 558D
DCD8 55CF
DCD9 55D5
DCDA 55E2
DCDB 55D6
DCDC 55C8
DCDD 55F2
DCDE 55CD
DCDF 55D9
DCE0 55C2
DCE1 5714
DCE2 5853
DCE3 5868
DCE4 5864
DCE5 584F
DCE6 584D
DCE7 5849
DCE8 586F
DCE9 5855
DCEA 584E
DCEB 585D
DCEC 5859
DCED 5865
DCEE 585B
DCEF 583D
DCF0 5863
DCF1 5871
DCF2 58FC
DCF3 5AC7
DCF4 5AC4
DCF5 5ACB
DCF6 5ABA
DCF7 5AB8
DCF8 5AB1
DCF9 5AB5
DCFA 5AB0
DCFB 5ABF
DCFC 5AC8
DCFD 5ABB
DCFE 5AC6
DD40 5AB7
DD41 5AC0
DD42 5ACA
DD43 5AB4
DD44 5AB6
DD45 5ACD
DD46 5AB9
DD47 5A90
DD48 5BD6
DD49 5BD8
DD4A 5BD9
DD4B 5C1F
DD4C 5C33
DD4D 5D71
DD4E 5D63
DD4F 5D4A
DD50 5D65
DD51 5D72
DD52 5D6C
DD53 5D5E
DD54 5D68
DD55 5D67
DD56 5D62
DD57 5DF0
DD58 5E4F
DD59 5E4E
DD5A 5E4A
DD5B 5E4D
DD5C 5E4B
DD5D 5EC5
DD5E 5ECC
DD5F 5EC6
DD60 5ECB
DD61 5EC7
DD62 5F40
DD63 5FAF
DD64 5FAD
DD65 60F7
DD66 6149
DD67 614A
DD68 612B
DD69 6145
DD6A 6136
DD6B 6132
DD6C 612E
DD6D 6146
DD6E 612F
DD6F 614F
DD70 6129
DD71 6140
DD72 6220
DD73 9168
DD74 6223
DD75 6225
DD76 6224
DD77 63C5
DD78 63F1
DD79 63EB
DD7A 6410
DD7B 6412
DD7C 6409
DD7D 6420
DD7E 6424
DDA1 6433
DDA2 6443
DDA3 641F
DDA4 6415
DDA5 6418
DDA6 6439
DDA7 6437
DDA8 6422
DDA9 6423
DDAA 640C
DDAB 6426
DDAC 6430
DDAD 6428
DDAE 6441
DDAF 6435
DDB0 642F
DDB1 640A
DDB2 641A
DDB3 6440
DDB4 6425
DDB5 6427
DDB6 640B
DDB7 63E7
DDB8 641B
DDB9 642E
DDBA 6421
DDBB 640E
DDBC 656F
DDBD 6592
DDBE 65D3
DDBF 6686
DDC0 668C
DDC1 6695
DDC2 6690
DDC3 668B
DDC4 668A
DDC5 6699
DDC6 6694
DDC7 6678
DDC8 6720
DDC9 6966
DDCA 695F
DDCB 6938
DDCC 694E
DDCD 6962
DDCE 6971
DDCF 693F
DDD0 6945
DDD1 696A
DDD2 6939
DDD3 6942
DDD4 6957
DDD5 6959
DDD6 697A
DDD7 6948
DDD8 6949
DDD9 6935
DDDA 696C
DDDB 6933
DDDC 693D
DDDD 6965
DDDE 68F0
DDDF 6978
DDE0 6934
DDE1 6969
DDE2 6940
DDE3 696F
DDE4 6944
DDE5 6976
DDE6 6958
DDE7 6941
DDE8 6974
DDE9 694C
DDEA 693B
DDEB 694B
DDEC 6937
DDED 695C
DDEE 694F
DDEF 6951
DDF0 6932
DDF1 6952
DDF2 692F
DDF3 697B
DDF4 693C
DDF5 6B46
DDF6 6B45
DDF7 6B43
DDF8 6B42
DDF9 6B48
DDFA 6B41
DDFB 6B9B
DDFC FA0D
DDFD 6BFB
DDFE 6BFC
DE40 6BF9
DE41 6BF7
DE42 6BF8
DE43 6E9B
DE44 6ED6
DE45 6EC8
DE46 6E8F
DE47 6EC0
DE48 6E9F
DE49 6E93
DE4A 6E94
DE4B 6EA0
DE4C 6EB1
DE4D 6EB9
DE4E 6EC6
DE4F 6ED2
DE50 6EBD
DE51 6EC1
DE52 6E9E
DE53 6EC9
DE54 6EB7
DE55 6EB0
DE56 6ECD
DE57 6EA6
DE58 6ECF
DE59 6EB2
DE5A 6EBE
DE5B 6EC3
DE5C 6EDC
DE5D 6ED8
DE5E 6E99
DE5F 6E92
DE60 6E8E
DE61 6E8D
DE62 6EA4
DE63 6EA1
DE64 6EBF
DE65 6EB3
DE66 6ED0
DE67 6ECA
DE68 6E97
DE69 6EAE
DE6A 6EA3
DE6B 7147
DE6C 7154
DE6D 7152
DE6E 7163
DE6F 7160
DE70 7141
DE71 715D
DE72 7162
DE73 7172
DE74 7178
DE75 716A
DE76 7161
DE77 7142
DE78 7158
DE79 7143
DE7A 714B
DE7B 7170
DE7C 715F
DE7D 7150
DE7E 7153
DEA1 7144
DEA2 714D
DEA3 715A
DEA4 724F
DEA5 728D
DEA6 728C
DEA7 7291
DEA8 7290
DEA9 728E
DEAA 733C
DEAB 7342
DEAC 733B
DEAD 733A
DEAE 7340
DEAF 734A
DEB0 7349
DEB1 7444
DEB2 744A
DEB3 744B
DEB4 7452
DEB5 7451
DEB6 7457
DEB7 7440
DEB8 744F
DEB9 7450
DEBA 744E
DEBB 7442
DEBC 7446
DEBD 744D
DEBE 7454
DEBF 74E1
DEC0 74FF
DEC1 74FE
DEC2 74FD
DEC3 751D
DEC4 7579
DEC5 7577
DEC6 6983
DEC7 75EF
DEC8 760F
DEC9 7603
DECA 75F7
DECB 75FE
DECC 75FC
DECD 75F9
DECE 75F8
DECF 7610
DED0 75FB
DED1 75F6
DED2 75ED
DED3 75F5
DED4 75FD
DED5 7699
DED6 76B5
DED7 76DD
DED8 7755
DED9 775F
DEDA 7760
DEDB 7752
DEDC 7756
DEDD 775A
DEDE 7769
DEDF 7767
DEE0 7754
DEE1 7759
DEE2 776D
DEE3 77E0
DEE4 7887
DEE5 789A
DEE6 7894
DEE7 788F
DEE8 7884
DEE9 7895
DEEA 7885
DEEB 7886
DEEC 78A1
DEED 7883
DEEE 7879
DEEF 7899
DEF0 7880
DEF1 7896
DEF2 787B
DEF3 797C
DEF4 7982
DEF5 797D
DEF6 7979
DEF7 7A11
DEF8 7A18
DEF9 7A19
DEFA 7A12
DEFB 7A17
DEFC 7A15
DEFD 7A22
DEFE 7A13
DF40 7A1B
DF41 7A10
DF42 7AA3
DF43 7AA2
DF44 7A9E
DF45 7AEB
DF46 7B66
DF47 7B64
DF48 7B6D
DF49 7B74
DF4A 7B69
DF4B 7B72
DF4C 7B65
DF4D 7B73
DF4E 7B71
DF4F 7B70
DF50 7B61
DF51 7B78
DF52 7B76
DF53 7B63
DF54 7CB2
DF55 7CB4
DF56 7CAF
DF57 7D88
DF58 7D86
DF59 7D80
DF5A 7D8D
DF5B 7D7F
DF5C 7D85
DF5D 7D7A
DF5E 7D8E
DF5F 7D7B
DF60 7D83
DF61 7D7C
DF62 7D8C
DF63 7D94
DF64 7D84
DF65 7D7D
DF66 7D92
DF67 7F6D
DF68 7F6B
DF69 7F67
DF6A 7F68
DF6B 7F6C
DF6C 7FA6
DF6D 7FA5
DF6E 7FA7
DF6F 7FDB
DF70 7FDC
DF71 8021
DF72 8164
DF73 8160
DF74 8177
DF75 815C
DF76 8169
DF77 815B
DF78 8162
DF79 8172
DF7A 6721
DF7B 815E
DF7C 8176
DF7D 8167
DF7E 816F
DFA1 8144
DFA2 8161
DFA3 821D
DFA4 8249
DFA5 8244
DFA6 8240
DFA7 8242
DFA8 8245
DFA9 84F1
DFAA 843F
DFAB 8456
DFAC 8476
DFAD 8479
DFAE 848F
DFAF 848D
DFB0 8465
DFB1 8451
DFB2 8440
DFB3 8486
DFB4 8467
DFB5 8430
DFB6 844D
DFB7 847D
DFB8 845A
DFB9 8459
DFBA 8474
DFBB 8473
DFBC 845D
DFBD 8507
DFBE 845E
DFBF 8437
DFC0 843A
DFC1 8434
DFC2 847A
DFC3 8443
DFC4 8478
DFC5 8432
DFC6 8445
DFC7 8429
DFC8 83D9
DFC9 844B
DFCA 842F
DFCB 8442
DFCC 842D
DFCD 845F
DFCE 8470
DFCF 8439
DFD0 844E
DFD1 844C
DFD2 8452
DFD3 846F
DFD4 84C5
DFD5 848E
DFD6 843B
DFD7 8447
DFD8 8436
DFD9 8433
DFDA 8468
DFDB 847E
DFDC 8444
DFDD 842B
DFDE 8460
DFDF 8454
DFE0 846E
DFE1 8450
DFE2 870B
DFE3 8704
DFE4 86F7
DFE5 870C
DFE6 86FA
DFE7 86D6
DFE8 86F5
DFE9 874D
DFEA 86F8
DFEB 870E
DFEC 8709
DFED 8701
DFEE 86F6
DFEF 870D
DFF0 8705
DFF1 88D6
DFF2 88CB
DFF3 88CD
DFF4 88CE
DFF5 88DE
DFF6 88DB
DFF7 88DA
DFF8 88CC
DFF9 88D0
DFFA 8985
DFFB 899B
DFFC 89DF
DFFD 89E5
DFFE 89E4
E040 89E1
E041 89E0
E042 89E2
E043 89DC
E044 89E6
E045 8A76
E046 8A86
E047 8A7F
E048 8A61
E049 8A3F
E04A 8A77
E04B 8A82
E04C 8A84
E04D 8A75
E04E 8A83
E04F 8A81
E050 8A74
E051 8A7A
E052 8C3C
E053 8C4B
E054 8C4A
E055 8C65
E056 8C64
E057 8C66
E058 8C86
E059 8C84
E05A 8C85
E05B 8CCC
E05C 8D68
E05D 8D69
E05E 8D91
E05F 8D8C
E060 8D8E
E061 8D8F
E062 8D8D
E063 8D93
E064 8D94
E065 8D90
E066 8D92
E067 8DF0
E068 8DE0
E069 8DEC
E06A 8DF1
E06B 8DEE
E06C 8DD0
E06D 8DE9
E06E 8DE3
E06F 8DE2
E070 8DE7
E071 8DF2
E072 8DEB
E073 8DF4
E074 8F06
E075 8EFF
E076 8F01
E077 8F00
E078 8F05
E079 8F07
E07A 8F08
E07B 8F02
E07C 8F0B
E07D 9052
E07E 903F
E0A1 9044
E0A2 9049
E0A3 903D
E0A4 9110
E0A5 910D
E0A6 910F
E0A7 9111
E0A8 9116
E0A9 9114
E0AA 910B
E0AB 910E
E0AC 916E
E0AD 916F
E0AE 9248
E0AF 9252
E0B0 9230
E0B1 923A
E0B2 9266
E0B3 9233
E0B4 9265
E0B5 925E
E0B6 9283
E0B7 922E
E0B8 924A
E0B9 9246
E0BA 926D
E0BB 926C
E0BC 924F
E0BD 9260
E0BE 9267
E0BF 926F
E0C0 9236
E0C1 9261
E0C2 9270
E0C3 9231
E0C4 9254
E0C5 9263
E0C6 9250
E0C7 9272
E0C8 924E
E0C9 9253
E0CA 924C
E0CB 9256
E0CC 9232
E0CD 959F
E0CE 959C
E0CF 959E
E0D0 959B
E0D1 9692
E0D2 9693
E0D3 9691
E0D4 9697
E0D5 96CE
E0D6 96FA
E0D7 96FD
E0D8 96F8
E0D9 96F5
E0DA 9773
E0DB 9777
E0DC 9778
E0DD 9772
E0DE 980F
E0DF 980D
E0E0 980E
E0E1 98AC
E0E2 98F6
E0E3 98F9
E0E4 99AF
E0E5 99B2
E0E6 99B0
E0E7 99B5
E0E8 9AAD
E0E9 9AAB
E0EA 9B5B
E0EB 9CEA
E0EC 9CED
E0ED 9CE7
E0EE 9E80
E0EF 9EFD
E0F0 50E6
E0F1 50D4
E0F2 50D7
E0F3 50E8
E0F4 50F3
E0F5 50DB
E0F6 50EA
E0F7 50DD
E0F8 50E4
E0F9 50D3
E0FA 50EC
E0FB 50F0
E0FC 50EF
E0FD 50E3
E0FE 50E0
E140 51D8
E141 5280
E142 5281
E143 52E9
E144 52EB
E145 5330
E146 53AC
E147 5627
E148 5615
E149 560C
E14A 5612
E14B 55FC
E14C 560F
E14D 561C
E14E 5601
E14F 5613
E150 5602
E151 55FA
E152 561D
E153 5604
E154 55FF
E155 55F9
E156 5889
E157 587C
E158 5890
E159 5898
E15A 5886
E15B 5881
E15C 587F
E15D 5874
E15E 588B
E15F 587A
E160 5887
E161 5891
E162 588E
E163 5876
E164 5882
E165 5888
E166 587B
E167 5894
E168 588F
E169 58FE
E16A 596B
E16B 5ADC
E16C 5AEE
E16D 5AE5
E16E 5AD5
E16F 5AEA
E170 5ADA
E171 5AED
E172 5AEB
E173 5AF3
E174 5AE2
E175 5AE0
E176 5ADB
E177 5AEC
E178 5ADE
E179 5ADD
E17A 5AD9
E17B 5AE8
E17C 5ADF
E17D 5B77
E17E 5BE0
E1A1 5BE3
E1A2 5C63
E1A3 5D82
E1A4 5D80
E1A5 5D7D
E1A6 5D86
E1A7 5D7A
E1A8 5D81
E1A9 5D77
E1AA 5D8A
E1AB 5D89
E1AC 5D88
E1AD 5D7E
E1AE 5D7C
E1AF 5D8D
E1B0 5D79
E1B1 5D7F
E1B2 5E58
E1B3 5E59
E1B4 5E53
E1B5 5ED8
E1B6 5ED1
E1B7 5ED7
E1B8 5ECE
E1B9 5EDC
E1BA 5ED5
E1BB 5ED9
E1BC 5ED2
E1BD 5ED4
E1BE 5F44
E1BF 5F43
E1C0 5F6F
E1C1 5FB6
E1C2 612C
E1C3 6128
E1C4 6141
E1C5 615E
E1C6 6171
E1C7 6173
E1C8 6152
E1C9 6153
E1CA 6172
E1CB 616C
E1CC 6180
E1CD 6174
E1CE 6154
E1CF 617A
E1D0 615B
E1D1 6165
E1D2 613B
E1D3 616A
E1D4 6161
E1D5 6156
E1D6 6229
E1D7 6227
E1D8 622B
E1D9 642B
E1DA 644D
E1DB 645B
E1DC 645D
E1DD 6474
E1DE 6476
E1DF 6472
E1E0 6473
E1E1 647D
E1E2 6475
E1E3 6466
E1E4 64A6
E1E5 644E
E1E6 6482
E1E7 645E
E1E8 645C
E1E9 644B
E1EA 6453
E1EB 6460
E1EC 6450
E1ED 647F
E1EE 643F
E1EF 646C
E1F0 646B
E1F1 6459
E1F2 6465
E1F3 6477
E1F4 6573
E1F5 65A0
E1F6 66A1
E1F7 66A0
E1F8 669F
E1F9 6705
E1FA 6704
E1FB 6722
E1FC 69B1
E1FD 69B6
E1FE 69C9
E240 69A0
E241 69CE
E242 6996
E243 69B0
E244 69AC
E245 69BC
E246 6991
E247 6999
E248 698E
E249 69A7
E24A 698D
E24B 69A9
E24C 69BE
E24D 69AF
E24E 69BF
E24F 69C4
E250 69BD
E251 69A4
E252 69D4
E253 69B9
E254 69CA
E255 699A
E256 69CF
E257 69B3
E258 6993
E259 69AA
E25A 69A1
E25B 699E
E25C 69D9
E25D 6997
E25E 6990
E25F 69C2
E260 69B5
E261 69A5
E262 69C6
E263 6B4A
E264 6B4D
E265 6B4B
E266 6B9E
E267 6B9F
E268 6BA0
E269 6BC3
E26A 6BC4
E26B 6BFE
E26C 6ECE
E26D 6EF5
E26E 6EF1
E26F 6F03
E270 6F25
E271 6EF8
E272 6F37
E273 6EFB
E274 6F2E
E275 6F09
E276 6F4E
E277 6F19
E278 6F1A
E279 6F27
E27A 6F18
E27B 6F3B
E27C 6F12
E27D 6EED
E27E 6F0A
E2A1 6F36
E2A2 6F73
E2A3 6EF9
E2A4 6EEE
E2A5 6F2D
E2A6 6F40
E2A7 6F30
E2A8 6F3C
E2A9 6F35
E2AA 6EEB
E2AB 6F07
E2AC 6F0E
E2AD 6F43
E2AE 6F05
E2AF 6EFD
E2B0 6EF6
E2B1 6F39
E2B2 6F1C
E2B3 6EFC
E2B4 6F3A
E2B5 6F1F
E2B6 6F0D
E2B7 6F1E
E2B8 6F08
E2B9 6F21
E2BA 7187
E2BB 7190
E2BC 7189
E2BD 7180
E2BE 7185
E2BF 7182
E2C0 718F
E2C1 717B
E2C2 7186
E2C3 7181
E2C4 7197
E2C5 7244
E2C6 7253
E2C7 7297
E2C8 7295
E2C9 7293
E2CA 7343
E2CB 734D
E2CC 7351
E2CD 734C
E2CE 7462
E2CF 7473
E2D0 7471
E2D1 7475
E2D2 7472
E2D3 7467
E2D4 746E
E2D5 7500
E2D6 7502
E2D7 7503
E2D8 757D
E2D9 7590
E2DA 7616
E2DB 7608
E2DC 760C
E2DD 7615
E2DE 7611
E2DF 760A
E2E0 7614
E2E1 76B8
E2E2 7781
E2E3 777C
E2E4 7785
E2E5 7782
E2E6 776E
E2E7 7780
E2E8 776F
E2E9 777E
E2EA 7783
E2EB 78B2
E2EC 78AA
E2ED 78B4
E2EE 78AD
E2EF 78A8
E2F0 787E
E2F1 78AB
E2F2 789E
E2F3 78A5
E2F4 78A0
E2F5 78AC
E2F6 78A2
E2F7 78A4
E2F8 7998
E2F9 798A
E2FA 798B
E2FB 7996
E2FC 7995
E2FD 7994
E2FE 7993
E340 7997
E341 7988
E342 7992
E343 7990
E344 7A2B
E345 7A4A
E346 7A30
E347 7A2F
E348 7A28
E349 7A26
E34A 7AA8
E34B 7AAB
E34C 7AAC
E34D 7AEE
E34E 7B88
E34F 7B9C
E350 7B8A
E351 7B91
E352 7B90
E353 7B96
E354 7B8D
E355 7B8C
E356 7B9B
E357 7B8E
E358 7B85
E359 7B98
E35A 5284
E35B 7B99
E35C 7BA4
E35D 7B82
E35E 7CBB
E35F 7CBF
E360 7CBC
E361 7CBA
E362 7DA7
E363 7DB7
E364 7DC2
E365 7DA3
E366 7DAA
E367 7DC1
E368 7DC0
E369 7DC5
E36A 7D9D
E36B 7DCE
E36C 7DC4
E36D 7DC6
E36E 7DCB
E36F 7DCC
E370 7DAF
E371 7DB9
E372 7D96
E373 7DBC
E374 7D9F
E375 7DA6
E376 7DAE
E377 7DA9
E378 7DA1
E379 7DC9
E37A 7F73
E37B 7FE2
E37C 7FE3
E37D 7FE5
E37E 7FDE
E3A1 8024
E3A2 805D
E3A3 805C
E3A4 8189
E3A5 8186
E3A6 8183
E3A7 8187
E3A8 818D
E3A9 818C
E3AA 818B
E3AB 8215
E3AC 8497
E3AD 84A4
E3AE 84A1
E3AF 849F
E3B0 84BA
E3B1 84CE
E3B2 84C2
E3B3 84AC
E3B4 84AE
E3B5 84AB
E3B6 84B9
E3B7 84B4
E3B8 84C1
E3B9 84CD
E3BA 84AA
E3BB 849A
E3BC 84B1
E3BD 84D0
E3BE 849D
E3BF 84A7
E3C0 84BB
E3C1 84A2
E3C2 8494
E3C3 84C7
E3C4 84CC
E3C5 849B
E3C6 84A9
E3C7 84AF
E3C8 84A8
E3C9 84D6
E3CA 8498
E3CB 84B6
E3CC 84CF
E3CD 84A0
E3CE 84D7
E3CF 84D4
E3D0 84D2
E3D1 84DB
E3D2 84B0
E3D3 8491
E3D4 8661
E3D5 8733
E3D6 8723
E3D7 8728
E3D8 876B
E3D9 8740
E3DA 872E
E3DB 871E
E3DC 8721
E3DD 8719
E3DE 871B
E3DF 8743
E3E0 872C
E3E1 8741
E3E2 873E
E3E3 8746
E3E4 8720
E3E5 8732
E3E6 872A
E3E7 872D
E3E8 873C
E3E9 8712
E3EA 873A
E3EB 8731
E3EC 8735
E3ED 8742
E3EE 8726
E3EF 8727
E3F0 8738
E3F1 8724
E3F2 871A
E3F3 8730
E3F4 8711
E3F5 88F7
E3F6 88E7
E3F7 88F1
E3F8 88F2
E3F9 88FA
E3FA 88FE
E3FB 88EE
E3FC 88FC
E3FD 88F6
E3FE 88FB
E440 88F0
E441 88EC
E442 88EB
E443 899D
E444 89A1
E445 899F
E446 899E
E447 89E9
E448 89EB
E449 89E8
E44A 8AAB
E44B 8A99
E44C 8A8B
E44D 8A92
E44E 8A8F
E44F 8A96
E450 8C3D
E451 8C68
E452 8C69
E453 8CD5
E454 8CCF
E455 8CD7
E456 8D96
E457 8E09
E458 8E02
E459 8DFF
E45A 8E0D
E45B 8DFD
E45C 8E0A
E45D 8E03
E45E 8E07
E45F 8E06
E460 8E05
E461 8DFE
E462 8E00
E463 8E04
E464 8F10
E465 8F11
E466 8F0E
E467 8F0D
E468 9123
E469 911C
E46A 9120
E46B 9122
E46C 911F
E46D 911D
E46E 911A
E46F 9124
E470 9121
E471 911B
E472 917A
E473 9172
E474 9179
E475 9173
E476 92A5
E477 92A4
E478 9276
E479 929B
E47A 927A
E47B 92A0
E47C 9294
E47D 92AA
E47E 928D
E4A1 92A6
E4A2 929A
E4A3 92AB
E4A4 9279
E4A5 9297
E4A6 927F
E4A7 92A3
E4A8 92EE
E4A9 928E
E4AA 9282
E4AB 9295
E4AC 92A2
E4AD 927D
E4AE 9288
E4AF 92A1
E4B0 928A
E4B1 9286
E4B2 928C
E4B3 9299
E4B4 92A7
E4B5 927E
E4B6 9287
E4B7 92A9
E4B8 929D
E4B9 928B
E4BA 922D
E4BB 969E
E4BC 96A1
E4BD 96FF
E4BE 9758
E4BF 977D
E4C0 977A
E4C1 977E
E4C2 9783
E4C3 9780
E4C4 9782
E4C5 977B
E4C6 9784
E4C7 9781
E4C8 977F
E4C9 97CE
E4CA 97CD
E4CB 9816
E4CC 98AD
E4CD 98AE
E4CE 9902
E4CF 9900
E4D0 9907
E4D1 999D
E4D2 999C
E4D3 99C3
E4D4 99B9
E4D5 99BB
E4D6 99BA
E4D7 99C2
E4D8 99BD
E4D9 99C7
E4DA 9AB1
E4DB 9AE3
E4DC 9AE7
E4DD 9B3E
E4DE 9B3F
E4DF 9B60
E4E0 9B61
E4E1 9B5F
E4E2 9CF1
E4E3 9CF2
E4E4 9CF5
E4E5 9EA7
E4E6 50FF
E4E7 5103
E4E8 5130
E4E9 50F8
E4EA 5106
E4EB 5107
E4EC 50F6
E4ED 50FE
E4EE 510B
E4EF 510C
E4F0 50FD
E4F1 510A
E4F2 528B
E4F3 528C
E4F4 52F1
E4F5 52EF
E4F6 5648
E4F7 5642
E4F8 564C
E4F9 5635
E4FA 5641
E4FB 564A
E4FC 5649
E4FD 5646
E4FE 5658
E540 565A
E541 5640
E542 5633
E543 563D
E544 562C
E545 563E
E546 5638
E547 562A
E548 563A
E549 571A
E54A 58AB
E54B 589D
E54C 58B1
E54D 58A0
E54E 58A3
E54F 58AF
E550 58AC
E551 58A5
E552 58A1
E553 58FF
E554 5AFF
E555 5AF4
E556 5AFD
E557 5AF7
E558 5AF6
E559 5B03
E55A 5AF8
E55B 5B02
E55C 5AF9
E55D 5B01
E55E 5B07
E55F 5B05
E560 5B0F
E561 5C67
E562 5D99
E563 5D97
E564 5D9F
E565 5D92
E566 5DA2
E567 5D93
E568 5D95
E569 5DA0
E56A 5D9C
E56B 5DA1
E56C 5D9A
E56D 5D9E
E56E 5E69
E56F 5E5D
E570 5E60
E571 5E5C
E572 7DF3
E573 5EDB
E574 5EDE
E575 5EE1
E576 5F49
E577 5FB2
E578 618B
E579 6183
E57A 6179
E57B 61B1
E57C 61B0
E57D 61A2
E57E 6189
E5A1 619B
E5A2 6193
E5A3 61AF
E5A4 61AD
E5A5 619F
E5A6 6192
E5A7 61AA
E5A8 61A1
E5A9 618D
E5AA 6166
E5AB 61B3
E5AC 622D
E5AD 646E
E5AE 6470
E5AF 6496
E5B0 64A0
E5B1 6485
E5B2 6497
E5B3 649C
E5B4 648F
E5B5 648B
E5B6 648A
E5B7 648C
E5B8 64A3
E5B9 649F
E5BA 6468
E5BB 64B1
E5BC 6498
E5BD 6576
E5BE 657A
E5BF 6579
E5C0 657B
E5C1 65B2
E5C2 65B3
E5C3 66B5
E5C4 66B0
E5C5 66A9
E5C6 66B2
E5C7 66B7
E5C8 66AA
E5C9 66AF
E5CA 6A00
E5CB 6A06
E5CC 6A17
E5CD 69E5
E5CE 69F8
E5CF 6A15
E5D0 69F1
E5D1 69E4
E5D2 6A20
E5D3 69FF
E5D4 69EC
E5D5 69E2
E5D6 6A1B
E5D7 6A1D
E5D8 69FE
E5D9 6A27
E5DA 69F2
E5DB 69EE
E5DC 6A14
E5DD 69F7
E5DE 69E7
E5DF 6A40
E5E0 6A08
E5E1 69E6
E5E2 69FB
E5E3 6A0D
E5E4 69FC
E5E5 69EB
E5E6 6A09
E5E7 6A04
E5E8 6A18
E5E9 6A25
E5EA 6A0F
E5EB 69F6
E5EC 6A26
E5ED 6A07
E5EE 69F4
E5EF 6A16
E5F0 6B51
E5F1 6BA5
E5F2 6BA3
E5F3 6BA2
E5F4 6BA6
E5F5 6C01
E5F6 6C00
E5F7 6BFF
E5F8 6C02
E5F9 6F41
E5FA 6F26
E5FB 6F7E
E5FC 6F87
E5FD 6FC6
E5FE 6F92
E640 6F8D
E641 6F89
E642 6F8C
E643 6F62
E644 6F4F
E645 6F85
E646 6F5A
E647 6F96
E648 6F76
E649 6F6C
E64A 6F82
E64B 6F55
E64C 6F72
E64D 6F52
E64E 6F50
E64F 6F57
E650 6F94
E651 6F93
E652 6F5D
E653 6F00
E654 6F61
E655 6F6B
E656 6F7D
E657 6F67
E658 6F90
E659 6F53
E65A 6F8B
E65B 6F69
E65C 6F7F
E65D 6F95
E65E 6F63
E65F 6F77
E660 6F6A
E661 6F7B
E662 71B2
E663 71AF
E664 719B
E665 71B0
E666 71A0
E667 719A
E668 71A9
E669 71B5
E66A 719D
E66B 71A5
E66C 719E
E66D 71A4
E66E 71A1
E66F 71AA
E670 719C
E671 71A7
E672 71B3
E673 7298
E674 729A
E675 7358
E676 7352
E677 735E
E678 735F
E679 7360
E67A 735D
E67B 735B
E67C 7361
E67D 735A
E67E 7359
E6A1 7362
E6A2 7487
E6A3 7489
E6A4 748A
E6A5 7486
E6A6 7481
E6A7 747D
E6A8 7485
E6A9 7488
E6AA 747C
E6AB 7479
E6AC 7508
E6AD 7507
E6AE 757E
E6AF 7625
E6B0 761E
E6B1 7619
E6B2 761D
E6B3 761C
E6B4 7623
E6B5 761A
E6B6 7628
E6B7 761B
E6B8 769C
E6B9 769D
E6BA 769E
E6BB 769B
E6BC 778D
E6BD 778F
E6BE 7789
E6BF 7788
E6C0 78CD
E6C1 78BB
E6C2 78CF
E6C3 78CC
E6C4 78D1
E6C5 78CE
E6C6 78D4
E6C7 78C8
E6C8 78C3
E6C9 78C4
E6CA 78C9
E6CB 799A
E6CC 79A1
E6CD 79A0
E6CE 799C
E6CF 79A2
E6D0 799B
E6D1 6B76
E6D2 7A39
E6D3 7AB2
E6D4 7AB4
E6D5 7AB3
E6D6 7BB7
E6D7 7BCB
E6D8 7BBE
E6D9 7BAC
E6DA 7BCE
E6DB 7BAF
E6DC 7BB9
E6DD 7BCA
E6DE 7BB5
E6DF 7CC5
E6E0 7CC8
E6E1 7CCC
E6E2 7CCB
E6E3 7DF7
E6E4 7DDB
E6E5 7DEA
E6E6 7DE7
E6E7 7DD7
E6E8 7DE1
E6E9 7E03
E6EA 7DFA
E6EB 7DE6
E6EC 7DF6
E6ED 7DF1
E6EE 7DF0
E6EF 7DEE
E6F0 7DDF
E6F1 7F76
E6F2 7FAC
E6F3 7FB0
E6F4 7FAD
E6F5 7FED
E6F6 7FEB
E6F7 7FEA
E6F8 7FEC
E6F9 7FE6
E6FA 7FE8
E6FB 8064
E6FC 8067
E6FD 81A3
E6FE 819F
E740 819E
E741 8195
E742 81A2
E743 8199
E744 8197
E745 8216
E746 824F
E747 8253
E748 8252
E749 8250
E74A 824E
E74B 8251
E74C 8524
E74D 853B
E74E 850F
E74F 8500
E750 8529
E751 850E
E752 8509
E753 850D
E754 851F
E755 850A
E756 8527
E757 851C
E758 84FB
E759 852B
E75A 84FA
E75B 8508
E75C 850C
E75D 84F4
E75E 852A
E75F 84F2
E760 8515
E761 84F7
E762 84EB
E763 84F3
E764 84FC
E765 8512
E766 84EA
E767 84E9
E768 8516
E769 84FE
E76A 8528
E76B 851D
E76C 852E
E76D 8502
E76E 84FD
E76F 851E
E770 84F6
E771 8531
E772 8526
E773 84E7
E774 84E8
E775 84F0
E776 84EF
E777 84F9
E778 8518
E779 8520
E77A 8530
E77B 850B
E77C 8519
E77D 852F
E77E 8662
E7A1 8756
E7A2 8763
E7A3 8764
E7A4 8777
E7A5 87E1
E7A6 8773
E7A7 8758
E7A8 8754
E7A9 875B
E7AA 8752
E7AB 8761
E7AC 875A
E7AD 8751
E7AE 875E
E7AF 876D
E7B0 876A
E7B1 8750
E7B2 874E
E7B3 875F
E7B4 875D
E7B5 876F
E7B6 876C
E7B7 877A
E7B8 876E
E7B9 875C
E7BA 8765
E7BB 874F
E7BC 877B
E7BD 8775
E7BE 8762
E7BF 8767
E7C0 8769
E7C1 885A
E7C2 8905
E7C3 890C
E7C4 8914
E7C5 890B
E7C6 8917
E7C7 8918
E7C8 8919
E7C9 8906
E7CA 8916
E7CB 8911
E7CC 890E
E7CD 8909
E7CE 89A2
E7CF 89A4
E7D0 89A3
E7D1 89ED
E7D2 89F0
E7D3 89EC
E7D4 8ACF
E7D5 8AC6
E7D6 8AB8
E7D7 8AD3
E7D8 8AD1
E7D9 8AD4
E7DA 8AD5
E7DB 8ABB
E7DC 8AD7
E7DD 8ABE
E7DE 8AC0
E7DF 8AC5
E7E0 8AD8
E7E1 8AC3
E7E2 8ABA
E7E3 8ABD
E7E4 8AD9
E7E5 8C3E
E7E6 8C4D
E7E7 8C8F
E7E8 8CE5
E7E9 8CDF
E7EA 8CD9
E7EB 8CE8
E7EC 8CDA
E7ED 8CDD
E7EE 8CE7
E7EF 8DA0
E7F0 8D9C
E7F1 8DA1
E7F2 8D9B
E7F3 8E20
E7F4 8E23
E7F5 8E25
E7F6 8E24
E7F7 8E2E
E7F8 8E15
E7F9 8E1B
E7FA 8E16
E7FB 8E11
E7FC 8E19
E7FD 8E26
E7FE 8E27
E840 8E14
E841 8E12
E842 8E18
E843 8E13
E844 8E1C
E845 8E17
E846 8E1A
E847 8F2C
E848 8F24
E849 8F18
E84A 8F1A
E84B 8F20
E84C 8F23
E84D 8F16
E84E 8F17
E84F 9073
E850 9070
E851 906F
E852 9067
E853 906B
E854 912F
E855 912B
E856 9129
E857 912A
E858 9132
E859 9126
E85A 912E
E85B 9185
E85C 9186
E85D 918A
E85E 9181
E85F 9182
E860 9184
E861 9180
E862 92D0
E863 92C3
E864 92C4
E865 92C0
E866 92D9
E867 92B6
E868 92CF
E869 92F1
E86A 92DF
E86B 92D8
E86C 92E9
E86D 92D7
E86E 92DD
E86F 92CC
E870 92EF
E871 92C2
E872 92E8
E873 92CA
E874 92C8
E875 92CE
E876 92E6
E877 92CD
E878 92D5
E879 92C9
E87A 92E0
E87B 92DE
E87C 92E7
E87D 92D1
E87E 92D3
E8A1 92B5
E8A2 92E1
E8A3 92C6
E8A4 92B4
E8A5 957C
E8A6 95AC
E8A7 95AB
E8A8 95AE
E8A9 95B0
E8AA 96A4
E8AB 96A2
E8AC 96D3
E8AD 9705
E8AE 9708
E8AF 9702
E8B0 975A
E8B1 978A
E8B2 978E
E8B3 9788
E8B4 97D0
E8B5 97CF
E8B6 981E
E8B7 981D
E8B8 9826
E8B9 9829
E8BA 9828
E8BB 9820
E8BC 981B
E8BD 9827
E8BE 98B2
E8BF 9908
E8C0 98FA
E8C1 9911
E8C2 9914
E8C3 9916
E8C4 9917
E8C5 9915
E8C6 99DC
E8C7 99CD
E8C8 99CF
E8C9 99D3
E8CA 99D4
E8CB 99CE
E8CC 99C9
E8CD 99D6
E8CE 99D8
E8CF 99CB
E8D0 99D7
E8D1 99CC
E8D2 9AB3
E8D3 9AEC
E8D4 9AEB
E8D5 9AF3
E8D6 9AF2
E8D7 9AF1
E8D8 9B46
E8D9 9B43
E8DA 9B67
E8DB 9B74
E8DC 9B71
E8DD 9B66
E8DE 9B76
E8DF 9B75
E8E0 9B70
E8E1 9B68
E8E2 9B64
E8E3 9B6C
E8E4 9CFC
E8E5 9CFA
E8E6 9CFD
E8E7 9CFF
E8E8 9CF7
E8E9 9D07
E8EA 9D00
E8EB 9CF9
E8EC 9CFB
E8ED 9D08
E8EE 9D05
E8EF 9D04
E8F0 9E83
E8F1 9ED3
E8F2 9F0F
E8F3 9F10
E8F4 511C
E8F5 5113
E8F6 5117
E8F7 511A
E8F8 5111
E8F9 51DE
E8FA 5334
E8FB 53E1
E8FC 5670
E8FD 5660
E8FE 566E
E940 5673
E941 5666
E942 5663
E943 566D
E944 5672
E945 565E
E946 5677
E947 571C
E948 571B
E949 58C8
E94A 58BD
E94B 58C9
E94C 58BF
E94D 58BA
E94E 58C2
E94F 58BC
E950 58C6
E951 5B17
E952 5B19
E953 5B1B
E954 5B21
E955 5B14
E956 5B13
E957 5B10
E958 5B16
E959 5B28
E95A 5B1A
E95B 5B20
E95C 5B1E
E95D 5BEF
E95E 5DAC
E95F 5DB1
E960 5DA9
E961 5DA7
E962 5DB5
E963 5DB0
E964 5DAE
E965 5DAA
E966 5DA8
E967 5DB2
E968 5DAD
E969 5DAF
E96A 5DB4
E96B 5E67
E96C 5E68
E96D 5E66
E96E 5E6F
E96F 5EE9
E970 5EE7
E971 5EE6
E972 5EE8
E973 5EE5
E974 5F4B
E975 5FBC
E976 619D
E977 61A8
E978 6196
E979 61C5
E97A 61B4
E97B 61C6
E97C 61C1
E97D 61CC
E97E 61BA
E9A1 61BF
E9A2 61B8
E9A3 618C
E9A4 64D7
E9A5 64D6
E9A6 64D0
E9A7 64CF
E9A8 64C9
E9A9 64BD
E9AA 6489
E9AB 64C3
E9AC 64DB
E9AD 64F3
E9AE 64D9
E9AF 6533
E9B0 657F
E9B1 657C
E9B2 65A2
E9B3 66C8
E9B4 66BE
E9B5 66C0
E9B6 66CA
E9B7 66CB
E9B8 66CF
E9B9 66BD
E9BA 66BB
E9BB 66BA
E9BC 66CC
E9BD 6723
E9BE 6A34
E9BF 6A66
E9C0 6A49
E9C1 6A67
E9C2 6A32
E9C3 6A68
E9C4 6A3E
E9C5 6A5D
E9C6 6A6D
E9C7 6A76
E9C8 6A5B
E9C9 6A51
E9CA 6A28
E9CB 6A5A
E9CC 6A3B
E9CD 6A3F
E9CE 6A41
E9CF 6A6A
E9D0 6A64
E9D1 6A50
E9D2 6A4F
E9D3 6A54
E9D4 6A6F
E9D5 6A69
E9D6 6A60
E9D7 6A3C
E9D8 6A5E
E9D9 6A56
E9DA 6A55
E9DB 6A4D
E9DC 6A4E
E9DD 6A46
E9DE 6B55
E9DF 6B54
E9E0 6B56
E9E1 6BA7
E9E2 6BAA
E9E3 6BAB
E9E4 6BC8
E9E5 6BC7
E9E6 6C04
E9E7 6C03
E9E8 6C06
E9E9 6FAD
E9EA 6FCB
E9EB 6FA3
E9EC 6FC7
E9ED 6FBC
E9EE 6FCE
E9EF 6FC8
E9F0 6F5E
E9F1 6FC4
E9F2 6FBD
E9F3 6F9E
E9F4 6FCA
E9F5 6FA8
E9F6 7004
E9F7 6FA5
E9F8 6FAE
E9F9 6FBA
E9FA 6FAC
E9FB 6FAA
E9FC 6FCF
E9FD 6FBF
E9FE 6FB8
EA40 6FA2
EA41 6FC9
EA42 6FAB
EA43 6FCD
EA44 6FAF
EA45 6FB2
EA46 6FB0
EA47 71C5
EA48 71C2
EA49 71BF
EA4A 71B8
EA4B 71D6
EA4C 71C0
EA4D 71C1
EA4E 71CB
EA4F 71D4
EA50 71CA
EA51 71C7
EA52 71CF
EA53 71BD
EA54 71D8
EA55 71BC
EA56 71C6
EA57 71DA
EA58 71DB
EA59 729D
EA5A 729E
EA5B 7369
EA5C 7366
EA5D 7367
EA5E 736C
EA5F 7365
EA60 736B
EA61 736A
EA62 747F
EA63 749A
EA64 74A0
EA65 7494
EA66 7492
EA67 7495
EA68 74A1
EA69 750B
EA6A 7580
EA6B 762F
EA6C 762D
EA6D 7631
EA6E 763D
EA6F 7633
EA70 763C
EA71 7635
EA72 7632
EA73 7630
EA74 76BB
EA75 76E6
EA76 779A
EA77 779D
EA78 77A1
EA79 779C
EA7A 779B
EA7B 77A2
EA7C 77A3
EA7D 7795
EA7E 7799
EAA1 7797
EAA2 78DD
EAA3 78E9
EAA4 78E5
EAA5 78EA
EAA6 78DE
EAA7 78E3
EAA8 78DB
EAA9 78E1
EAAA 78E2
EAAB 78ED
EAAC 78DF
EAAD 78E0
EAAE 79A4
EAAF 7A44
EAB0 7A48
EAB1 7A47
EAB2 7AB6
EAB3 7AB8
EAB4 7AB5
EAB5 7AB1
EAB6 7AB7
EAB7 7BDE
EAB8 7BE3
EAB9 7BE7
EABA 7BDD
EABB 7BD5
EABC 7BE5
EABD 7BDA
EABE 7BE8
EABF 7BF9
EAC0 7BD4
EAC1 7BEA
EAC2 7BE2
EAC3 7BDC
EAC4 7BEB
EAC5 7BD8
EAC6 7BDF
EAC7 7CD2
EAC8 7CD4
EAC9 7CD7
EACA 7CD0
EACB 7CD1
EACC 7E12
EACD 7E21
EACE 7E17
EACF 7E0C
EAD0 7E1F
EAD1 7E20
EAD2 7E13
EAD3 7E0E
EAD4 7E1C
EAD5 7E15
EAD6 7E1A
EAD7 7E22
EAD8 7E0B
EAD9 7E0F
EADA 7E16
EADB 7E0D
EADC 7E14
EADD 7E25
EADE 7E24
EADF 7F43
EAE0 7F7B
EAE1 7F7C
EAE2 7F7A
EAE3 7FB1
EAE4 7FEF
EAE5 802A
EAE6 8029
EAE7 806C
EAE8 81B1
EAE9 81A6
EAEA 81AE
EAEB 81B9
EAEC 81B5
EAED 81AB
EAEE 81B0
EAEF 81AC
EAF0 81B4
EAF1 81B2
EAF2 81B7
EAF3 81A7
EAF4 81F2
EAF5 8255
EAF6 8256
EAF7 8257
EAF8 8556
EAF9 8545
EAFA 856B
EAFB 854D
EAFC 8553
EAFD 8561
EAFE 8558
EB40 8540
EB41 8546
EB42 8564
EB43 8541
EB44 8562
EB45 8544
EB46 8551
EB47 8547
EB48 8563
EB49 853E
EB4A 855B
EB4B 8571
EB4C 854E
EB4D 856E
EB4E 8575
EB4F 8555
EB50 8567
EB51 8560
EB52 858C
EB53 8566
EB54 855D
EB55 8554
EB56 8565
EB57 856C
EB58 8663
EB59 8665
EB5A 8664
EB5B 879B
EB5C 878F
EB5D 8797
EB5E 8793
EB5F 8792
EB60 8788
EB61 8781
EB62 8796
EB63 8798
EB64 8779
EB65 8787
EB66 87A3
EB67 8785
EB68 8790
EB69 8791
EB6A 879D
EB6B 8784
EB6C 8794
EB6D 879C
EB6E 879A
EB6F 8789
EB70 891E
EB71 8926
EB72 8930
EB73 892D
EB74 892E
EB75 8927
EB76 8931
EB77 8922
EB78 8929
EB79 8923
EB7A 892F
EB7B 892C
EB7C 891F
EB7D 89F1
EB7E 8AE0
EBA1 8AE2
EBA2 8AF2
EBA3 8AF4
EBA4 8AF5
EBA5 8ADD
EBA6 8B14
EBA7 8AE4
EBA8 8ADF
EBA9 8AF0
EBAA 8AC8
EBAB 8ADE
EBAC 8AE1
EBAD 8AE8
EBAE 8AFF
EBAF 8AEF
EBB0 8AFB
EBB1 8C91
EBB2 8C92
EBB3 8C90
EBB4 8CF5
EBB5 8CEE
EBB6 8CF1
EBB7 8CF0
EBB8 8CF3
EBB9 8D6C
EBBA 8D6E
EBBB 8DA5
EBBC 8DA7
EBBD 8E33
EBBE 8E3E
EBBF 8E38
EBC0 8E40
EBC1 8E45
EBC2 8E36
EBC3 8E3C
EBC4 8E3D
EBC5 8E41
EBC6 8E30
EBC7 8E3F
EBC8 8EBD
EBC9 8F36
EBCA 8F2E
EBCB 8F35
EBCC 8F32
EBCD 8F39
EBCE 8F37
EBCF 8F34
EBD0 9076
EBD1 9079
EBD2 907B
EBD3 9086
EBD4 90FA
EBD5 9133
EBD6 9135
EBD7 9136
EBD8 9193
EBD9 9190
EBDA 9191
EBDB 918D
EBDC 918F
EBDD 9327
EBDE 931E
EBDF 9308
EBE0 931F
EBE1 9306
EBE2 930F
EBE3 937A
EBE4 9338
EBE5 933C
EBE6 931B
EBE7 9323
EBE8 9312
EBE9 9301
EBEA 9346
EBEB 932D
EBEC 930E
EBED 930D
EBEE 92CB
EBEF 931D
EBF0 92FA
EBF1 9325
EBF2 9313
EBF3 92F9
EBF4 92F7
EBF5 9334
EBF6 9302
EBF7 9324
EBF8 92FF
EBF9 9329
EBFA 9339
EBFB 9335
EBFC 932A
EBFD 9314
EBFE 930C
EC40 930B
EC41 92FE
EC42 9309
EC43 9300
EC44 92FB
EC45 9316
EC46 95BC
EC47 95CD
EC48 95BE
EC49 95B9
EC4A 95BA
EC4B 95B6
EC4C 95BF
EC4D 95B5
EC4E 95BD
EC4F 96A9
EC50 96D4
EC51 970B
EC52 9712
EC53 9710
EC54 9799
EC55 9797
EC56 9794
EC57 97F0
EC58 97F8
EC59 9835
EC5A 982F
EC5B 9832
EC5C 9924
EC5D 991F
EC5E 9927
EC5F 9929
EC60 999E
EC61 99EE
EC62 99EC
EC63 99E5
EC64 99E4
EC65 99F0
EC66 99E3
EC67 99EA
EC68 99E9
EC69 99E7
EC6A 9AB9
EC6B 9ABF
EC6C 9AB4
EC6D 9ABB
EC6E 9AF6
EC6F 9AFA
EC70 9AF9
EC71 9AF7
EC72 9B33
EC73 9B80
EC74 9B85
EC75 9B87
EC76 9B7C
EC77 9B7E
EC78 9B7B
EC79 9B82
EC7A 9B93
EC7B 9B92
EC7C 9B90
EC7D 9B7A
EC7E 9B95
ECA1 9B7D
ECA2 9B88
ECA3 9D25
ECA4 9D17
ECA5 9D20
ECA6 9D1E
ECA7 9D14
ECA8 9D29
ECA9 9D1D
ECAA 9D18
ECAB 9D22
ECAC 9D10
ECAD 9D19
ECAE 9D1F
ECAF 9E88
ECB0 9E86
ECB1 9E87
ECB2 9EAE
ECB3 9EAD
ECB4 9ED5
ECB5 9ED6
ECB6 9EFA
ECB7 9F12
ECB8 9F3D
ECB9 5126
ECBA 5125
ECBB 5122
ECBC 5124
ECBD 5120
ECBE 5129
ECBF 52F4
ECC0 5693
ECC1 568C
ECC2 568D
ECC3 5686
ECC4 5684
ECC5 5683
ECC6 567E
ECC7 5682
ECC8 567F
ECC9 5681
ECCA 58D6
ECCB 58D4
ECCC 58CF
ECCD 58D2
ECCE 5B2D
ECCF 5B25
ECD0 5B32
ECD1 5B23
ECD2 5B2C
ECD3 5B27
ECD4 5B26
ECD5 5B2F
ECD6 5B2E
ECD7 5B7B
ECD8 5BF1
ECD9 5BF2
ECDA 5DB7
ECDB 5E6C
ECDC 5E6A
ECDD 5FBE
ECDE 5FBB
ECDF 61C3
ECE0 61B5
ECE1 61BC
ECE2 61E7
ECE3 61E0
ECE4 61E5
ECE5 61E4
ECE6 61E8
ECE7 61DE
ECE8 64EF
ECE9 64E9
ECEA 64E3
ECEB 64EB
ECEC 64E4
ECED 64E8
ECEE 6581
ECEF 6580
ECF0 65B6
ECF1 65DA
ECF2 66D2
ECF3 6A8D
ECF4 6A96
ECF5 6A81
ECF6 6AA5
ECF7 6A89
ECF8 6A9F
ECF9 6A9B
ECFA 6AA1
ECFB 6A9E
ECFC 6A87
ECFD 6A93
ECFE 6A8E
ED40 6A95
ED41 6A83
ED42 6AA8
ED43 6AA4
ED44 6A91
ED45 6A7F
ED46 6AA6
ED47 6A9A
ED48 6A85
ED49 6A8C
ED4A 6A92
ED4B 6B5B
ED4C 6BAD
ED4D 6C09
ED4E 6FCC
ED4F 6FA9
ED50 6FF4
ED51 6FD4
ED52 6FE3
ED53 6FDC
ED54 6FED
ED55 6FE7
ED56 6FE6
ED57 6FDE
ED58 6FF2
ED59 6FDD
ED5A 6FE2
ED5B 6FE8
ED5C 71E1
ED5D 71F1
ED5E 71E8
ED5F 71F2
ED60 71E4
ED61 71F0
ED62 71E2
ED63 7373
ED64 736E
ED65 736F
ED66 7497
ED67 74B2
ED68 74AB
ED69 7490
ED6A 74AA
ED6B 74AD
ED6C 74B1
ED6D 74A5
ED6E 74AF
ED6F 7510
ED70 7511
ED71 7512
ED72 750F
ED73 7584
ED74 7643
ED75 7648
ED76 7649
ED77 7647
ED78 76A4
ED79 76E9
ED7A 77B5
ED7B 77AB
ED7C 77B2
ED7D 77B7
ED7E 77B6
EDA1 77B4
EDA2 77B1
EDA3 77A8
EDA4 77F0
EDA5 78F3
EDA6 78FD
EDA7 7902
EDA8 78FB
EDA9 78FC
EDAA 78F2
EDAB 7905
EDAC 78F9
EDAD 78FE
EDAE 7904
EDAF 79AB
EDB0 79A8
EDB1 7A5C
EDB2 7A5B
EDB3 7A56
EDB4 7A58
EDB5 7A54
EDB6 7A5A
EDB7 7ABE
EDB8 7AC0
EDB9 7AC1
EDBA 7C05
EDBB 7C0F
EDBC 7BF2
EDBD 7C00
EDBE 7BFF
EDBF 7BFB
EDC0 7C0E
EDC1 7BF4
EDC2 7C0B
EDC3 7BF3
EDC4 7C02
EDC5 7C09
EDC6 7C03
EDC7 7C01
EDC8 7BF8
EDC9 7BFD
EDCA 7C06
EDCB 7BF0
EDCC 7BF1
EDCD 7C10
EDCE 7C0A
EDCF 7CE8
EDD0 7E2D
EDD1 7E3C
EDD2 7E42
EDD3 7E33
EDD4 9848
EDD5 7E38
EDD6 7E2A
EDD7 7E49
EDD8 7E40
EDD9 7E47
EDDA 7E29
EDDB 7E4C
EDDC 7E30
EDDD 7E3B
EDDE 7E36
EDDF 7E44
EDE0 7E3A
EDE1 7F45
EDE2 7F7F
EDE3 7F7E
EDE4 7F7D
EDE5 7FF4
EDE6 7FF2
EDE7 802C
EDE8 81BB
EDE9 81C4
EDEA 81CC
EDEB 81CA
EDEC 81C5
EDED 81C7
EDEE 81BC
EDEF 81E9
EDF0 825B
EDF1 825A
EDF2 825C
EDF3 8583
EDF4 8580
EDF5 858F
EDF6 85A7
EDF7 8595
EDF8 85A0
EDF9 858B
EDFA 85A3
EDFB 857B
EDFC 85A4
EDFD 859A
EDFE 859E
EE40 8577
EE41 857C
EE42 8589
EE43 85A1
EE44 857A
EE45 8578
EE46 8557
EE47 858E
EE48 8596
EE49 8586
EE4A 858D
EE4B 8599
EE4C 859D
EE4D 8581
EE4E 85A2
EE4F 8582
EE50 8588
EE51 8585
EE52 8579
EE53 8576
EE54 8598
EE55 8590
EE56 859F
EE57 8668
EE58 87BE
EE59 87AA
EE5A 87AD
EE5B 87C5
EE5C 87B0
EE5D 87AC
EE5E 87B9
EE5F 87B5
EE60 87BC
EE61 87AE
EE62 87C9
EE63 87C3
EE64 87C2
EE65 87CC
EE66 87B7
EE67 87AF
EE68 87C4
EE69 87CA
EE6A 87B4
EE6B 87B6
EE6C 87BF
EE6D 87B8
EE6E 87BD
EE6F 87DE
EE70 87B2
EE71 8935
EE72 8933
EE73 893C
EE74 893E
EE75 8941
EE76 8952
EE77 8937
EE78 8942
EE79 89AD
EE7A 89AF
EE7B 89AE
EE7C 89F2
EE7D 89F3
EE7E 8B1E
EEA1 8B18
EEA2 8B16
EEA3 8B11
EEA4 8B05
EEA5 8B0B
EEA6 8B22
EEA7 8B0F
EEA8 8B12
EEA9 8B15
EEAA 8B07
EEAB 8B0D
EEAC 8B08
EEAD 8B06
EEAE 8B1C
EEAF 8B13
EEB0 8B1A
EEB1 8C4F
EEB2 8C70
EEB3 8C72
EEB4 8C71
EEB5 8C6F
EEB6 8C95
EEB7 8C94
EEB8 8CF9
EEB9 8D6F
EEBA 8E4E
EEBB 8E4D
EEBC 8E53
EEBD 8E50
EEBE 8E4C
EEBF 8E47
EEC0 8F43
EEC1 8F40
EEC2 9085
EEC3 907E
EEC4 9138
EEC5 919A
EEC6 91A2
EEC7 919B
EEC8 9199
EEC9 919F
EECA 91A1
EECB 919D
EECC 91A0
EECD 93A1
EECE 9383
EECF 93AF
EED0 9364
EED1 9356
EED2 9347
EED3 937C
EED4 9358
EED5 935C
EED6 9376
EED7 9349
EED8 9350
EED9 9351
EEDA 9360
EEDB 936D
EEDC 938F
EEDD 934C
EEDE 936A
EEDF 9379
EEE0 9357
EEE1 9355
EEE2 9352
EEE3 934F
EEE4 9371
EEE5 9377
EEE6 937B
EEE7 9361
EEE8 935E
EEE9 9363
EEEA 9367
EEEB 9380
EEEC 934E
EEED 9359
EEEE 95C7
EEEF 95C0
EEF0 95C9
EEF1 95C3
EEF2 95C5
EEF3 95B7
EEF4 96AE
EEF5 96B0
EEF6 96AC
EEF7 9720
EEF8 971F
EEF9 9718
EEFA 971D
EEFB 9719
EEFC 979A
EEFD 97A1
EEFE 979C
EF40 979E
EF41 979D
EF42 97D5
EF43 97D4
EF44 97F1
EF45 9841
EF46 9844
EF47 984A
EF48 9849
EF49 9845
EF4A 9843
EF4B 9925
EF4C 992B
EF4D 992C
EF4E 992A
EF4F 9933
EF50 9932
EF51 992F
EF52 992D
EF53 9931
EF54 9930
EF55 9998
EF56 99A3
EF57 99A1
EF58 9A02
EF59 99FA
EF5A 99F4
EF5B 99F7
EF5C 99F9
EF5D 99F8
EF5E 99F6
EF5F 99FB
EF60 99FD
EF61 99FE
EF62 99FC
EF63 9A03
EF64 9ABE
EF65 9AFE
EF66 9AFD
EF67 9B01
EF68 9AFC
EF69 9B48
EF6A 9B9A
EF6B 9BA8
EF6C 9B9E
EF6D 9B9B
EF6E 9BA6
EF6F 9BA1
EF70 9BA5
EF71 9BA4
EF72 9B86
EF73 9BA2
EF74 9BA0
EF75 9BAF
EF76 9D33
EF77 9D41
EF78 9D67
EF79 9D36
EF7A 9D2E
EF7B 9D2F
EF7C 9D31
EF7D 9D38
EF7E 9D30
EFA1 9D45
EFA2 9D42
EFA3 9D43
EFA4 9D3E
EFA5 9D37
EFA6 9D40
EFA7 9D3D
EFA8 7FF5
EFA9 9D2D
EFAA 9E8A
EFAB 9E89
EFAC 9E8D
EFAD 9EB0
EFAE 9EC8
EFAF 9EDA
EFB0 9EFB
EFB1 9EFF
EFB2 9F24
EFB3 9F23
EFB4 9F22
EFB5 9F54
EFB6 9FA0
EFB7 5131
EFB8 512D
EFB9 512E
EFBA 5698
EFBB 569C
EFBC 5697
EFBD 569A
EFBE 569D
EFBF 5699
EFC0 5970
EFC1 5B3C
EFC2 5C69
EFC3 5C6A
EFC4 5DC0
EFC5 5E6D
EFC6 5E6E
EFC7 61D8
EFC8 61DF
EFC9 61ED
EFCA 61EE
EFCB 61F1
EFCC 61EA
EFCD 61F0
EFCE 61EB
EFCF 61D6
EFD0 61E9
EFD1 64FF
EFD2 6504
EFD3 64FD
EFD4 64F8
EFD5 6501
EFD6 6503
EFD7 64FC
EFD8 6594
EFD9 65DB
EFDA 66DA
EFDB 66DB
EFDC 66D8
EFDD 6AC5
EFDE 6AB9
EFDF 6ABD
EFE0 6AE1
EFE1 6AC6
EFE2 6ABA
EFE3 6AB6
EFE4 6AB7
EFE5 6AC7
EFE6 6AB4
EFE7 6AAD
EFE8 6B5E
EFE9 6BC9
EFEA 6C0B
EFEB 7007
EFEC 700C
EFED 700D
EFEE 7001
EFEF 7005
EFF0 7014
EFF1 700E
EFF2 6FFF
EFF3 7000
EFF4 6FFB
EFF5 7026
EFF6 6FFC
EFF7 6FF7
EFF8 700A
EFF9 7201
EFFA 71FF
EFFB 71F9
EFFC 7203
EFFD 71FD
EFFE 7376
F040 74B8
F041 74C0
F042 74B5
F043 74C1
F044 74BE
F045 74B6
F046 74BB
F047 74C2
F048 7514
F049 7513
F04A 765C
F04B 7664
F04C 7659
F04D 7650
F04E 7653
F04F 7657
F050 765A
F051 76A6
F052 76BD
F053 76EC
F054 77C2
F055 77BA
F056 78FF
F057 790C
F058 7913
F059 7914
F05A 7909
F05B 7910
F05C 7912
F05D 7911
F05E 79AD
F05F 79AC
F060 7A5F
F061 7C1C
F062 7C29
F063 7C19
F064 7C20
F065 7C1F
F066 7C2D
F067 7C1D
F068 7C26
F069 7C28
F06A 7C22
F06B 7C25
F06C 7C30
F06D 7E5C
F06E 7E50
F06F 7E56
F070 7E63
F071 7E58
F072 7E62
F073 7E5F
F074 7E51
F075 7E60
F076 7E57
F077 7E53
F078 7FB5
F079 7FB3
F07A 7FF7
F07B 7FF8
F07C 8075
F07D 81D1
F07E 81D2
F0A1 81D0
F0A2 825F
F0A3 825E
F0A4 85B4
F0A5 85C6
F0A6 85C0
F0A7 85C3
F0A8 85C2
F0A9 85B3
F0AA 85B5
F0AB 85BD
F0AC 85C7
F0AD 85C4
F0AE 85BF
F0AF 85CB
F0B0 85CE
F0B1 85C8
F0B2 85C5
F0B3 85B1
F0B4 85B6
F0B5 85D2
F0B6 8624
F0B7 85B8
F0B8 85B7
F0B9 85BE
F0BA 8669
F0BB 87E7
F0BC 87E6
F0BD 87E2
F0BE 87DB
F0BF 87EB
F0C0 87EA
F0C1 87E5
F0C2 87DF
F0C3 87F3
F0C4 87E4
F0C5 87D4
F0C6 87DC
F0C7 87D3
F0C8 87ED
F0C9 87D8
F0CA 87E3
F0CB 87A4
F0CC 87D7
F0CD 87D9
F0CE 8801
F0CF 87F4
F0D0 87E8
F0D1 87DD
F0D2 8953
F0D3 894B
F0D4 894F
F0D5 894C
F0D6 8946
F0D7 8950
F0D8 8951
F0D9 8949
F0DA 8B2A
F0DB 8B27
F0DC 8B23
F0DD 8B33
F0DE 8B30
F0DF 8B35
F0E0 8B47
F0E1 8B2F
F0E2 8B3C
F0E3 8B3E
F0E4 8B31
F0E5 8B25
F0E6 8B37
F0E7 8B26
F0E8 8B36
F0E9 8B2E
F0EA 8B24
F0EB 8B3B
F0EC 8B3D
F0ED 8B3A
F0EE 8C42
F0EF 8C75
F0F0 8C99
F0F1 8C98
F0F2 8C97
F0F3 8CFE
F0F4 8D04
F0F5 8D02
F0F6 8D00
F0F7 8E5C
F0F8 8E62
F0F9 8E60
F0FA 8E57
F0FB 8E56
F0FC 8E5E
F0FD 8E65
F0FE 8E67
F140 8E5B
F141 8E5A
F142 8E61
F143 8E5D
F144 8E69
F145 8E54
F146 8F46
F147 8F47
F148 8F48
F149 8F4B
F14A 9128
F14B 913A
F14C 913B
F14D 913E
F14E 91A8
F14F 91A5
F150 91A7
F151 91AF
F152 91AA
F153 93B5
F154 938C
F155 9392
F156 93B7
F157 939B
F158 939D
F159 9389
F15A 93A7
F15B 938E
F15C 93AA
F15D 939E
F15E 93A6
F15F 9395
F160 9388
F161 9399
F162 939F
F163 938D
F164 93B1
F165 9391
F166 93B2
F167 93A4
F168 93A8
F169 93B4
F16A 93A3
F16B 93A5
F16C 95D2
F16D 95D3
F16E 95D1
F16F 96B3
F170 96D7
F171 96DA
F172 5DC2
F173 96DF
F174 96D8
F175 96DD
F176 9723
F177 9722
F178 9725
F179 97AC
F17A 97AE
F17B 97A8
F17C 97AB
F17D 97A4
F17E 97AA
F1A1 97A2
F1A2 97A5
F1A3 97D7
F1A4 97D9
F1A5 97D6
F1A6 97D8
F1A7 97FA
F1A8 9850
F1A9 9851
F1AA 9852
F1AB 98B8
F1AC 9941
F1AD 993C
F1AE 993A
F1AF 9A0F
F1B0 9A0B
F1B1 9A09
F1B2 9A0D
F1B3 9A04
F1B4 9A11
F1B5 9A0A
F1B6 9A05
F1B7 9A07
F1B8 9A06
F1B9 9AC0
F1BA 9ADC
F1BB 9B08
F1BC 9B04
F1BD 9B05
F1BE 9B29
F1BF 9B35
F1C0 9B4A
F1C1 9B4C
F1C2 9B4B
F1C3 9BC7
F1C4 9BC6
F1C5 9BC3
F1C6 9BBF
F1C7 9BC1
F1C8 9BB5
F1C9 9BB8
F1CA 9BD3
F1CB 9BB6
F1CC 9BC4
F1CD 9BB9
F1CE 9BBD
F1CF 9D5C
F1D0 9D53
F1D1 9D4F
F1D2 9D4A
F1D3 9D5B
F1D4 9D4B
F1D5 9D59
F1D6 9D56
F1D7 9D4C
F1D8 9D57
F1D9 9D52
F1DA 9D54
F1DB 9D5F
F1DC 9D58
F1DD 9D5A
F1DE 9E8E
F1DF 9E8C
F1E0 9EDF
F1E1 9F01
F1E2 9F00
F1E3 9F16
F1E4 9F25
F1E5 9F2B
F1E6 9F2A
F1E7 9F29
F1E8 9F28
F1E9 9F4C
F1EA 9F55
F1EB 5134
F1EC 5135
F1ED 5296
F1EE 52F7
F1EF 53B4
F1F0 56AB
F1F1 56AD
F1F2 56A6
F1F3 56A7
F1F4 56AA
F1F5 56AC
F1F6 58DA
F1F7 58DD
F1F8 58DB
F1F9 5912
F1FA 5B3D
F1FB 5B3E
F1FC 5B3F
F1FD 5DC3
F1FE 5E70
F240 5FBF
F241 61FB
F242 6507
F243 6510
F244 650D
F245 6509
F246 650C
F247 650E
F248 6584
F249 65DE
F24A 65DD
F24B 66DE
F24C 6AE7
F24D 6AE0
F24E 6ACC
F24F 6AD1
F250 6AD9
F251 6ACB
F252 6ADF
F253 6ADC
F254 6AD0
F255 6AEB
F256 6ACF
F257 6ACD
F258 6ADE
F259 6B60
F25A 6BB0
F25B 6C0C
F25C 7019
F25D 7027
F25E 7020
F25F 7016
F260 702B
F261 7021
F262 7022
F263 7023
F264 7029
F265 7017
F266 7024
F267 701C
F268 702A
F269 720C
F26A 720A
F26B 7207
F26C 7202
F26D 7205
F26E 72A5
F26F 72A6
F270 72A4
F271 72A3
F272 72A1
F273 74CB
F274 74C5
F275 74B7
F276 74C3
F277 7516
F278 7660
F279 77C9
F27A 77CA
F27B 77C4
F27C 77F1
F27D 791D
F27E 791B
F2A1 7921
F2A2 791C
F2A3 7917
F2A4 791E
F2A5 79B0
F2A6 7A67
F2A7 7A68
F2A8 7C33
F2A9 7C3C
F2AA 7C39
F2AB 7C2C
F2AC 7C3B
F2AD 7CEC
F2AE 7CEA
F2AF 7E76
F2B0 7E75
F2B1 7E78
F2B2 7E70
F2B3 7E77
F2B4 7E6F
F2B5 7E7A
F2B6 7E72
F2B7 7E74
F2B8 7E68
F2B9 7F4B
F2BA 7F4A
F2BB 7F83
F2BC 7F86
F2BD 7FB7
F2BE 7FFD
F2BF 7FFE
F2C0 8078
F2C1 81D7
F2C2 81D5
F2C3 8264
F2C4 8261
F2C5 8263
F2C6 85EB
F2C7 85F1
F2C8 85ED
F2C9 85D9
F2CA 85E1
F2CB 85E8
F2CC 85DA
F2CD 85D7
F2CE 85EC
F2CF 85F2
F2D0 85F8
F2D1 85D8
F2D2 85DF
F2D3 85E3
F2D4 85DC
F2D5 85D1
F2D6 85F0
F2D7 85E6
F2D8 85EF
F2D9 85DE
F2DA 85E2
F2DB 8800
F2DC 87FA
F2DD 8803
F2DE 87F6
F2DF 87F7
F2E0 8809
F2E1 880C
F2E2 880B
F2E3 8806
F2E4 87FC
F2E5 8808
F2E6 87FF
F2E7 880A
F2E8 8802
F2E9 8962
F2EA 895A
F2EB 895B
F2EC 8957
F2ED 8961
F2EE 895C
F2EF 8958
F2F0 895D
F2F1 8959
F2F2 8988
F2F3 89B7
F2F4 89B6
F2F5 89F6
F2F6 8B50
F2F7 8B48
F2F8 8B4A
F2F9 8B40
F2FA 8B53
F2FB 8B56
F2FC 8B54
F2FD 8B4B
F2FE 8B55
F340 8B51
F341 8B42
F342 8B52
F343 8B57
F344 8C43
F345 8C77
F346 8C76
F347 8C9A
F348 8D06
F349 8D07
F34A 8D09
F34B 8DAC
F34C 8DAA
F34D 8DAD
F34E 8DAB
F34F 8E6D
F350 8E78
F351 8E73
F352 8E6A
F353 8E6F
F354 8E7B
F355 8EC2
F356 8F52
F357 8F51
F358 8F4F
F359 8F50
F35A 8F53
F35B 8FB4
F35C 9140
F35D 913F
F35E 91B0
F35F 91AD
F360 93DE
F361 93C7
F362 93CF
F363 93C2
F364 93DA
F365 93D0
F366 93F9
F367 93EC
F368 93CC
F369 93D9
F36A 93A9
F36B 93E6
F36C 93CA
F36D 93D4
F36E 93EE
F36F 93E3
F370 93D5
F371 93C4
F372 93CE
F373 93C0
F374 93D2
F375 93E7
F376 957D
F377 95DA
F378 95DB
F379 96E1
F37A 9729
F37B 972B
F37C 972C
F37D 9728
F37E 9726
F3A1 97B3
F3A2 97B7
F3A3 97B6
F3A4 97DD
F3A5 97DE
F3A6 97DF
F3A7 985C
F3A8 9859
F3A9 985D
F3AA 9857
F3AB 98BF
F3AC 98BD
F3AD 98BB
F3AE 98BE
F3AF 9948
F3B0 9947
F3B1 9943
F3B2 99A6
F3B3 99A7
F3B4 9A1A
F3B5 9A15
F3B6 9A25
F3B7 9A1D
F3B8 9A24
F3B9 9A1B
F3BA 9A22
F3BB 9A20
F3BC 9A27
F3BD 9A23
F3BE 9A1E
F3BF 9A1C
F3C0 9A14
F3C1 9AC2
F3C2 9B0B
F3C3 9B0A
F3C4 9B0E
F3C5 9B0C
F3C6 9B37
F3C7 9BEA
F3C8 9BEB
F3C9 9BE0
F3CA 9BDE
F3CB 9BE4
F3CC 9BE6
F3CD 9BE2
F3CE 9BF0
F3CF 9BD4
F3D0 9BD7
F3D1 9BEC
F3D2 9BDC
F3D3 9BD9
F3D4 9BE5
F3D5 9BD5
F3D6 9BE1
F3D7 9BDA
F3D8 9D77
F3D9 9D81
F3DA 9D8A
F3DB 9D84
F3DC 9D88
F3DD 9D71
F3DE 9D80
F3DF 9D78
F3E0 9D86
F3E1 9D8B
F3E2 9D8C
F3E3 9D7D
F3E4 9D6B
F3E5 9D74
F3E6 9D75
F3E7 9D70
F3E8 9D69
F3E9 9D85
F3EA 9D73
F3EB 9D7B
F3EC 9D82
F3ED 9D6F
F3EE 9D79
F3EF 9D7F
F3F0 9D87
F3F1 9D68
F3F2 9E94
F3F3 9E91
F3F4 9EC0
F3F5 9EFC
F3F6 9F2D
F3F7 9F40
F3F8 9F41
F3F9 9F4D
F3FA 9F56
F3FB 9F57
F3FC 9F58
F3FD 5337
F3FE 56B2
F440 56B5
F441 56B3
F442 58E3
F443 5B45
F444 5DC6
F445 5DC7
F446 5EEE
F447 5EEF
F448 5FC0
F449 5FC1
F44A 61F9
F44B 6517
F44C 6516
F44D 6515
F44E 6513
F44F 65DF
F450 66E8
F451 66E3
F452 66E4
F453 6AF3
F454 6AF0
F455 6AEA
F456 6AE8
F457 6AF9
F458 6AF1
F459 6AEE
F45A 6AEF
F45B 703C
F45C 7035
F45D 702F
F45E 7037
F45F 7034
F460 7031
F461 7042
F462 7038
F463 703F
F464 703A
F465 7039
F466 7040
F467 703B
F468 7033
F469 7041
F46A 7213
F46B 7214
F46C 72A8
F46D 737D
F46E 737C
F46F 74BA
F470 76AB
F471 76AA
F472 76BE
F473 76ED
F474 77CC
F475 77CE
F476 77CF
F477 77CD
F478 77F2
F479 7925
F47A 7923
F47B 7927
F47C 7928
F47D 7924
F47E 7929
F4A1 79B2
F4A2 7A6E
F4A3 7A6C
F4A4 7A6D
F4A5 7AF7
F4A6 7C49
F4A7 7C48
F4A8 7C4A
F4A9 7C47
F4AA 7C45
F4AB 7CEE
F4AC 7E7B
F4AD 7E7E
F4AE 7E81
F4AF 7E80
F4B0 7FBA
F4B1 7FFF
F4B2 8079
F4B3 81DB
F4B4 81D9
F4B5 820B
F4B6 8268
F4B7 8269
F4B8 8622
F4B9 85FF
F4BA 8601
F4BB 85FE
F4BC 861B
F4BD 8600
F4BE 85F6
F4BF 8604
F4C0 8609
F4C1 8605
F4C2 860C
F4C3 85FD
F4C4 8819
F4C5 8810
F4C6 8811
F4C7 8817
F4C8 8813
F4C9 8816
F4CA 8963
F4CB 8966
F4CC 89B9
F4CD 89F7
F4CE 8B60
F4CF 8B6A
F4D0 8B5D
F4D1 8B68
F4D2 8B63
F4D3 8B65
F4D4 8B67
F4D5 8B6D
F4D6 8DAE
F4D7 8E86
F4D8 8E88
F4D9 8E84
F4DA 8F59
F4DB 8F56
F4DC 8F57
F4DD 8F55
F4DE 8F58
F4DF 8F5A
F4E0 908D
F4E1 9143
F4E2 9141
F4E3 91B7
F4E4 91B5
F4E5 91B2
F4E6 91B3
F4E7 940B
F4E8 9413
F4E9 93FB
F4EA 9420
F4EB 940F
F4EC 9414
F4ED 93FE
F4EE 9415
F4EF 9410
F4F0 9428
F4F1 9419
F4F2 940D
F4F3 93F5
F4F4 9400
F4F5 93F7
F4F6 9407
F4F7 940E
F4F8 9416
F4F9 9412
F4FA 93FA
F4FB 9409
F4FC 93F8
F4FD 940A
F4FE 93FF
F540 93FC
F541 940C
F542 93F6
F543 9411
F544 9406
F545 95DE
F546 95E0
F547 95DF
F548 972E
F549 972F
F54A 97B9
F54B 97BB
F54C 97FD
F54D 97FE
F54E 9860
F54F 9862
F550 9863
F551 985F
F552 98C1
F553 98C2
F554 9950
F555 994E
F556 9959
F557 994C
F558 994B
F559 9953
F55A 9A32
F55B 9A34
F55C 9A31
F55D 9A2C
F55E 9A2A
F55F 9A36
F560 9A29
F561 9A2E
F562 9A38
F563 9A2D
F564 9AC7
F565 9ACA
F566 9AC6
F567 9B10
F568 9B12
F569 9B11
F56A 9C0B
F56B 9C08
F56C 9BF7
F56D 9C05
F56E 9C12
F56F 9BF8
F570 9C40
F571 9C07
F572 9C0E
F573 9C06
F574 9C17
F575 9C14
F576 9C09
F577 9D9F
F578 9D99
F579 9DA4
F57A 9D9D
F57B 9D92
F57C 9D98
F57D 9D90
F57E 9D9B
F5A1 9DA0
F5A2 9D94
F5A3 9D9C
F5A4 9DAA
F5A5 9D97
F5A6 9DA1
F5A7 9D9A
F5A8 9DA2
F5A9 9DA8
F5AA 9D9E
F5AB 9DA3
F5AC 9DBF
F5AD 9DA9
F5AE 9D96
F5AF 9DA6
F5B0 9DA7
F5B1 9E99
F5B2 9E9B
F5B3 9E9A
F5B4 9EE5
F5B5 9EE4
F5B6 9EE7
F5B7 9EE6
F5B8 9F30
F5B9 9F2E
F5BA 9F5B
F5BB 9F60
F5BC 9F5E
F5BD 9F5D
F5BE 9F59
F5BF 9F91
F5C0 513A
F5C1 5139
F5C2 5298
F5C3 5297
F5C4 56C3
F5C5 56BD
F5C6 56BE
F5C7 5B48
F5C8 5B47
F5C9 5DCB
F5CA 5DCF
F5CB 5EF1
F5CC 61FD
F5CD 651B
F5CE 6B02
F5CF 6AFC
F5D0 6B03
F5D1 6AF8
F5D2 6B00
F5D3 7043
F5D4 7044
F5D5 704A
F5D6 7048
F5D7 7049
F5D8 7045
F5D9 7046
F5DA 721D
F5DB 721A
F5DC 7219
F5DD 737E
F5DE 7517
F5DF 766A
F5E0 77D0
F5E1 792D
F5E2 7931
F5E3 792F
F5E4 7C54
F5E5 7C53
F5E6 7CF2
F5E7 7E8A
F5E8 7E87
F5E9 7E88
F5EA 7E8B
F5EB 7E86
F5EC 7E8D
F5ED 7F4D
F5EE 7FBB
F5EF 8030
F5F0 81DD
F5F1 8618
F5F2 862A
F5F3 8626
F5F4 861F
F5F5 8623
F5F6 861C
F5F7 8619
F5F8 8627
F5F9 862E
F5FA 8621
F5FB 8620
F5FC 8629
F5FD 861E
F5FE 8625
F640 8829
F641 881D
F642 881B
F643 8820
F644 8824
F645 881C
F646 882B
F647 884A
F648 896D
F649 8969
F64A 896E
F64B 896B
F64C 89FA
F64D 8B79
F64E 8B78
F64F 8B45
F650 8B7A
F651 8B7B
F652 8D10
F653 8D14
F654 8DAF
F655 8E8E
F656 8E8C
F657 8F5E
F658 8F5B
F659 8F5D
F65A 9146
F65B 9144
F65C 9145
F65D 91B9
F65E 943F
F65F 943B
F660 9436
F661 9429
F662 943D
F663 943C
F664 9430
F665 9439
F666 942A
F667 9437
F668 942C
F669 9440
F66A 9431
F66B 95E5
F66C 95E4
F66D 95E3
F66E 9735
F66F 973A
F670 97BF
F671 97E1
F672 9864
F673 98C9
F674 98C6
F675 98C0
F676 9958
F677 9956
F678 9A39
F679 9A3D
F67A 9A46
F67B 9A44
F67C 9A42
F67D 9A41
F67E 9A3A
F6A1 9A3F
F6A2 9ACD
F6A3 9B15
F6A4 9B17
F6A5 9B18
F6A6 9B16
F6A7 9B3A
F6A8 9B52
F6A9 9C2B
F6AA 9C1D
F6AB 9C1C
F6AC 9C2C
F6AD 9C23
F6AE 9C28
F6AF 9C29
F6B0 9C24
F6B1 9C21
F6B2 9DB7
F6B3 9DB6
F6B4 9DBC
F6B5 9DC1
F6B6 9DC7
F6B7 9DCA
F6B8 9DCF
F6B9 9DBE
F6BA 9DC5
F6BB 9DC3
F6BC 9DBB
F6BD 9DB5
F6BE 9DCE
F6BF 9DB9
F6C0 9DBA
F6C1 9DAC
F6C2 9DC8
F6C3 9DB1
F6C4 9DAD
F6C5 9DCC
F6C6 9DB3
F6C7 9DCD
F6C8 9DB2
F6C9 9E7A
F6CA 9E9C
F6CB 9EEB
F6CC 9EEE
F6CD 9EED
F6CE 9F1B
F6CF 9F18
F6D0 9F1A
F6D1 9F31
F6D2 9F4E
F6D3 9F65
F6D4 9F64
F6D5 9F92
F6D6 4EB9
F6D7 56C6
F6D8 56C5
F6D9 56CB
F6DA 5971
F6DB 5B4B
F6DC 5B4C
F6DD 5DD5
F6DE 5DD1
F6DF 5EF2
F6E0 6521
F6E1 6520
F6E2 6526
F6E3 6522
F6E4 6B0B
F6E5 6B08
F6E6 6B09
F6E7 6C0D
F6E8 7055
F6E9 7056
F6EA 7057
F6EB 7052
F6EC 721E
F6ED 721F
F6EE 72A9
F6EF 737F
F6F0 74D8
F6F1 74D5
F6F2 74D9
F6F3 74D7
F6F4 766D
F6F5 76AD
F6F6 7935
F6F7 79B4
F6F8 7A70
F6F9 7A71
F6FA 7C57
F6FB 7C5C
F6FC 7C59
F6FD 7C5B
F6FE 7C5A
F740 7CF4
F741 7CF1
F742 7E91
F743 7F4F
F744 7F87
F745 81DE
F746 826B
F747 8634
F748 8635
F749 8633
F74A 862C
F74B 8632
F74C 8636
F74D 882C
F74E 8828
F74F 8826
F750 882A
F751 8825
F752 8971
F753 89BF
F754 89BE
F755 89FB
F756 8B7E
F757 8B84
F758 8B82
F759 8B86
F75A 8B85
F75B 8B7F
F75C 8D15
F75D 8E95
F75E 8E94
F75F 8E9A
F760 8E92
F761 8E90
F762 8E96
F763 8E97
F764 8F60
F765 8F62
F766 9147
F767 944C
F768 9450
F769 944A
F76A 944B
F76B 944F
F76C 9447
F76D 9445
F76E 9448
F76F 9449
F770 9446
F771 973F
F772 97E3
F773 986A
F774 9869
F775 98CB
F776 9954
F777 995B
F778 9A4E
F779 9A53
F77A 9A54
F77B 9A4C
F77C 9A4F
F77D 9A48
F77E 9A4A
F7A1 9A49
F7A2 9A52
F7A3 9A50
F7A4 9AD0
F7A5 9B19
F7A6 9B2B
F7A7 9B3B
F7A8 9B56
F7A9 9B55
F7AA 9C46
F7AB 9C48
F7AC 9C3F
F7AD 9C44
F7AE 9C39
F7AF 9C33
F7B0 9C41
F7B1 9C3C
F7B2 9C37
F7B3 9C34
F7B4 9C32
F7B5 9C3D
F7B6 9C36
F7B7 9DDB
F7B8 9DD2
F7B9 9DDE
F7BA 9DDA
F7BB 9DCB
F7BC 9DD0
F7BD 9DDC
F7BE 9DD1
F7BF 9DDF
F7C0 9DE9
F7C1 9DD9
F7C2 9DD8
F7C3 9DD6
F7C4 9DF5
F7C5 9DD5
F7C6 9DDD
F7C7 9EB6
F7C8 9EF0
F7C9 9F35
F7CA 9F33
F7CB 9F32
F7CC 9F42
F7CD 9F6B
F7CE 9F95
F7CF 9FA2
F7D0 513D
F7D1 5299
F7D2 58E8
F7D3 58E7
F7D4 5972
F7D5 5B4D
F7D6 5DD8
F7D7 882F
F7D8 5F4F
F7D9 6201
F7DA 6203
F7DB 6204
F7DC 6529
F7DD 6525
F7DE 6596
F7DF 66EB
F7E0 6B11
F7E1 6B12
F7E2 6B0F
F7E3 6BCA
F7E4 705B
F7E5 705A
F7E6 7222
F7E7 7382
F7E8 7381
F7E9 7383
F7EA 7670
F7EB 77D4
F7EC 7C67
F7ED 7C66
F7EE 7E95
F7EF 826C
F7F0 863A
F7F1 8640
F7F2 8639
F7F3 863C
F7F4 8631
F7F5 863B
F7F6 863E
F7F7 8830
F7F8 8832
F7F9 882E
F7FA 8833
F7FB 8976
F7FC 8974
F7FD 8973
F7FE 89FE
F840 8B8C
F841 8B8E
F842 8B8B
F843 8B88
F844 8C45
F845 8D19
F846 8E98
F847 8F64
F848 8F63
F849 91BC
F84A 9462
F84B 9455
F84C 945D
F84D 9457
F84E 945E
F84F 97C4
F850 97C5
F851 9800
F852 9A56
F853 9A59
F854 9B1E
F855 9B1F
F856 9B20
F857 9C52
F858 9C58
F859 9C50
F85A 9C4A
F85B 9C4D
F85C 9C4B
F85D 9C55
F85E 9C59
F85F 9C4C
F860 9C4E
F861 9DFB
F862 9DF7
F863 9DEF
F864 9DE3
F865 9DEB
F866 9DF8
F867 9DE4
F868 9DF6
F869 9DE1
F86A 9DEE
F86B 9DE6
F86C 9DF2
F86D 9DF0
F86E 9DE2
F86F 9DEC
F870 9DF4
F871 9DF3
F872 9DE8
F873 9DED
F874 9EC2
F875 9ED0
F876 9EF2
F877 9EF3
F878 9F06
F879 9F1C
F87A 9F38
F87B 9F37
F87C 9F36
F87D 9F43
F87E 9F4F
F8A1 9F71
F8A2 9F70
F8A3 9F6E
F8A4 9F6F
F8A5 56D3
F8A6 56CD
F8A7 5B4E
F8A8 5C6D
F8A9 652D
F8AA 66ED
F8AB 66EE
F8AC 6B13
F8AD 705F
F8AE 7061
F8AF 705D
F8B0 7060
F8B1 7223
F8B2 74DB
F8B3 74E5
F8B4 77D5
F8B5 7938
F8B6 79B7
F8B7 79B6
F8B8 7C6A
F8B9 7E97
F8BA 7F89
F8BB 826D
F8BC 8643
F8BD 8838
F8BE 8837
F8BF 8835
F8C0 884B
F8C1 8B94
F8C2 8B95
F8C3 8E9E
F8C4 8E9F
F8C5 8EA0
F8C6 8E9D
F8C7 91BE
F8C8 91BD
F8C9 91C2
F8CA 946B
F8CB 9468
F8CC 9469
F8CD 96E5
F8CE 9746
F8CF 9743
F8D0 9747
F8D1 97C7
F8D2 97E5
F8D3 9A5E
F8D4 9AD5
F8D5 9B59
F8D6 9C63
F8D7 9C67
F8D8 9C66
F8D9 9C62
F8DA 9C5E
F8DB 9C60
F8DC 9E02
F8DD 9DFE
F8DE 9E07
F8DF 9E03
F8E0 9E06
F8E1 9E05
F8E2 9E00
F8E3 9E01
F8E4 9E09
F8E5 9DFF
F8E6 9DFD
F8E7 9E04
F8E8 9EA0
F8E9 9F1E
F8EA 9F46
F8EB 9F74
F8EC 9F75
F8ED 9F76
F8EE 56D4
F8EF 652E
F8F0 65B8
F8F1 6B18
F8F2 6B19
F8F3 6B17
F8F4 6B1A
F8F5 7062
F8F6 7226
F8F7 72AA
F8F8 77D8
F8F9 77D9
F8FA 7939
F8FB 7C69
F8FC 7C6B
F8FD 7CF6
F8FE 7E9A
F940 7E98
F941 7E9B
F942 7E99
F943 81E0
F944 81E1
F945 8646
F946 8647
F947 8648
F948 8979
F949 897A
F94A 897C
F94B 897B
F94C 89FF
F94D 8B98
F94E 8B99
F94F 8EA5
F950 8EA4
F951 8EA3
F952 946E
F953 946D
F954 946F
F955 9471
F956 9473
F957 9749
F958 9872
F959 995F
F95A 9C68
F95B 9C6E
F95C 9C6D
F95D 9E0B
F95E 9E0D
F95F 9E10
F960 9E0F
F961 9E12
F962 9E11
F963 9EA1
F964 9EF5
F965 9F09
F966 9F47
F967 9F78
F968 9F7B
F969 9F7A
F96A 9F79
F96B 571E
F96C 7066
F96D 7C6F
F96E 883C
F96F 8DB2
F970 8EA6
F971 91C3
F972 9474
F973 9478
F974 9476
F975 9475
F976 9A60
F977 9C74
F978 9C73
F979 9C71
F97A 9C75
F97B 9E14
F97C 9E13
F97D 9EF6
F97E 9F0A
F9A1 9FA4
F9A2 7068
F9A3 7065
F9A4 7CF7
F9A5 866A
F9A6 883E
F9A7 883D
F9A8 883F
F9A9 8B9E
F9AA 8C9C
F9AB 8EA9
F9AC 8EC9
F9AD 974B
F9AE 9873
F9AF 9874
F9B0 98CC
F9B1 9961
F9B2 99AB
F9B3 9A64
F9B4 9A66
F9B5 9A67
F9B6 9B24
F9B7 9E15
F9B8 9E17
F9B9 9F48
F9BA 6207
F9BB 6B1E
F9BC 7227
F9BD 864C
F9BE 8EA8
F9BF 9482
F9C0 9480
F9C1 9481
F9C2 9A69
F9C3 9A68
F9C4 9B2E
F9C5 9E19
F9C6 7229
F9C7 864B
F9C8 8B9F
F9C9 9483
F9CA 9C79
F9CB 9EB7
F9CC 7675
F9CD 9A6B
F9CE 9C7A
F9CF 9E1D
F9D0 7069
F9D1 706A
F9D2 9EA4
F9D3 9F7E
F9D4 9F49
F9D5 9F98
| 141,327 | 13,809 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_ordered_dict.py | import builtins
import contextlib
import copy
import gc
import pickle
from random import randrange, shuffle
import struct
import sys
import unittest
import weakref
from collections.abc import MutableMapping
from test import mapping_tests, support
py_coll = support.import_fresh_module('collections', blocked=['_collections'])
c_coll = support.import_fresh_module('collections', fresh=['_collections'])
@contextlib.contextmanager
def replaced_module(name, replacement):
original_module = sys.modules[name]
sys.modules[name] = replacement
try:
yield
finally:
sys.modules[name] = original_module
class OrderedDictTests:
def test_init(self):
OrderedDict = self.OrderedDict
with self.assertRaises(TypeError):
OrderedDict([('a', 1), ('b', 2)], None) # too many args
pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
self.assertEqual(sorted(OrderedDict(dict(pairs)).items()), pairs) # dict input
self.assertEqual(sorted(OrderedDict(**dict(pairs)).items()), pairs) # kwds input
self.assertEqual(list(OrderedDict(pairs).items()), pairs) # pairs input
self.assertEqual(list(OrderedDict([('a', 1), ('b', 2), ('c', 9), ('d', 4)],
c=3, e=5).items()), pairs) # mixed input
# make sure no positional args conflict with possible kwdargs
self.assertEqual(list(OrderedDict(self=42).items()), [('self', 42)])
self.assertEqual(list(OrderedDict(other=42).items()), [('other', 42)])
self.assertRaises(TypeError, OrderedDict, 42)
self.assertRaises(TypeError, OrderedDict, (), ())
self.assertRaises(TypeError, OrderedDict.__init__)
# Make sure that direct calls to __init__ do not clear previous contents
d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)])
d.__init__([('e', 5), ('f', 6)], g=7, d=4)
self.assertEqual(list(d.items()),
[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)])
def test_468(self):
OrderedDict = self.OrderedDict
items = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]
shuffle(items)
argdict = OrderedDict(items)
d = OrderedDict(**argdict)
self.assertEqual(list(d.items()), items)
def test_update(self):
OrderedDict = self.OrderedDict
with self.assertRaises(TypeError):
OrderedDict().update([('a', 1), ('b', 2)], None) # too many args
pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
od = OrderedDict()
od.update(dict(pairs))
self.assertEqual(sorted(od.items()), pairs) # dict input
od = OrderedDict()
od.update(**dict(pairs))
self.assertEqual(sorted(od.items()), pairs) # kwds input
od = OrderedDict()
od.update(pairs)
self.assertEqual(list(od.items()), pairs) # pairs input
od = OrderedDict()
od.update([('a', 1), ('b', 2), ('c', 9), ('d', 4)], c=3, e=5)
self.assertEqual(list(od.items()), pairs) # mixed input
# Issue 9137: Named argument called 'other' or 'self'
# shouldn't be treated specially.
od = OrderedDict()
od.update(self=23)
self.assertEqual(list(od.items()), [('self', 23)])
od = OrderedDict()
od.update(other={})
self.assertEqual(list(od.items()), [('other', {})])
od = OrderedDict()
od.update(red=5, blue=6, other=7, self=8)
self.assertEqual(sorted(list(od.items())),
[('blue', 6), ('other', 7), ('red', 5), ('self', 8)])
# Make sure that direct calls to update do not clear previous contents
# add that updates items are not moved to the end
d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)])
d.update([('e', 5), ('f', 6)], g=7, d=4)
self.assertEqual(list(d.items()),
[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)])
self.assertRaises(TypeError, OrderedDict().update, 42)
self.assertRaises(TypeError, OrderedDict().update, (), ())
self.assertRaises(TypeError, OrderedDict.update)
self.assertRaises(TypeError, OrderedDict().update, 42)
self.assertRaises(TypeError, OrderedDict().update, (), ())
self.assertRaises(TypeError, OrderedDict.update)
def test_init_calls(self):
calls = []
class Spam:
def keys(self):
calls.append('keys')
return ()
def items(self):
calls.append('items')
return ()
self.OrderedDict(Spam())
self.assertEqual(calls, ['keys'])
def test_fromkeys(self):
OrderedDict = self.OrderedDict
od = OrderedDict.fromkeys('abc')
self.assertEqual(list(od.items()), [(c, None) for c in 'abc'])
od = OrderedDict.fromkeys('abc', value=None)
self.assertEqual(list(od.items()), [(c, None) for c in 'abc'])
od = OrderedDict.fromkeys('abc', value=0)
self.assertEqual(list(od.items()), [(c, 0) for c in 'abc'])
def test_abc(self):
OrderedDict = self.OrderedDict
self.assertIsInstance(OrderedDict(), MutableMapping)
self.assertTrue(issubclass(OrderedDict, MutableMapping))
def test_clear(self):
OrderedDict = self.OrderedDict
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
shuffle(pairs)
od = OrderedDict(pairs)
self.assertEqual(len(od), len(pairs))
od.clear()
self.assertEqual(len(od), 0)
def test_delitem(self):
OrderedDict = self.OrderedDict
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
od = OrderedDict(pairs)
del od['a']
self.assertNotIn('a', od)
with self.assertRaises(KeyError):
del od['a']
self.assertEqual(list(od.items()), pairs[:2] + pairs[3:])
def test_setitem(self):
OrderedDict = self.OrderedDict
od = OrderedDict([('d', 1), ('b', 2), ('c', 3), ('a', 4), ('e', 5)])
od['c'] = 10 # existing element
od['f'] = 20 # new element
self.assertEqual(list(od.items()),
[('d', 1), ('b', 2), ('c', 10), ('a', 4), ('e', 5), ('f', 20)])
def test_iterators(self):
OrderedDict = self.OrderedDict
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
shuffle(pairs)
od = OrderedDict(pairs)
self.assertEqual(list(od), [t[0] for t in pairs])
self.assertEqual(list(od.keys()), [t[0] for t in pairs])
self.assertEqual(list(od.values()), [t[1] for t in pairs])
self.assertEqual(list(od.items()), pairs)
self.assertEqual(list(reversed(od)),
[t[0] for t in reversed(pairs)])
self.assertEqual(list(reversed(od.keys())),
[t[0] for t in reversed(pairs)])
self.assertEqual(list(reversed(od.values())),
[t[1] for t in reversed(pairs)])
self.assertEqual(list(reversed(od.items())), list(reversed(pairs)))
def test_detect_deletion_during_iteration(self):
OrderedDict = self.OrderedDict
od = OrderedDict.fromkeys('abc')
it = iter(od)
key = next(it)
del od[key]
with self.assertRaises(Exception):
# Note, the exact exception raised is not guaranteed
# The only guarantee that the next() will not succeed
next(it)
def test_sorted_iterators(self):
OrderedDict = self.OrderedDict
with self.assertRaises(TypeError):
OrderedDict([('a', 1), ('b', 2)], None)
pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
od = OrderedDict(pairs)
self.assertEqual(sorted(od), [t[0] for t in pairs])
self.assertEqual(sorted(od.keys()), [t[0] for t in pairs])
self.assertEqual(sorted(od.values()), [t[1] for t in pairs])
self.assertEqual(sorted(od.items()), pairs)
self.assertEqual(sorted(reversed(od)),
sorted([t[0] for t in reversed(pairs)]))
def test_iterators_empty(self):
OrderedDict = self.OrderedDict
od = OrderedDict()
empty = []
self.assertEqual(list(od), empty)
self.assertEqual(list(od.keys()), empty)
self.assertEqual(list(od.values()), empty)
self.assertEqual(list(od.items()), empty)
self.assertEqual(list(reversed(od)), empty)
self.assertEqual(list(reversed(od.keys())), empty)
self.assertEqual(list(reversed(od.values())), empty)
self.assertEqual(list(reversed(od.items())), empty)
def test_popitem(self):
OrderedDict = self.OrderedDict
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
shuffle(pairs)
od = OrderedDict(pairs)
while pairs:
self.assertEqual(od.popitem(), pairs.pop())
with self.assertRaises(KeyError):
od.popitem()
self.assertEqual(len(od), 0)
def test_popitem_last(self):
OrderedDict = self.OrderedDict
pairs = [(i, i) for i in range(30)]
obj = OrderedDict(pairs)
for i in range(8):
obj.popitem(True)
obj.popitem(True)
obj.popitem(last=True)
self.assertEqual(len(obj), 20)
def test_pop(self):
OrderedDict = self.OrderedDict
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
shuffle(pairs)
od = OrderedDict(pairs)
shuffle(pairs)
while pairs:
k, v = pairs.pop()
self.assertEqual(od.pop(k), v)
with self.assertRaises(KeyError):
od.pop('xyz')
self.assertEqual(len(od), 0)
self.assertEqual(od.pop(k, 12345), 12345)
# make sure pop still works when __missing__ is defined
class Missing(OrderedDict):
def __missing__(self, key):
return 0
m = Missing(a=1)
self.assertEqual(m.pop('b', 5), 5)
self.assertEqual(m.pop('a', 6), 1)
self.assertEqual(m.pop('a', 6), 6)
self.assertEqual(m.pop('a', default=6), 6)
with self.assertRaises(KeyError):
m.pop('a')
def test_equality(self):
OrderedDict = self.OrderedDict
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
shuffle(pairs)
od1 = OrderedDict(pairs)
od2 = OrderedDict(pairs)
self.assertEqual(od1, od2) # same order implies equality
pairs = pairs[2:] + pairs[:2]
od2 = OrderedDict(pairs)
self.assertNotEqual(od1, od2) # different order implies inequality
# comparison to regular dict is not order sensitive
self.assertEqual(od1, dict(od2))
self.assertEqual(dict(od2), od1)
# different length implied inequality
self.assertNotEqual(od1, OrderedDict(pairs[:-1]))
def test_copying(self):
OrderedDict = self.OrderedDict
# Check that ordered dicts are copyable, deepcopyable, picklable,
# and have a repr/eval round-trip
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
od = OrderedDict(pairs)
def check(dup):
msg = "\ncopy: %s\nod: %s" % (dup, od)
self.assertIsNot(dup, od, msg)
self.assertEqual(dup, od)
self.assertEqual(list(dup.items()), list(od.items()))
self.assertEqual(len(dup), len(od))
self.assertEqual(type(dup), type(od))
check(od.copy())
check(copy.copy(od))
check(copy.deepcopy(od))
# pickle directly pulls the module, so we have to fake it
with replaced_module('collections', self.module):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
with self.subTest(proto=proto):
check(pickle.loads(pickle.dumps(od, proto)))
check(eval(repr(od)))
update_test = OrderedDict()
update_test.update(od)
check(update_test)
check(OrderedDict(od))
def test_yaml_linkage(self):
OrderedDict = self.OrderedDict
# Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature.
# In yaml, lists are native but tuples are not.
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
od = OrderedDict(pairs)
# yaml.dump(od) -->
# '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n - [b, 2]\n'
self.assertTrue(all(type(pair)==list for pair in od.__reduce__()[1]))
def test_reduce_not_too_fat(self):
OrderedDict = self.OrderedDict
# do not save instance dictionary if not needed
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
od = OrderedDict(pairs)
self.assertIsInstance(od.__dict__, dict)
self.assertIsNone(od.__reduce__()[2])
od.x = 10
self.assertEqual(od.__dict__['x'], 10)
self.assertEqual(od.__reduce__()[2], {'x': 10})
def test_pickle_recursive(self):
OrderedDict = self.OrderedDict
od = OrderedDict()
od[1] = od
# pickle directly pulls the module, so we have to fake it
with replaced_module('collections', self.module):
for proto in range(-1, pickle.HIGHEST_PROTOCOL + 1):
dup = pickle.loads(pickle.dumps(od, proto))
self.assertIsNot(dup, od)
self.assertEqual(list(dup.keys()), [1])
self.assertIs(dup[1], dup)
def test_repr(self):
OrderedDict = self.OrderedDict
od = OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])
self.assertEqual(repr(od),
"OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])")
self.assertEqual(eval(repr(od)), od)
self.assertEqual(repr(OrderedDict()), "OrderedDict()")
def test_repr_recursive(self):
OrderedDict = self.OrderedDict
# See issue #9826
od = OrderedDict.fromkeys('abc')
od['x'] = od
self.assertEqual(repr(od),
"OrderedDict([('a', None), ('b', None), ('c', None), ('x', ...)])")
def test_repr_recursive_values(self):
OrderedDict = self.OrderedDict
od = OrderedDict()
od[42] = od.values()
r = repr(od)
# Cannot perform a stronger test, as the contents of the repr
# are implementation-dependent. All we can say is that we
# want a str result, not an exception of any sort.
self.assertIsInstance(r, str)
od[42] = od.items()
r = repr(od)
# Again.
self.assertIsInstance(r, str)
def test_setdefault(self):
OrderedDict = self.OrderedDict
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
shuffle(pairs)
od = OrderedDict(pairs)
pair_order = list(od.items())
self.assertEqual(od.setdefault('a', 10), 3)
# make sure order didn't change
self.assertEqual(list(od.items()), pair_order)
self.assertEqual(od.setdefault('x', 10), 10)
# make sure 'x' is added to the end
self.assertEqual(list(od.items())[-1], ('x', 10))
self.assertEqual(od.setdefault('g', default=9), 9)
# make sure setdefault still works when __missing__ is defined
class Missing(OrderedDict):
def __missing__(self, key):
return 0
self.assertEqual(Missing().setdefault(5, 9), 9)
def test_reinsert(self):
OrderedDict = self.OrderedDict
# Given insert a, insert b, delete a, re-insert a,
# verify that a is now later than b.
od = OrderedDict()
od['a'] = 1
od['b'] = 2
del od['a']
self.assertEqual(list(od.items()), [('b', 2)])
od['a'] = 1
self.assertEqual(list(od.items()), [('b', 2), ('a', 1)])
def test_move_to_end(self):
OrderedDict = self.OrderedDict
od = OrderedDict.fromkeys('abcde')
self.assertEqual(list(od), list('abcde'))
od.move_to_end('c')
self.assertEqual(list(od), list('abdec'))
od.move_to_end('c', 0)
self.assertEqual(list(od), list('cabde'))
od.move_to_end('c', 0)
self.assertEqual(list(od), list('cabde'))
od.move_to_end('e')
self.assertEqual(list(od), list('cabde'))
od.move_to_end('b', last=False)
self.assertEqual(list(od), list('bcade'))
with self.assertRaises(KeyError):
od.move_to_end('x')
with self.assertRaises(KeyError):
od.move_to_end('x', 0)
def test_move_to_end_issue25406(self):
OrderedDict = self.OrderedDict
od = OrderedDict.fromkeys('abc')
od.move_to_end('c', last=False)
self.assertEqual(list(od), list('cab'))
od.move_to_end('a', last=False)
self.assertEqual(list(od), list('acb'))
od = OrderedDict.fromkeys('abc')
od.move_to_end('a')
self.assertEqual(list(od), list('bca'))
od.move_to_end('c')
self.assertEqual(list(od), list('bac'))
def test_sizeof(self):
OrderedDict = self.OrderedDict
# Wimpy test: Just verify the reported size is larger than a regular dict
d = dict(a=1)
od = OrderedDict(**d)
self.assertGreater(sys.getsizeof(od), sys.getsizeof(d))
def test_views(self):
OrderedDict = self.OrderedDict
# See http://bugs.python.org/issue24286
s = 'the quick brown fox jumped over a lazy dog yesterday before dawn'.split()
od = OrderedDict.fromkeys(s)
self.assertEqual(od.keys(), dict(od).keys())
self.assertEqual(od.items(), dict(od).items())
def test_override_update(self):
OrderedDict = self.OrderedDict
# Verify that subclasses can override update() without breaking __init__()
class MyOD(OrderedDict):
def update(self, *args, **kwds):
raise Exception()
items = [('a', 1), ('c', 3), ('b', 2)]
self.assertEqual(list(MyOD(items).items()), items)
def test_highly_nested(self):
# Issue 25395: crashes during garbage collection
OrderedDict = self.OrderedDict
obj = None
for _ in range(1000):
obj = OrderedDict([(None, obj)])
del obj
support.gc_collect()
def test_highly_nested_subclass(self):
# Issue 25395: crashes during garbage collection
OrderedDict = self.OrderedDict
deleted = []
class MyOD(OrderedDict):
def __del__(self):
deleted.append(self.i)
obj = None
for i in range(100):
obj = MyOD([(None, obj)])
obj.i = i
del obj
support.gc_collect()
self.assertEqual(deleted, list(reversed(range(100))))
def test_delitem_hash_collision(self):
OrderedDict = self.OrderedDict
class Key:
def __init__(self, hash):
self._hash = hash
self.value = str(id(self))
def __hash__(self):
return self._hash
def __eq__(self, other):
try:
return self.value == other.value
except AttributeError:
return False
def __repr__(self):
return self.value
def blocking_hash(hash):
# See the collision-handling in lookdict (in Objects/dictobject.c).
MINSIZE = 8
i = (hash & MINSIZE-1)
return (i << 2) + i + hash + 1
COLLIDING = 1
key = Key(COLLIDING)
colliding = Key(COLLIDING)
blocking = Key(blocking_hash(COLLIDING))
od = OrderedDict()
od[key] = ...
od[blocking] = ...
od[colliding] = ...
od['after'] = ...
del od[blocking]
del od[colliding]
self.assertEqual(list(od.items()), [(key, ...), ('after', ...)])
def test_issue24347(self):
OrderedDict = self.OrderedDict
class Key:
def __hash__(self):
return randrange(100000)
od = OrderedDict()
for i in range(100):
key = Key()
od[key] = i
# These should not crash.
with self.assertRaises(KeyError):
list(od.values())
with self.assertRaises(KeyError):
list(od.items())
with self.assertRaises(KeyError):
repr(od)
with self.assertRaises(KeyError):
od.copy()
def test_issue24348(self):
OrderedDict = self.OrderedDict
class Key:
def __hash__(self):
return 1
od = OrderedDict()
od[Key()] = 0
# This should not crash.
od.popitem()
def test_issue24667(self):
"""
dict resizes after a certain number of insertion operations,
whether or not there were deletions that freed up slots in the
hash table. During fast node lookup, OrderedDict must correctly
respond to all resizes, even if the current "size" is the same
as the old one. We verify that here by forcing a dict resize
on a sparse odict and then perform an operation that should
trigger an odict resize (e.g. popitem). One key aspect here is
that we will keep the size of the odict the same at each popitem
call. This verifies that we handled the dict resize properly.
"""
OrderedDict = self.OrderedDict
od = OrderedDict()
for c0 in '0123456789ABCDEF':
for c1 in '0123456789ABCDEF':
if len(od) == 4:
# This should not raise a KeyError.
od.popitem(last=False)
key = c0 + c1
od[key] = key
# Direct use of dict methods
def test_dict_setitem(self):
OrderedDict = self.OrderedDict
od = OrderedDict()
dict.__setitem__(od, 'spam', 1)
self.assertNotIn('NULL', repr(od))
def test_dict_delitem(self):
OrderedDict = self.OrderedDict
od = OrderedDict()
od['spam'] = 1
od['ham'] = 2
dict.__delitem__(od, 'spam')
with self.assertRaises(KeyError):
repr(od)
def test_dict_clear(self):
OrderedDict = self.OrderedDict
od = OrderedDict()
od['spam'] = 1
od['ham'] = 2
dict.clear(od)
self.assertNotIn('NULL', repr(od))
def test_dict_pop(self):
OrderedDict = self.OrderedDict
od = OrderedDict()
od['spam'] = 1
od['ham'] = 2
dict.pop(od, 'spam')
with self.assertRaises(KeyError):
repr(od)
def test_dict_popitem(self):
OrderedDict = self.OrderedDict
od = OrderedDict()
od['spam'] = 1
od['ham'] = 2
dict.popitem(od)
with self.assertRaises(KeyError):
repr(od)
def test_dict_setdefault(self):
OrderedDict = self.OrderedDict
od = OrderedDict()
dict.setdefault(od, 'spam', 1)
self.assertNotIn('NULL', repr(od))
def test_dict_update(self):
OrderedDict = self.OrderedDict
od = OrderedDict()
dict.update(od, [('spam', 1)])
self.assertNotIn('NULL', repr(od))
def test_reference_loop(self):
# Issue 25935
OrderedDict = self.OrderedDict
class A:
od = OrderedDict()
A.od[A] = None
r = weakref.ref(A)
del A
gc.collect()
self.assertIsNone(r())
def test_free_after_iterating(self):
support.check_free_after_iterating(self, iter, self.OrderedDict)
support.check_free_after_iterating(self, lambda d: iter(d.keys()), self.OrderedDict)
support.check_free_after_iterating(self, lambda d: iter(d.values()), self.OrderedDict)
support.check_free_after_iterating(self, lambda d: iter(d.items()), self.OrderedDict)
@unittest.skipIf(c_coll, "skip pure-python test if C impl is present")
class PurePythonOrderedDictTests(OrderedDictTests, unittest.TestCase):
module = py_coll
OrderedDict = py_coll.OrderedDict
class CPythonBuiltinDictTests(unittest.TestCase):
"""Builtin dict preserves insertion order.
Reuse some of tests in OrderedDict selectively.
"""
module = builtins
OrderedDict = dict
for method in (
"test_init test_update test_abc test_clear test_delitem " +
"test_setitem test_detect_deletion_during_iteration " +
"test_popitem test_reinsert test_override_update " +
"test_highly_nested test_highly_nested_subclass " +
"test_delitem_hash_collision ").split():
setattr(CPythonBuiltinDictTests, method, getattr(OrderedDictTests, method))
del method
@unittest.skipUnless(c_coll, 'requires the C version of the collections module')
class CPythonOrderedDictTests(OrderedDictTests, unittest.TestCase):
module = c_coll
OrderedDict = c_coll.OrderedDict
check_sizeof = support.check_sizeof
@support.cpython_only
def test_sizeof_exact(self):
OrderedDict = self.OrderedDict
calcsize = struct.calcsize
size = support.calcobjsize
check = self.check_sizeof
basicsize = size('nQ2P' + '3PnPn2P') + calcsize('2nP2n')
entrysize = calcsize('n2P')
p = calcsize('P')
nodesize = calcsize('Pn2P')
od = OrderedDict()
check(od, basicsize + 8 + 5*entrysize) # 8byte indices + 8*2//3 * entry table
od.x = 1
check(od, basicsize + 8 + 5*entrysize)
od.update([(i, i) for i in range(3)])
check(od, basicsize + 8*p + 8 + 5*entrysize + 3*nodesize)
od.update([(i, i) for i in range(3, 10)])
check(od, basicsize + 16*p + 16 + 10*entrysize + 10*nodesize)
check(od.keys(), size('P'))
check(od.items(), size('P'))
check(od.values(), size('P'))
itersize = size('iP2n2P')
check(iter(od), itersize)
check(iter(od.keys()), itersize)
check(iter(od.items()), itersize)
check(iter(od.values()), itersize)
def test_key_change_during_iteration(self):
OrderedDict = self.OrderedDict
od = OrderedDict.fromkeys('abcde')
self.assertEqual(list(od), list('abcde'))
with self.assertRaises(RuntimeError):
for i, k in enumerate(od):
od.move_to_end(k)
self.assertLess(i, 5)
with self.assertRaises(RuntimeError):
for k in od:
od['f'] = None
with self.assertRaises(RuntimeError):
for k in od:
del od['c']
self.assertEqual(list(od), list('bdeaf'))
def test_iterators_pickling(self):
OrderedDict = self.OrderedDict
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
od = OrderedDict(pairs)
for method_name in ('keys', 'values', 'items'):
meth = getattr(od, method_name)
expected = list(meth())[1:]
for i in range(pickle.HIGHEST_PROTOCOL + 1):
with self.subTest(method_name=method_name, protocol=i):
it = iter(meth())
next(it)
p = pickle.dumps(it, i)
unpickled = pickle.loads(p)
self.assertEqual(list(unpickled), expected)
self.assertEqual(list(it), expected)
@unittest.skipIf(c_coll, "skip pure-python test if C impl is present")
class PurePythonOrderedDictSubclassTests(PurePythonOrderedDictTests):
module = py_coll
class OrderedDict(py_coll.OrderedDict):
pass
class CPythonOrderedDictSubclassTests(CPythonOrderedDictTests):
module = c_coll
class OrderedDict(c_coll.OrderedDict):
pass
@unittest.skipIf(c_coll, "skip pure-python test if C impl is present")
class PurePythonGeneralMappingTests(mapping_tests.BasicTestMappingProtocol):
@classmethod
def setUpClass(cls):
cls.type2test = py_coll.OrderedDict
def test_popitem(self):
d = self._empty_mapping()
self.assertRaises(KeyError, d.popitem)
@unittest.skipUnless(c_coll, 'requires the C version of the collections module')
class CPythonGeneralMappingTests(mapping_tests.BasicTestMappingProtocol):
@classmethod
def setUpClass(cls):
cls.type2test = c_coll.OrderedDict
def test_popitem(self):
d = self._empty_mapping()
self.assertRaises(KeyError, d.popitem)
@unittest.skipIf(c_coll, "skip pure-python test if C impl is present")
class PurePythonSubclassMappingTests(mapping_tests.BasicTestMappingProtocol):
@classmethod
def setUpClass(cls):
class MyOrderedDict(py_coll.OrderedDict):
pass
cls.type2test = MyOrderedDict
def test_popitem(self):
d = self._empty_mapping()
self.assertRaises(KeyError, d.popitem)
@unittest.skipUnless(c_coll, 'requires the C version of the collections module')
class CPythonSubclassMappingTests(mapping_tests.BasicTestMappingProtocol):
@classmethod
def setUpClass(cls):
class MyOrderedDict(c_coll.OrderedDict):
pass
cls.type2test = MyOrderedDict
def test_popitem(self):
d = self._empty_mapping()
self.assertRaises(KeyError, d.popitem)
if __name__ == "__main__":
unittest.main()
| 29,916 | 823 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_gzip.py | """Test script for the gzip module.
"""
import array
import functools
import io
import os
import pathlib
import struct
import sys
import unittest
from encodings import utf_16
from subprocess import PIPE, Popen
from test import support
from test.support import _4G, bigmemtest
from test.support.script_helper import assert_python_ok
gzip = support.import_module('gzip')
if __name__ == 'PYOBJ.COM': import gzip
data1 = b""" int length=DEFAULTALLOC, err = Z_OK;
PyObject *RetVal;
int flushmode = Z_FINISH;
unsigned long start_total_out;
"""
data2 = b"""/* zlibmodule.c -- gzip-compatible data compression */
/* See http://www.gzip.org/zlib/
/* See http://www.winimage.com/zLibDll for Windows */
"""
TEMPDIR = os.path.abspath(support.TESTFN) + '-gzdir'
class UnseekableIO(io.BytesIO):
def seekable(self):
return False
def tell(self):
raise io.UnsupportedOperation
def seek(self, *args):
raise io.UnsupportedOperation
class BaseTest(unittest.TestCase):
filename = support.TESTFN
def setUp(self):
support.unlink(self.filename)
def tearDown(self):
support.unlink(self.filename)
class TestGzip(BaseTest):
def write_and_read_back(self, data, mode='b'):
b_data = bytes(data)
with gzip.GzipFile(self.filename, 'w'+mode) as f:
l = f.write(data)
self.assertEqual(l, len(b_data))
with gzip.GzipFile(self.filename, 'r'+mode) as f:
self.assertEqual(f.read(), b_data)
def test_write(self):
with gzip.GzipFile(self.filename, 'wb') as f:
f.write(data1 * 50)
# Try flush and fileno.
f.flush()
f.fileno()
# TODO(jart): Why does this need fsync()?
#if hasattr(os, 'fsync'):
# os.fsync(f.fileno())
f.close()
# Test multiple close() calls.
f.close()
def test_write_read_with_pathlike_file(self):
filename = pathlib.Path(self.filename)
with gzip.GzipFile(filename, 'w') as f:
f.write(data1 * 50)
self.assertIsInstance(f.name, str)
with gzip.GzipFile(filename, 'a') as f:
f.write(data1)
with gzip.GzipFile(filename) as f:
d = f.read()
self.assertEqual(d, data1 * 51)
self.assertIsInstance(f.name, str)
# The following test_write_xy methods test that write accepts
# the corresponding bytes-like object type as input
# and that the data written equals bytes(xy) in all cases.
def test_write_memoryview(self):
self.write_and_read_back(memoryview(data1 * 50))
m = memoryview(bytes(range(256)))
data = m.cast('B', shape=[8,8,4])
self.write_and_read_back(data)
def test_write_bytearray(self):
self.write_and_read_back(bytearray(data1 * 50))
def test_write_array(self):
self.write_and_read_back(array.array('I', data1 * 40))
def test_write_incompatible_type(self):
# Test that non-bytes-like types raise TypeError.
# Issue #21560: attempts to write incompatible types
# should not affect the state of the fileobject
with gzip.GzipFile(self.filename, 'wb') as f:
with self.assertRaises(TypeError):
f.write('')
with self.assertRaises(TypeError):
f.write([])
f.write(data1)
with gzip.GzipFile(self.filename, 'rb') as f:
self.assertEqual(f.read(), data1)
def test_read(self):
self.test_write()
# Try reading.
with gzip.GzipFile(self.filename, 'r') as f:
d = f.read()
self.assertEqual(d, data1*50)
def test_read1(self):
self.test_write()
blocks = []
nread = 0
with gzip.GzipFile(self.filename, 'r') as f:
while True:
d = f.read1()
if not d:
break
blocks.append(d)
nread += len(d)
# Check that position was updated correctly (see issue10791).
self.assertEqual(f.tell(), nread)
self.assertEqual(b''.join(blocks), data1 * 50)
@bigmemtest(size=_4G, memuse=1)
def test_read_large(self, size):
# Read chunk size over UINT_MAX should be supported, despite zlib's
# limitation per low-level call
compressed = gzip.compress(data1, compresslevel=1)
f = gzip.GzipFile(fileobj=io.BytesIO(compressed), mode='rb')
self.assertEqual(f.read(size), data1)
def test_io_on_closed_object(self):
# Test that I/O operations on closed GzipFile objects raise a
# ValueError, just like the corresponding functions on file objects.
# Write to a file, open it for reading, then close it.
self.test_write()
f = gzip.GzipFile(self.filename, 'r')
fileobj = f.fileobj
self.assertFalse(fileobj.closed)
f.close()
self.assertTrue(fileobj.closed)
with self.assertRaises(ValueError):
f.read(1)
with self.assertRaises(ValueError):
f.seek(0)
with self.assertRaises(ValueError):
f.tell()
# Open the file for writing, then close it.
f = gzip.GzipFile(self.filename, 'w')
fileobj = f.fileobj
self.assertFalse(fileobj.closed)
f.close()
self.assertTrue(fileobj.closed)
with self.assertRaises(ValueError):
f.write(b'')
with self.assertRaises(ValueError):
f.flush()
def test_append(self):
self.test_write()
# Append to the previous file
with gzip.GzipFile(self.filename, 'ab') as f:
f.write(data2 * 15)
with gzip.GzipFile(self.filename, 'rb') as f:
d = f.read()
self.assertEqual(d, (data1*50) + (data2*15))
def test_many_append(self):
# Bug #1074261 was triggered when reading a file that contained
# many, many members. Create such a file and verify that reading it
# works.
with gzip.GzipFile(self.filename, 'wb', 9) as f:
f.write(b'a')
for i in range(0, 200):
with gzip.GzipFile(self.filename, "ab", 9) as f: # append
f.write(b'a')
# Try reading the file
with gzip.GzipFile(self.filename, "rb") as zgfile:
contents = b""
while 1:
ztxt = zgfile.read(8192)
contents += ztxt
if not ztxt: break
self.assertEqual(contents, b'a'*201)
def test_exclusive_write(self):
with gzip.GzipFile(self.filename, 'xb') as f:
f.write(data1 * 50)
with gzip.GzipFile(self.filename, 'rb') as f:
self.assertEqual(f.read(), data1 * 50)
with self.assertRaises(FileExistsError):
gzip.GzipFile(self.filename, 'xb')
def test_buffered_reader(self):
# Issue #7471: a GzipFile can be wrapped in a BufferedReader for
# performance.
self.test_write()
with gzip.GzipFile(self.filename, 'rb') as f:
with io.BufferedReader(f) as r:
lines = [line for line in r]
self.assertEqual(lines, 50 * data1.splitlines(keepends=True))
def test_readline(self):
self.test_write()
# Try .readline() with varying line lengths
with gzip.GzipFile(self.filename, 'rb') as f:
line_length = 0
while 1:
L = f.readline(line_length)
if not L and line_length != 0: break
self.assertTrue(len(L) <= line_length)
line_length = (line_length + 1) % 50
def test_readlines(self):
self.test_write()
# Try .readlines()
with gzip.GzipFile(self.filename, 'rb') as f:
L = f.readlines()
with gzip.GzipFile(self.filename, 'rb') as f:
while 1:
L = f.readlines(150)
if L == []: break
def test_seek_read(self):
self.test_write()
# Try seek, read test
with gzip.GzipFile(self.filename) as f:
while 1:
oldpos = f.tell()
line1 = f.readline()
if not line1: break
newpos = f.tell()
f.seek(oldpos) # negative seek
if len(line1)>10:
amount = 10
else:
amount = len(line1)
line2 = f.read(amount)
self.assertEqual(line1[:amount], line2)
f.seek(newpos) # positive seek
def test_seek_whence(self):
self.test_write()
# Try seek(whence=1), read test
with gzip.GzipFile(self.filename) as f:
f.read(10)
f.seek(10, whence=1)
y = f.read(10)
self.assertEqual(y, data1[20:30])
def test_seek_write(self):
# Try seek, write test
with gzip.GzipFile(self.filename, 'w') as f:
for pos in range(0, 256, 16):
f.seek(pos)
f.write(b'GZ\n')
def test_mode(self):
self.test_write()
with gzip.GzipFile(self.filename, 'r') as f:
self.assertEqual(f.myfileobj.mode, 'rb')
support.unlink(self.filename)
with gzip.GzipFile(self.filename, 'x') as f:
self.assertEqual(f.myfileobj.mode, 'xb')
def test_1647484(self):
for mode in ('wb', 'rb'):
with gzip.GzipFile(self.filename, mode) as f:
self.assertTrue(hasattr(f, "name"))
self.assertEqual(f.name, self.filename)
def test_paddedfile_getattr(self):
self.test_write()
with gzip.GzipFile(self.filename, 'rb') as f:
self.assertTrue(hasattr(f.fileobj, "name"))
self.assertEqual(f.fileobj.name, self.filename)
def test_mtime(self):
mtime = 123456789
with gzip.GzipFile(self.filename, 'w', mtime = mtime) as fWrite:
fWrite.write(data1)
with gzip.GzipFile(self.filename) as fRead:
self.assertTrue(hasattr(fRead, 'mtime'))
self.assertIsNone(fRead.mtime)
dataRead = fRead.read()
self.assertEqual(dataRead, data1)
self.assertEqual(fRead.mtime, mtime)
def test_metadata(self):
mtime = 123456789
with gzip.GzipFile(self.filename, 'w', mtime = mtime) as fWrite:
fWrite.write(data1)
with open(self.filename, 'rb') as fRead:
# see RFC 1952: http://www.faqs.org/rfcs/rfc1952.html
idBytes = fRead.read(2)
self.assertEqual(idBytes, b'\x1f\x8b') # gzip ID
cmByte = fRead.read(1)
self.assertEqual(cmByte, b'\x08') # deflate
flagsByte = fRead.read(1)
self.assertEqual(flagsByte, b'\x08') # only the FNAME flag is set
mtimeBytes = fRead.read(4)
self.assertEqual(mtimeBytes, struct.pack('<i', mtime)) # little-endian
xflByte = fRead.read(1)
self.assertEqual(xflByte, b'\x02') # maximum compression
osByte = fRead.read(1)
self.assertEqual(osByte, b'\xff') # OS "unknown" (OS-independent)
# [jart] todo wut
# # Since the FNAME flag is set, the zero-terminated filename follows.
# # RFC 1952 specifies that this is the name of the input file, if any.
# # However, the gzip module defaults to storing the name of the output
# # file in this field.
# expected = self.filename.encode('Latin-1') + b'\x00'
# nameBytes = fRead.read(len(expected))
# self.assertEqual(nameBytes, expected)
# Since no other flags were set, the header ends here.
# Rather than process the compressed data, let's seek to the trailer.
fRead.seek(os.stat(self.filename).st_size - 8)
crc32Bytes = fRead.read(4) # CRC32 of uncompressed data [data1]
self.assertEqual(crc32Bytes, b'\xaf\xd7d\x83')
isizeBytes = fRead.read(4)
self.assertEqual(isizeBytes, struct.pack('<i', len(data1)))
def test_with_open(self):
# GzipFile supports the context management protocol
with gzip.GzipFile(self.filename, "wb") as f:
f.write(b"xxx")
f = gzip.GzipFile(self.filename, "rb")
f.close()
try:
with f:
pass
except ValueError:
pass
else:
self.fail("__enter__ on a closed file didn't raise an exception")
try:
with gzip.GzipFile(self.filename, "wb") as f:
1/0
except ZeroDivisionError:
pass
else:
self.fail("1/0 didn't raise an exception")
def test_zero_padded_file(self):
with gzip.GzipFile(self.filename, "wb") as f:
f.write(data1 * 50)
# Pad the file with zeroes
with open(self.filename, "ab") as f:
f.write(b"\x00" * 50)
with gzip.GzipFile(self.filename, "rb") as f:
d = f.read()
self.assertEqual(d, data1 * 50, "Incorrect data in file")
def test_non_seekable_file(self):
uncompressed = data1 * 50
buf = UnseekableIO()
with gzip.GzipFile(fileobj=buf, mode="wb") as f:
f.write(uncompressed)
compressed = buf.getvalue()
buf = UnseekableIO(compressed)
with gzip.GzipFile(fileobj=buf, mode="rb") as f:
self.assertEqual(f.read(), uncompressed)
def test_peek(self):
uncompressed = data1 * 200
with gzip.GzipFile(self.filename, "wb") as f:
f.write(uncompressed)
def sizes():
while True:
for n in range(5, 50, 10):
yield n
with gzip.GzipFile(self.filename, "rb") as f:
f.max_read_chunk = 33
nread = 0
for n in sizes():
s = f.peek(n)
if s == b'':
break
self.assertEqual(f.read(len(s)), s)
nread += len(s)
self.assertEqual(f.read(100), b'')
self.assertEqual(nread, len(uncompressed))
def test_textio_readlines(self):
# Issue #10791: TextIOWrapper.readlines() fails when wrapping GzipFile.
lines = (data1 * 50).decode("utf-8").splitlines(keepends=True)
self.test_write()
with gzip.GzipFile(self.filename, 'r') as f:
with io.TextIOWrapper(f, encoding="utf-8") as t:
self.assertEqual(t.readlines(), lines)
def test_fileobj_from_fdopen(self):
# Issue #13781: Opening a GzipFile for writing fails when using a
# fileobj created with os.fdopen().
fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT)
with os.fdopen(fd, "wb") as f:
with gzip.GzipFile(fileobj=f, mode="w") as g:
pass
def test_fileobj_mode(self):
gzip.GzipFile(self.filename, "wb").close()
with open(self.filename, "r+b") as f:
with gzip.GzipFile(fileobj=f, mode='r') as g:
self.assertEqual(g.mode, gzip.READ)
with gzip.GzipFile(fileobj=f, mode='w') as g:
self.assertEqual(g.mode, gzip.WRITE)
with gzip.GzipFile(fileobj=f, mode='a') as g:
self.assertEqual(g.mode, gzip.WRITE)
with gzip.GzipFile(fileobj=f, mode='x') as g:
self.assertEqual(g.mode, gzip.WRITE)
with self.assertRaises(ValueError):
gzip.GzipFile(fileobj=f, mode='z')
for mode in "rb", "r+b":
with open(self.filename, mode) as f:
with gzip.GzipFile(fileobj=f) as g:
self.assertEqual(g.mode, gzip.READ)
for mode in "wb", "ab", "xb":
if "x" in mode:
support.unlink(self.filename)
with open(self.filename, mode) as f:
with gzip.GzipFile(fileobj=f) as g:
self.assertEqual(g.mode, gzip.WRITE)
def test_bytes_filename(self):
str_filename = self.filename
try:
bytes_filename = str_filename.encode("utf-8")
except UnicodeEncodeError:
self.skipTest("Temporary file name needs to be ASCII")
with gzip.GzipFile(bytes_filename, "wb") as f:
f.write(data1 * 50)
with gzip.GzipFile(bytes_filename, "rb") as f:
self.assertEqual(f.read(), data1 * 50)
# Sanity check that we are actually operating on the right file.
with gzip.GzipFile(str_filename, "rb") as f:
self.assertEqual(f.read(), data1 * 50)
def test_decompress_limited(self):
"""Decompressed data buffering should be limited"""
bomb = gzip.compress(b'\0' * int(2e6), compresslevel=9)
self.assertLess(len(bomb), io.DEFAULT_BUFFER_SIZE)
bomb = io.BytesIO(bomb)
decomp = gzip.GzipFile(fileobj=bomb)
self.assertEqual(decomp.read(1), b'\0')
max_decomp = 1 + io.DEFAULT_BUFFER_SIZE
self.assertLessEqual(decomp._buffer.raw.tell(), max_decomp,
"Excessive amount of data was decompressed")
# Testing compress/decompress shortcut functions
def test_compress(self):
for data in [data1, data2]:
for args in [(), (1,), (6,), (9,)]:
datac = gzip.compress(data, *args)
self.assertEqual(type(datac), bytes)
with gzip.GzipFile(fileobj=io.BytesIO(datac), mode="rb") as f:
self.assertEqual(f.read(), data)
def test_decompress(self):
for data in (data1, data2):
buf = io.BytesIO()
with gzip.GzipFile(fileobj=buf, mode="wb") as f:
f.write(data)
self.assertEqual(gzip.decompress(buf.getvalue()), data)
# Roundtrip with compress
datac = gzip.compress(data)
self.assertEqual(gzip.decompress(datac), data)
def test_read_truncated(self):
data = data1*50
# Drop the CRC (4 bytes) and file size (4 bytes).
truncated = gzip.compress(data)[:-8]
with gzip.GzipFile(fileobj=io.BytesIO(truncated)) as f:
self.assertRaises(EOFError, f.read)
with gzip.GzipFile(fileobj=io.BytesIO(truncated)) as f:
self.assertEqual(f.read(len(data)), data)
self.assertRaises(EOFError, f.read, 1)
# Incomplete 10-byte header.
for i in range(2, 10):
with gzip.GzipFile(fileobj=io.BytesIO(truncated[:i])) as f:
self.assertRaises(EOFError, f.read, 1)
def test_read_with_extra(self):
# Gzip data with an extra field
gzdata = (b'\x1f\x8b\x08\x04\xb2\x17cQ\x02\xff'
b'\x05\x00Extra'
b'\x0bI-.\x01\x002\xd1Mx\x04\x00\x00\x00')
with gzip.GzipFile(fileobj=io.BytesIO(gzdata)) as f:
self.assertEqual(f.read(), b'Test')
def test_prepend_error(self):
# See issue #20875
with gzip.open(self.filename, "wb") as f:
f.write(data1)
with gzip.open(self.filename, "rb") as f:
f._buffer.raw._fp.prepend()
class TestOpen(BaseTest):
def test_binary_modes(self):
uncompressed = data1 * 50
with gzip.open(self.filename, "wb") as f:
f.write(uncompressed)
with open(self.filename, "rb") as f:
file_data = gzip.decompress(f.read())
self.assertEqual(file_data, uncompressed)
with gzip.open(self.filename, "rb") as f:
self.assertEqual(f.read(), uncompressed)
with gzip.open(self.filename, "ab") as f:
f.write(uncompressed)
with open(self.filename, "rb") as f:
file_data = gzip.decompress(f.read())
self.assertEqual(file_data, uncompressed * 2)
with self.assertRaises(FileExistsError):
gzip.open(self.filename, "xb")
support.unlink(self.filename)
with gzip.open(self.filename, "xb") as f:
f.write(uncompressed)
with open(self.filename, "rb") as f:
file_data = gzip.decompress(f.read())
self.assertEqual(file_data, uncompressed)
def test_pathlike_file(self):
filename = pathlib.Path(self.filename)
with gzip.open(filename, "wb") as f:
f.write(data1 * 50)
with gzip.open(filename, "ab") as f:
f.write(data1)
with gzip.open(filename) as f:
self.assertEqual(f.read(), data1 * 51)
def test_implicit_binary_modes(self):
# Test implicit binary modes (no "b" or "t" in mode string).
uncompressed = data1 * 50
with gzip.open(self.filename, "w") as f:
f.write(uncompressed)
with open(self.filename, "rb") as f:
file_data = gzip.decompress(f.read())
self.assertEqual(file_data, uncompressed)
with gzip.open(self.filename, "r") as f:
self.assertEqual(f.read(), uncompressed)
with gzip.open(self.filename, "a") as f:
f.write(uncompressed)
with open(self.filename, "rb") as f:
file_data = gzip.decompress(f.read())
self.assertEqual(file_data, uncompressed * 2)
with self.assertRaises(FileExistsError):
gzip.open(self.filename, "x")
support.unlink(self.filename)
with gzip.open(self.filename, "x") as f:
f.write(uncompressed)
with open(self.filename, "rb") as f:
file_data = gzip.decompress(f.read())
self.assertEqual(file_data, uncompressed)
def test_text_modes(self):
uncompressed = data1.decode("ascii") * 50
uncompressed_raw = uncompressed.replace("\n", os.linesep)
with gzip.open(self.filename, "wt") as f:
f.write(uncompressed)
with open(self.filename, "rb") as f:
file_data = gzip.decompress(f.read()).decode("ascii")
self.assertEqual(file_data, uncompressed_raw)
with gzip.open(self.filename, "rt") as f:
self.assertEqual(f.read(), uncompressed)
with gzip.open(self.filename, "at") as f:
f.write(uncompressed)
with open(self.filename, "rb") as f:
file_data = gzip.decompress(f.read()).decode("ascii")
self.assertEqual(file_data, uncompressed_raw * 2)
def test_fileobj(self):
uncompressed_bytes = data1 * 50
uncompressed_str = uncompressed_bytes.decode("ascii")
compressed = gzip.compress(uncompressed_bytes)
with gzip.open(io.BytesIO(compressed), "r") as f:
self.assertEqual(f.read(), uncompressed_bytes)
with gzip.open(io.BytesIO(compressed), "rb") as f:
self.assertEqual(f.read(), uncompressed_bytes)
with gzip.open(io.BytesIO(compressed), "rt") as f:
self.assertEqual(f.read(), uncompressed_str)
def test_bad_params(self):
# Test invalid parameter combinations.
with self.assertRaises(TypeError):
gzip.open(123.456)
with self.assertRaises(ValueError):
gzip.open(self.filename, "wbt")
with self.assertRaises(ValueError):
gzip.open(self.filename, "xbt")
with self.assertRaises(ValueError):
gzip.open(self.filename, "rb", encoding="utf-8")
with self.assertRaises(ValueError):
gzip.open(self.filename, "rb", errors="ignore")
with self.assertRaises(ValueError):
gzip.open(self.filename, "rb", newline="\n")
def test_encoding(self):
# Test non-default encoding.
return
uncompressed = data1.decode("ascii") * 50
uncompressed_raw = uncompressed.replace("\n", os.linesep)
with gzip.open(self.filename, "wt", encoding="utf-16") as f:
f.write(uncompressed)
with open(self.filename, "rb") as f:
file_data = gzip.decompress(f.read()).decode("utf-16")
self.assertEqual(file_data, uncompressed_raw)
with gzip.open(self.filename, "rt", encoding="utf-16") as f:
self.assertEqual(f.read(), uncompressed)
def test_encoding_error_handler(self):
# Test with non-default encoding error handler.
with gzip.open(self.filename, "wb") as f:
f.write(b"foo\xffbar")
with gzip.open(self.filename, "rt", encoding="utf-8", errors="ignore") \
as f:
self.assertEqual(f.read(), "foobar")
def test_newline(self):
# Test with explicit newline (universal newline mode disabled).
uncompressed = data1.decode("ascii") * 50
with gzip.open(self.filename, "wt", newline="\n") as f:
f.write(uncompressed)
with gzip.open(self.filename, "rt", newline="\r") as f:
self.assertEqual(f.readlines(), [uncompressed])
def create_and_remove_directory(directory):
def decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
os.makedirs(directory)
try:
return function(*args, **kwargs)
finally:
support.rmtree(directory)
return wrapper
return decorator
class TestCommandLine(unittest.TestCase):
data = b'This is a simple test with gzip'
def test_decompress_stdin_stdout(self):
with io.BytesIO() as bytes_io:
with gzip.GzipFile(fileobj=bytes_io, mode='wb') as gzip_file:
gzip_file.write(self.data)
args = sys.executable, '-m', 'gzip', '-d'
with Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
out, err = proc.communicate(bytes_io.getvalue())
self.assertEqual(err, b'')
self.assertEqual(out, self.data)
@create_and_remove_directory(TEMPDIR)
def test_decompress_infile_outfile(self):
gzipname = os.path.join(TEMPDIR, 'testgzip.gz')
self.assertFalse(os.path.exists(gzipname))
with gzip.open(gzipname, mode='wb') as fp:
fp.write(self.data)
rc, out, err = assert_python_ok('-m', 'gzip', '-d', gzipname)
with open(os.path.join(TEMPDIR, "testgzip"), "rb") as gunziped:
self.assertEqual(gunziped.read(), self.data)
self.assertTrue(os.path.exists(gzipname))
self.assertEqual(rc, 0)
self.assertEqual(out, b'')
self.assertEqual(err, b'')
def test_decompress_infile_outfile_error(self):
rc, out, err = assert_python_ok('-m', 'gzip', '-d', 'thisisatest.out')
self.assertIn(b"filename doesn't end in .gz:", out)
self.assertEqual(rc, 0)
self.assertEqual(err, b'')
@create_and_remove_directory(TEMPDIR)
def test_compress_stdin_outfile(self):
args = sys.executable, '-m', 'gzip'
with Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
out, err = proc.communicate(self.data)
self.assertEqual(err, b'')
self.assertEqual(out[:2], b"\x1f\x8b")
@create_and_remove_directory(TEMPDIR)
def test_compress_infile_outfile(self):
local_testgzip = os.path.join(TEMPDIR, 'testgzip')
gzipname = local_testgzip + '.gz'
self.assertFalse(os.path.exists(gzipname))
with open(local_testgzip, 'wb') as fp:
fp.write(self.data)
rc, out, err = assert_python_ok('-m', 'gzip', local_testgzip)
self.assertTrue(os.path.exists(gzipname))
self.assertEqual(rc, 0)
self.assertEqual(out, b'')
self.assertEqual(err, b'')
def test_main(verbose=None):
support.run_unittest(TestGzip, TestOpen, TestCommandLine)
if __name__ == "__main__":
test_main(verbose=True)
| 27,791 | 765 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/test/test_imaplib.py | from test import support
# If we end up with a significant number of tests that don't require
# threading, this test module should be split. Right now we skip
# them all if we don't have threading.
threading = support.import_module('threading')
from contextlib import contextmanager
import errno
import imaplib
import os.path
import socketserver
import time
import calendar
import inspect
from test.support import (reap_threads, verbose, transient_internet,
run_with_tz, run_with_locale, cpython_only)
import unittest
from unittest import mock
from datetime import datetime, timezone, timedelta
try:
import ssl
except ImportError:
ssl = None
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")
class TestImaplib(unittest.TestCase):
def test_Internaldate2tuple(self):
t0 = calendar.timegm((2000, 1, 1, 0, 0, 0, -1, -1, -1))
tt = imaplib.Internaldate2tuple(
b'25 (INTERNALDATE "01-Jan-2000 00:00:00 +0000")')
self.assertEqual(time.mktime(tt), t0)
tt = imaplib.Internaldate2tuple(
b'25 (INTERNALDATE "01-Jan-2000 11:30:00 +1130")')
self.assertEqual(time.mktime(tt), t0)
tt = imaplib.Internaldate2tuple(
b'25 (INTERNALDATE "31-Dec-1999 12:30:00 -1130")')
self.assertEqual(time.mktime(tt), t0)
@run_with_tz('MST+07MDT,M4.1.0,M10.5.0')
def test_Internaldate2tuple_issue10941(self):
self.assertNotEqual(imaplib.Internaldate2tuple(
b'25 (INTERNALDATE "02-Apr-2000 02:30:00 +0000")'),
imaplib.Internaldate2tuple(
b'25 (INTERNALDATE "02-Apr-2000 03:30:00 +0000")'))
def timevalues(self):
return [2000000000, 2000000000.0, time.localtime(2000000000),
(2033, 5, 18, 5, 33, 20, -1, -1, -1),
(2033, 5, 18, 5, 33, 20, -1, -1, 1),
datetime.fromtimestamp(2000000000,
timezone(timedelta(0, 2 * 60 * 60))),
'"18-May-2033 05:33:20 +0200"']
@run_with_locale('LC_ALL', 'de_DE', 'fr_FR')
# DST rules included to work around quirk where the Gnu C library may not
# otherwise restore the previous time zone
@run_with_tz('STD-1DST,M3.2.0,M11.1.0')
def test_Time2Internaldate(self):
expected = '"18-May-2033 05:33:20 +0200"'
for t in self.timevalues():
internal = imaplib.Time2Internaldate(t)
self.assertEqual(internal, expected)
def test_that_Time2Internaldate_returns_a_result(self):
# Without tzset, we can check only that it successfully
# produces a result, not the correctness of the result itself,
# since the result depends on the timezone the machine is in.
for t in self.timevalues():
imaplib.Time2Internaldate(t)
def test_imap4_host_default_value(self):
expected_errnos = [
# This is the exception that should be raised.
errno.ECONNREFUSED,
]
if hasattr(errno, 'EADDRNOTAVAIL'):
# socket.create_connection() fails randomly with
# EADDRNOTAVAIL on Travis CI.
expected_errnos.append(errno.EADDRNOTAVAIL)
with self.assertRaises(OSError) as cm:
imaplib.IMAP4()
self.assertIn(cm.exception.errno, expected_errnos)
if ssl:
class SecureTCPServer(socketserver.TCPServer):
def get_request(self):
newsocket, fromaddr = self.socket.accept()
context = ssl.SSLContext()
context.load_cert_chain(CERTFILE)
connstream = context.wrap_socket(newsocket, server_side=True)
return connstream, fromaddr
IMAP4_SSL = imaplib.IMAP4_SSL
else:
class SecureTCPServer:
pass
IMAP4_SSL = None
class SimpleIMAPHandler(socketserver.StreamRequestHandler):
timeout = 1
continuation = None
capabilities = ''
def setup(self):
super().setup()
self.server.logged = None
def _send(self, message):
if verbose:
print("SENT: %r" % message.strip())
self.wfile.write(message)
def _send_line(self, message):
self._send(message + b'\r\n')
def _send_textline(self, message):
self._send_line(message.encode('ASCII'))
def _send_tagged(self, tag, code, message):
self._send_textline(' '.join((tag, code, message)))
def handle(self):
# Send a welcome message.
self._send_textline('* OK IMAP4rev1')
while 1:
# Gather up input until we receive a line terminator or we timeout.
# Accumulate read(1) because it's simpler to handle the differences
# between naked sockets and SSL sockets.
line = b''
while 1:
try:
part = self.rfile.read(1)
if part == b'':
# Naked sockets return empty strings..
return
line += part
except OSError:
# ..but SSLSockets raise exceptions.
return
if line.endswith(b'\r\n'):
break
if verbose:
print('GOT: %r' % line.strip())
if self.continuation:
try:
self.continuation.send(line)
except StopIteration:
self.continuation = None
continue
splitline = line.decode('ASCII').split()
tag = splitline[0]
cmd = splitline[1]
args = splitline[2:]
if hasattr(self, 'cmd_' + cmd):
continuation = getattr(self, 'cmd_' + cmd)(tag, args)
if continuation:
self.continuation = continuation
next(continuation)
else:
self._send_tagged(tag, 'BAD', cmd + ' unknown')
def cmd_CAPABILITY(self, tag, args):
caps = ('IMAP4rev1 ' + self.capabilities
if self.capabilities
else 'IMAP4rev1')
self._send_textline('* CAPABILITY ' + caps)
self._send_tagged(tag, 'OK', 'CAPABILITY completed')
def cmd_LOGOUT(self, tag, args):
self.server.logged = None
self._send_textline('* BYE IMAP4ref1 Server logging out')
self._send_tagged(tag, 'OK', 'LOGOUT completed')
def cmd_LOGIN(self, tag, args):
self.server.logged = args[0]
self._send_tagged(tag, 'OK', 'LOGIN completed')
class NewIMAPTestsMixin():
client = None
def _setup(self, imap_handler, connect=True):
"""
Sets up imap_handler for tests. imap_handler should inherit from either:
- SimpleIMAPHandler - for testing IMAP commands,
- socketserver.StreamRequestHandler - if raw access to stream is needed.
Returns (client, server).
"""
class TestTCPServer(self.server_class):
def handle_error(self, request, client_address):
"""
End request and raise the error if one occurs.
"""
self.close_request(request)
self.server_close()
raise
self.addCleanup(self._cleanup)
self.server = self.server_class((support.HOST, 0), imap_handler)
self.thread = threading.Thread(
name=self._testMethodName+'-server',
target=self.server.serve_forever,
# Short poll interval to make the test finish quickly.
# Time between requests is short enough that we won't wake
# up spuriously too many times.
kwargs={'poll_interval': 0.01})
self.thread.daemon = True # In case this function raises.
self.thread.start()
if connect:
self.client = self.imap_class(*self.server.server_address)
return self.client, self.server
def _cleanup(self):
"""
Cleans up the test server. This method should not be called manually,
it is added to the cleanup queue in the _setup method already.
"""
# if logout was called already we'd raise an exception trying to
# shutdown the client once again
if self.client is not None and self.client.state != 'LOGOUT':
self.client.shutdown()
# cleanup the server
self.server.shutdown()
self.server.server_close()
self.thread.join(3.0)
def test_EOF_without_complete_welcome_message(self):
# http://bugs.python.org/issue5949
class EOFHandler(socketserver.StreamRequestHandler):
def handle(self):
self.wfile.write(b'* OK')
_, server = self._setup(EOFHandler, connect=False)
self.assertRaises(imaplib.IMAP4.abort, self.imap_class,
*server.server_address)
def test_line_termination(self):
class BadNewlineHandler(SimpleIMAPHandler):
def cmd_CAPABILITY(self, tag, args):
self._send(b'* CAPABILITY IMAP4rev1 AUTH\n')
self._send_tagged(tag, 'OK', 'CAPABILITY completed')
_, server = self._setup(BadNewlineHandler, connect=False)
self.assertRaises(imaplib.IMAP4.abort, self.imap_class,
*server.server_address)
def test_enable_raises_error_if_not_AUTH(self):
class EnableHandler(SimpleIMAPHandler):
capabilities = 'AUTH ENABLE UTF8=ACCEPT'
client, _ = self._setup(EnableHandler)
self.assertFalse(client.utf8_enabled)
with self.assertRaisesRegex(imaplib.IMAP4.error, 'ENABLE.*NONAUTH'):
client.enable('foo')
self.assertFalse(client.utf8_enabled)
def test_enable_raises_error_if_no_capability(self):
client, _ = self._setup(SimpleIMAPHandler)
with self.assertRaisesRegex(imaplib.IMAP4.error,
'does not support ENABLE'):
client.enable('foo')
def test_enable_UTF8_raises_error_if_not_supported(self):
client, _ = self._setup(SimpleIMAPHandler)
typ, data = client.login('user', 'pass')
self.assertEqual(typ, 'OK')
with self.assertRaisesRegex(imaplib.IMAP4.error,
'does not support ENABLE'):
client.enable('UTF8=ACCEPT')
def test_enable_UTF8_True_append(self):
class UTF8AppendServer(SimpleIMAPHandler):
capabilities = 'ENABLE UTF8=ACCEPT'
def cmd_ENABLE(self, tag, args):
self._send_tagged(tag, 'OK', 'ENABLE successful')
def cmd_AUTHENTICATE(self, tag, args):
self._send_textline('+')
self.server.response = yield
self._send_tagged(tag, 'OK', 'FAKEAUTH successful')
def cmd_APPEND(self, tag, args):
self._send_textline('+')
self.server.response = yield
self._send_tagged(tag, 'OK', 'okay')
client, server = self._setup(UTF8AppendServer)
self.assertEqual(client._encoding, 'ascii')
code, _ = client.authenticate('MYAUTH', lambda x: b'fake')
self.assertEqual(code, 'OK')
self.assertEqual(server.response, b'ZmFrZQ==\r\n') # b64 encoded 'fake'
code, _ = client.enable('UTF8=ACCEPT')
self.assertEqual(code, 'OK')
self.assertEqual(client._encoding, 'utf-8')
msg_string = 'Subject: üñéöðé'
typ, data = client.append(None, None, None, msg_string.encode('utf-8'))
self.assertEqual(typ, 'OK')
self.assertEqual(server.response,
('UTF8 (%s)\r\n' % msg_string).encode('utf-8'))
def test_search_disallows_charset_in_utf8_mode(self):
class UTF8Server(SimpleIMAPHandler):
capabilities = 'AUTH ENABLE UTF8=ACCEPT'
def cmd_ENABLE(self, tag, args):
self._send_tagged(tag, 'OK', 'ENABLE successful')
def cmd_AUTHENTICATE(self, tag, args):
self._send_textline('+')
self.server.response = yield
self._send_tagged(tag, 'OK', 'FAKEAUTH successful')
client, _ = self._setup(UTF8Server)
typ, _ = client.authenticate('MYAUTH', lambda x: b'fake')
self.assertEqual(typ, 'OK')
typ, _ = client.enable('UTF8=ACCEPT')
self.assertEqual(typ, 'OK')
self.assertTrue(client.utf8_enabled)
with self.assertRaisesRegex(imaplib.IMAP4.error, 'charset.*UTF8'):
client.search('foo', 'bar')
def test_bad_auth_name(self):
class MyServer(SimpleIMAPHandler):
def cmd_AUTHENTICATE(self, tag, args):
self._send_tagged(tag, 'NO',
'unrecognized authentication type {}'.format(args[0]))
client, _ = self._setup(MyServer)
with self.assertRaisesRegex(imaplib.IMAP4.error,
'unrecognized authentication type METHOD'):
client.authenticate('METHOD', lambda: 1)
def test_invalid_authentication(self):
class MyServer(SimpleIMAPHandler):
def cmd_AUTHENTICATE(self, tag, args):
self._send_textline('+')
self.response = yield
self._send_tagged(tag, 'NO', '[AUTHENTICATIONFAILED] invalid')
client, _ = self._setup(MyServer)
with self.assertRaisesRegex(imaplib.IMAP4.error,
r'\[AUTHENTICATIONFAILED\] invalid'):
client.authenticate('MYAUTH', lambda x: b'fake')
def test_valid_authentication_bytes(self):
class MyServer(SimpleIMAPHandler):
def cmd_AUTHENTICATE(self, tag, args):
self._send_textline('+')
self.server.response = yield
self._send_tagged(tag, 'OK', 'FAKEAUTH successful')
client, server = self._setup(MyServer)
code, _ = client.authenticate('MYAUTH', lambda x: b'fake')
self.assertEqual(code, 'OK')
self.assertEqual(server.response, b'ZmFrZQ==\r\n') # b64 encoded 'fake'
def test_valid_authentication_plain_text(self):
class MyServer(SimpleIMAPHandler):
def cmd_AUTHENTICATE(self, tag, args):
self._send_textline('+')
self.server.response = yield
self._send_tagged(tag, 'OK', 'FAKEAUTH successful')
client, server = self._setup(MyServer)
code, _ = client.authenticate('MYAUTH', lambda x: 'fake')
self.assertEqual(code, 'OK')
self.assertEqual(server.response, b'ZmFrZQ==\r\n') # b64 encoded 'fake'
def test_login_cram_md5_bytes(self):
class AuthHandler(SimpleIMAPHandler):
capabilities = 'LOGINDISABLED AUTH=CRAM-MD5'
def cmd_AUTHENTICATE(self, tag, args):
self._send_textline('+ PDE4OTYuNjk3MTcwOTUyQHBvc3RvZmZpY2Uucm'
'VzdG9uLm1jaS5uZXQ=')
r = yield
if (r == b'dGltIGYxY2E2YmU0NjRiOWVmYT'
b'FjY2E2ZmZkNmNmMmQ5ZjMy\r\n'):
self._send_tagged(tag, 'OK', 'CRAM-MD5 successful')
else:
self._send_tagged(tag, 'NO', 'No access')
client, _ = self._setup(AuthHandler)
self.assertTrue('AUTH=CRAM-MD5' in client.capabilities)
ret, _ = client.login_cram_md5("tim", b"tanstaaftanstaaf")
self.assertEqual(ret, "OK")
def test_login_cram_md5_plain_text(self):
class AuthHandler(SimpleIMAPHandler):
capabilities = 'LOGINDISABLED AUTH=CRAM-MD5'
def cmd_AUTHENTICATE(self, tag, args):
self._send_textline('+ PDE4OTYuNjk3MTcwOTUyQHBvc3RvZmZpY2Uucm'
'VzdG9uLm1jaS5uZXQ=')
r = yield
if (r == b'dGltIGYxY2E2YmU0NjRiOWVmYT'
b'FjY2E2ZmZkNmNmMmQ5ZjMy\r\n'):
self._send_tagged(tag, 'OK', 'CRAM-MD5 successful')
else:
self._send_tagged(tag, 'NO', 'No access')
client, _ = self._setup(AuthHandler)
self.assertTrue('AUTH=CRAM-MD5' in client.capabilities)
ret, _ = client.login_cram_md5("tim", "tanstaaftanstaaf")
self.assertEqual(ret, "OK")
def test_aborted_authentication(self):
class MyServer(SimpleIMAPHandler):
def cmd_AUTHENTICATE(self, tag, args):
self._send_textline('+')
self.response = yield
if self.response == b'*\r\n':
self._send_tagged(
tag,
'NO',
'[AUTHENTICATIONFAILED] aborted')
else:
self._send_tagged(tag, 'OK', 'MYAUTH successful')
client, _ = self._setup(MyServer)
with self.assertRaisesRegex(imaplib.IMAP4.error,
r'\[AUTHENTICATIONFAILED\] aborted'):
client.authenticate('MYAUTH', lambda x: None)
@mock.patch('imaplib._MAXLINE', 10)
def test_linetoolong(self):
class TooLongHandler(SimpleIMAPHandler):
def handle(self):
# send response line longer than the limit set in the next line
self.wfile.write(b'* OK ' + 11 * b'x' + b'\r\n')
_, server = self._setup(TooLongHandler, connect=False)
with self.assertRaisesRegex(imaplib.IMAP4.error,
'got more than 10 bytes'):
self.imap_class(*server.server_address)
def test_simple_with_statement(self):
_, server = self._setup(SimpleIMAPHandler, connect=False)
with self.imap_class(*server.server_address):
pass
def test_with_statement(self):
_, server = self._setup(SimpleIMAPHandler, connect=False)
with self.imap_class(*server.server_address) as imap:
imap.login('user', 'pass')
self.assertEqual(server.logged, 'user')
self.assertIsNone(server.logged)
def test_with_statement_logout(self):
# It is legal to log out explicitly inside the with block
_, server = self._setup(SimpleIMAPHandler, connect=False)
with self.imap_class(*server.server_address) as imap:
imap.login('user', 'pass')
self.assertEqual(server.logged, 'user')
imap.logout()
self.assertIsNone(server.logged)
self.assertIsNone(server.logged)
# command tests
def test_login(self):
client, _ = self._setup(SimpleIMAPHandler)
typ, data = client.login('user', 'pass')
self.assertEqual(typ, 'OK')
self.assertEqual(data[0], b'LOGIN completed')
self.assertEqual(client.state, 'AUTH')
def test_logout(self):
client, _ = self._setup(SimpleIMAPHandler)
typ, data = client.login('user', 'pass')
self.assertEqual(typ, 'OK')
self.assertEqual(data[0], b'LOGIN completed')
typ, data = client.logout()
self.assertEqual(typ, 'BYE')
self.assertEqual(data[0], b'IMAP4ref1 Server logging out')
self.assertEqual(client.state, 'LOGOUT')
def test_lsub(self):
class LsubCmd(SimpleIMAPHandler):
def cmd_LSUB(self, tag, args):
self._send_textline('* LSUB () "." directoryA')
return self._send_tagged(tag, 'OK', 'LSUB completed')
client, _ = self._setup(LsubCmd)
client.login('user', 'pass')
typ, data = client.lsub()
self.assertEqual(typ, 'OK')
self.assertEqual(data[0], b'() "." directoryA')
class NewIMAPTests(NewIMAPTestsMixin, unittest.TestCase):
imap_class = imaplib.IMAP4
server_class = socketserver.TCPServer
@unittest.skipUnless(ssl, "SSL not available")
class NewIMAPSSLTests(NewIMAPTestsMixin, unittest.TestCase):
imap_class = IMAP4_SSL
server_class = SecureTCPServer
def test_ssl_raises(self):
ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ssl_context.verify_mode = ssl.CERT_REQUIRED
ssl_context.check_hostname = True
ssl_context.load_verify_locations(CAFILE)
with self.assertRaisesRegex(ssl.CertificateError,
"hostname '127.0.0.1' doesn't match 'localhost'"):
_, server = self._setup(SimpleIMAPHandler)
client = self.imap_class(*server.server_address,
ssl_context=ssl_context)
client.shutdown()
def test_ssl_verified(self):
ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ssl_context.verify_mode = ssl.CERT_REQUIRED
ssl_context.check_hostname = True
ssl_context.load_verify_locations(CAFILE)
_, server = self._setup(SimpleIMAPHandler)
client = self.imap_class("localhost", server.server_address[1],
ssl_context=ssl_context)
client.shutdown()
# Mock the private method _connect(), so mark the test as specific
# to CPython stdlib
@cpython_only
def test_certfile_arg_warn(self):
with support.check_warnings(('', DeprecationWarning)):
with mock.patch.object(self.imap_class, 'open'):
with mock.patch.object(self.imap_class, '_connect'):
self.imap_class('localhost', 143, certfile=CERTFILE)
class ThreadedNetworkedTests(unittest.TestCase):
server_class = socketserver.TCPServer
imap_class = imaplib.IMAP4
def make_server(self, addr, hdlr):
class MyServer(self.server_class):
def handle_error(self, request, client_address):
self.close_request(request)
self.server_close()
raise
if verbose:
print("creating server")
server = MyServer(addr, hdlr)
self.assertEqual(server.server_address, server.socket.getsockname())
if verbose:
print("server created")
print("ADDR =", addr)
print("CLASS =", self.server_class)
print("HDLR =", server.RequestHandlerClass)
t = threading.Thread(
name='%s serving' % self.server_class,
target=server.serve_forever,
# Short poll interval to make the test finish quickly.
# Time between requests is short enough that we won't wake
# up spuriously too many times.
kwargs={'poll_interval': 0.01})
t.daemon = True # In case this function raises.
t.start()
if verbose:
print("server running")
return server, t
def reap_server(self, server, thread):
if verbose:
print("waiting for server")
server.shutdown()
server.server_close()
thread.join()
if verbose:
print("done")
@contextmanager
def reaped_server(self, hdlr):
server, thread = self.make_server((support.HOST, 0), hdlr)
try:
yield server
finally:
self.reap_server(server, thread)
@contextmanager
def reaped_pair(self, hdlr):
with self.reaped_server(hdlr) as server:
client = self.imap_class(*server.server_address)
try:
yield server, client
finally:
client.logout()
@reap_threads
def test_connect(self):
with self.reaped_server(SimpleIMAPHandler) as server:
client = self.imap_class(*server.server_address)
client.shutdown()
@reap_threads
def test_bracket_flags(self):
# This violates RFC 3501, which disallows ']' characters in tag names,
# but imaplib has allowed producing such tags forever, other programs
# also produce them (eg: OtherInbox's Organizer app as of 20140716),
# and Gmail, for example, accepts them and produces them. So we
# support them. See issue #21815.
class BracketFlagHandler(SimpleIMAPHandler):
def handle(self):
self.flags = ['Answered', 'Flagged', 'Deleted', 'Seen', 'Draft']
super().handle()
def cmd_AUTHENTICATE(self, tag, args):
self._send_textline('+')
self.server.response = yield
self._send_tagged(tag, 'OK', 'FAKEAUTH successful')
def cmd_SELECT(self, tag, args):
flag_msg = ' \\'.join(self.flags)
self._send_line(('* FLAGS (%s)' % flag_msg).encode('ascii'))
self._send_line(b'* 2 EXISTS')
self._send_line(b'* 0 RECENT')
msg = ('* OK [PERMANENTFLAGS %s \\*)] Flags permitted.'
% flag_msg)
self._send_line(msg.encode('ascii'))
self._send_tagged(tag, 'OK', '[READ-WRITE] SELECT completed.')
def cmd_STORE(self, tag, args):
new_flags = args[2].strip('(').strip(')').split()
self.flags.extend(new_flags)
flags_msg = '(FLAGS (%s))' % ' \\'.join(self.flags)
msg = '* %s FETCH %s' % (args[0], flags_msg)
self._send_line(msg.encode('ascii'))
self._send_tagged(tag, 'OK', 'STORE completed.')
with self.reaped_pair(BracketFlagHandler) as (server, client):
code, data = client.authenticate('MYAUTH', lambda x: b'fake')
self.assertEqual(code, 'OK')
self.assertEqual(server.response, b'ZmFrZQ==\r\n')
client.select('test')
typ, [data] = client.store(b'1', "+FLAGS", "[test]")
self.assertIn(b'[test]', data)
client.select('test')
typ, [data] = client.response('PERMANENTFLAGS')
self.assertIn(b'[test]', data)
@reap_threads
def test_issue5949(self):
class EOFHandler(socketserver.StreamRequestHandler):
def handle(self):
# EOF without sending a complete welcome message.
self.wfile.write(b'* OK')
with self.reaped_server(EOFHandler) as server:
self.assertRaises(imaplib.IMAP4.abort,
self.imap_class, *server.server_address)
@reap_threads
def test_line_termination(self):
class BadNewlineHandler(SimpleIMAPHandler):
def cmd_CAPABILITY(self, tag, args):
self._send(b'* CAPABILITY IMAP4rev1 AUTH\n')
self._send_tagged(tag, 'OK', 'CAPABILITY completed')
with self.reaped_server(BadNewlineHandler) as server:
self.assertRaises(imaplib.IMAP4.abort,
self.imap_class, *server.server_address)
class UTF8Server(SimpleIMAPHandler):
capabilities = 'AUTH ENABLE UTF8=ACCEPT'
def cmd_ENABLE(self, tag, args):
self._send_tagged(tag, 'OK', 'ENABLE successful')
def cmd_AUTHENTICATE(self, tag, args):
self._send_textline('+')
self.server.response = yield
self._send_tagged(tag, 'OK', 'FAKEAUTH successful')
@reap_threads
def test_enable_raises_error_if_not_AUTH(self):
with self.reaped_pair(self.UTF8Server) as (server, client):
self.assertFalse(client.utf8_enabled)
self.assertRaises(imaplib.IMAP4.error, client.enable, 'foo')
self.assertFalse(client.utf8_enabled)
# XXX Also need a test that enable after SELECT raises an error.
@reap_threads
def test_enable_raises_error_if_no_capability(self):
class NoEnableServer(self.UTF8Server):
capabilities = 'AUTH'
with self.reaped_pair(NoEnableServer) as (server, client):
self.assertRaises(imaplib.IMAP4.error, client.enable, 'foo')
@reap_threads
def test_enable_UTF8_raises_error_if_not_supported(self):
class NonUTF8Server(SimpleIMAPHandler):
pass
with self.assertRaises(imaplib.IMAP4.error):
with self.reaped_pair(NonUTF8Server) as (server, client):
typ, data = client.login('user', 'pass')
self.assertEqual(typ, 'OK')
client.enable('UTF8=ACCEPT')
pass
@reap_threads
def test_enable_UTF8_True_append(self):
class UTF8AppendServer(self.UTF8Server):
def cmd_APPEND(self, tag, args):
self._send_textline('+')
self.server.response = yield
self._send_tagged(tag, 'OK', 'okay')
with self.reaped_pair(UTF8AppendServer) as (server, client):
self.assertEqual(client._encoding, 'ascii')
code, _ = client.authenticate('MYAUTH', lambda x: b'fake')
self.assertEqual(code, 'OK')
self.assertEqual(server.response,
b'ZmFrZQ==\r\n') # b64 encoded 'fake'
code, _ = client.enable('UTF8=ACCEPT')
self.assertEqual(code, 'OK')
self.assertEqual(client._encoding, 'utf-8')
msg_string = 'Subject: üñéöðé'
typ, data = client.append(
None, None, None, msg_string.encode('utf-8'))
self.assertEqual(typ, 'OK')
self.assertEqual(
server.response,
('UTF8 (%s)\r\n' % msg_string).encode('utf-8')
)
# XXX also need a test that makes sure that the Literal and Untagged_status
# regexes uses unicode in UTF8 mode instead of the default ASCII.
@reap_threads
def test_search_disallows_charset_in_utf8_mode(self):
with self.reaped_pair(self.UTF8Server) as (server, client):
typ, _ = client.authenticate('MYAUTH', lambda x: b'fake')
self.assertEqual(typ, 'OK')
typ, _ = client.enable('UTF8=ACCEPT')
self.assertEqual(typ, 'OK')
self.assertTrue(client.utf8_enabled)
self.assertRaises(imaplib.IMAP4.error, client.search, 'foo', 'bar')
@reap_threads
def test_bad_auth_name(self):
class MyServer(SimpleIMAPHandler):
def cmd_AUTHENTICATE(self, tag, args):
self._send_tagged(tag, 'NO', 'unrecognized authentication '
'type {}'.format(args[0]))
with self.reaped_pair(MyServer) as (server, client):
with self.assertRaises(imaplib.IMAP4.error):
client.authenticate('METHOD', lambda: 1)
@reap_threads
def test_invalid_authentication(self):
class MyServer(SimpleIMAPHandler):
def cmd_AUTHENTICATE(self, tag, args):
self._send_textline('+')
self.response = yield
self._send_tagged(tag, 'NO', '[AUTHENTICATIONFAILED] invalid')
with self.reaped_pair(MyServer) as (server, client):
with self.assertRaises(imaplib.IMAP4.error):
code, data = client.authenticate('MYAUTH', lambda x: b'fake')
@reap_threads
def test_valid_authentication(self):
class MyServer(SimpleIMAPHandler):
def cmd_AUTHENTICATE(self, tag, args):
self._send_textline('+')
self.server.response = yield
self._send_tagged(tag, 'OK', 'FAKEAUTH successful')
with self.reaped_pair(MyServer) as (server, client):
code, data = client.authenticate('MYAUTH', lambda x: b'fake')
self.assertEqual(code, 'OK')
self.assertEqual(server.response,
b'ZmFrZQ==\r\n') # b64 encoded 'fake'
with self.reaped_pair(MyServer) as (server, client):
code, data = client.authenticate('MYAUTH', lambda x: 'fake')
self.assertEqual(code, 'OK')
self.assertEqual(server.response,
b'ZmFrZQ==\r\n') # b64 encoded 'fake'
@reap_threads
def test_login_cram_md5(self):
class AuthHandler(SimpleIMAPHandler):
capabilities = 'LOGINDISABLED AUTH=CRAM-MD5'
def cmd_AUTHENTICATE(self, tag, args):
self._send_textline('+ PDE4OTYuNjk3MTcwOTUyQHBvc3RvZmZpY2Uucm'
'VzdG9uLm1jaS5uZXQ=')
r = yield
if (r == b'dGltIGYxY2E2YmU0NjRiOWVmYT'
b'FjY2E2ZmZkNmNmMmQ5ZjMy\r\n'):
self._send_tagged(tag, 'OK', 'CRAM-MD5 successful')
else:
self._send_tagged(tag, 'NO', 'No access')
with self.reaped_pair(AuthHandler) as (server, client):
self.assertTrue('AUTH=CRAM-MD5' in client.capabilities)
ret, data = client.login_cram_md5("tim", "tanstaaftanstaaf")
self.assertEqual(ret, "OK")
with self.reaped_pair(AuthHandler) as (server, client):
self.assertTrue('AUTH=CRAM-MD5' in client.capabilities)
ret, data = client.login_cram_md5("tim", b"tanstaaftanstaaf")
self.assertEqual(ret, "OK")
@reap_threads
def test_aborted_authentication(self):
class MyServer(SimpleIMAPHandler):
def cmd_AUTHENTICATE(self, tag, args):
self._send_textline('+')
self.response = yield
if self.response == b'*\r\n':
self._send_tagged(tag, 'NO', '[AUTHENTICATIONFAILED] aborted')
else:
self._send_tagged(tag, 'OK', 'MYAUTH successful')
with self.reaped_pair(MyServer) as (server, client):
with self.assertRaises(imaplib.IMAP4.error):
code, data = client.authenticate('MYAUTH', lambda x: None)
def test_linetoolong(self):
class TooLongHandler(SimpleIMAPHandler):
def handle(self):
# Send a very long response line
self.wfile.write(b'* OK ' + imaplib._MAXLINE * b'x' + b'\r\n')
with self.reaped_server(TooLongHandler) as server:
self.assertRaises(imaplib.IMAP4.error,
self.imap_class, *server.server_address)
@reap_threads
def test_simple_with_statement(self):
# simplest call
with self.reaped_server(SimpleIMAPHandler) as server:
with self.imap_class(*server.server_address):
pass
@reap_threads
def test_with_statement(self):
with self.reaped_server(SimpleIMAPHandler) as server:
with self.imap_class(*server.server_address) as imap:
imap.login('user', 'pass')
self.assertEqual(server.logged, 'user')
self.assertIsNone(server.logged)
@reap_threads
def test_with_statement_logout(self):
# what happens if already logout in the block?
with self.reaped_server(SimpleIMAPHandler) as server:
with self.imap_class(*server.server_address) as imap:
imap.login('user', 'pass')
self.assertEqual(server.logged, 'user')
imap.logout()
self.assertIsNone(server.logged)
self.assertIsNone(server.logged)
@unittest.skipUnless(ssl, "SSL not available")
class ThreadedNetworkedTestsSSL(ThreadedNetworkedTests):
server_class = SecureTCPServer
imap_class = IMAP4_SSL
@reap_threads
def test_ssl_verified(self):
ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ssl_context.verify_mode = ssl.CERT_REQUIRED
ssl_context.check_hostname = True
ssl_context.load_verify_locations(CAFILE)
with self.assertRaisesRegex(
ssl.CertificateError,
"hostname '127.0.0.1' doesn't match 'localhost'"):
with self.reaped_server(SimpleIMAPHandler) as server:
client = self.imap_class(*server.server_address,
ssl_context=ssl_context)
client.shutdown()
with self.reaped_server(SimpleIMAPHandler) as server:
client = self.imap_class("localhost", server.server_address[1],
ssl_context=ssl_context)
client.shutdown()
@unittest.skipUnless(
support.is_resource_enabled('network'), 'network resource disabled')
class RemoteIMAPTest(unittest.TestCase):
host = 'cyrus.andrew.cmu.edu'
port = 143
username = 'anonymous'
password = 'pass'
imap_class = imaplib.IMAP4
def setUp(self):
with transient_internet(self.host):
self.server = self.imap_class(self.host, self.port)
def tearDown(self):
if self.server is not None:
with transient_internet(self.host):
self.server.logout()
def test_logincapa(self):
with transient_internet(self.host):
for cap in self.server.capabilities:
self.assertIsInstance(cap, str)
self.assertIn('LOGINDISABLED', self.server.capabilities)
self.assertIn('AUTH=ANONYMOUS', self.server.capabilities)
rs = self.server.login(self.username, self.password)
self.assertEqual(rs[0], 'OK')
def test_logout(self):
with transient_internet(self.host):
rs = self.server.logout()
self.server = None
self.assertEqual(rs[0], 'BYE')
@unittest.skipUnless(ssl, "SSL not available")
@unittest.skipUnless(
support.is_resource_enabled('network'), 'network resource disabled')
class RemoteIMAP_STARTTLSTest(RemoteIMAPTest):
def setUp(self):
super().setUp()
with transient_internet(self.host):
rs = self.server.starttls()
self.assertEqual(rs[0], 'OK')
def test_logincapa(self):
for cap in self.server.capabilities:
self.assertIsInstance(cap, str)
self.assertNotIn('LOGINDISABLED', self.server.capabilities)
@unittest.skipUnless(ssl, "SSL not available")
class RemoteIMAP_SSLTest(RemoteIMAPTest):
port = 993
imap_class = IMAP4_SSL
def setUp(self):
pass
def tearDown(self):
pass
def create_ssl_context(self):
ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ssl_context.load_cert_chain(CERTFILE)
return ssl_context
def check_logincapa(self, server):
try:
for cap in server.capabilities:
self.assertIsInstance(cap, str)
self.assertNotIn('LOGINDISABLED', server.capabilities)
self.assertIn('AUTH=PLAIN', server.capabilities)
rs = server.login(self.username, self.password)
self.assertEqual(rs[0], 'OK')
finally:
server.logout()
def test_logincapa(self):
with transient_internet(self.host):
_server = self.imap_class(self.host, self.port)
self.check_logincapa(_server)
def test_logout(self):
with transient_internet(self.host):
_server = self.imap_class(self.host, self.port)
rs = _server.logout()
self.assertEqual(rs[0], 'BYE')
def test_ssl_context_certfile_exclusive(self):
with transient_internet(self.host):
self.assertRaises(
ValueError, self.imap_class, self.host, self.port,
certfile=CERTFILE, ssl_context=self.create_ssl_context())
def test_ssl_context_keyfile_exclusive(self):
with transient_internet(self.host):
self.assertRaises(
ValueError, self.imap_class, self.host, self.port,
keyfile=CERTFILE, ssl_context=self.create_ssl_context())
if __name__ == "__main__":
unittest.main()
| 39,506 | 1,013 | 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.