Your IP : 216.73.216.7
�
g f:��@sdZedkr!ed��nddlZddlZddlZddlZddlZddl Z ddl
Z
ddlZddlZddl
ZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZyddl Z ddl!Z!Wnek
r�dZ dZ!YnXyddl"Z#Wnek
r�dZ#YnXyddl$Z$Wnek
r�dZ$YnXyddl%Z%Wnek
rdZ%YnXyddl&Z&Wnek
rAdZ&YnXyddl'Z'Wnek
rldZ'YnXyddl(Z(Wnek
r�dZ(YnXddddd d
ddd
ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRgNZ)GdSd
�d
e*�Z+GdTd�de+�Z,GdUd�dej-�Z.ej/dVdWdX��Z0dYdZfd[d
�Z1d\d]�Z2d^d_�Z3d`d9�Z4dad:�Z5ffdYdbd�Z6dcd5�Z7ddZ8dZ9da:da;dYZ<dZ=da>ded�Z?dfd�Z@dgd�ZAejjBdh�r�dYdidj�ZCdkdl�ZDdmdn�ZEdodp�ZFnejGZDejHZEejIZFdqd�ZGdrds�ZHdtd�ZIdudv�ZJdwd�ZKdxdy�ZLdzd �ZMdd{d!�ZNd|d}�ZOd~d"�ZPdd#�ZQd�d$�ZRd�ZSd�ZTejUejVd�d?�ZWeSd�d@�ZXd�d��ZYeY�ZZd�d��Z[d)Z\d,Z]ej^e_j`d��jBd��d��Zaej^e$d��Zbej^e%d��Zcej^e&d��Zdej^e'd��ZeejjBd��Zfejgd�kr�d�Zhnd�Zhd�jiehejj��ZhdZkxDd-D]<Zlyejmejnel��Wneok
r�Yq�XelZkPq�Wehd�Zpejd�kr*ddlqZqeqjrd�ep�Zpnejs�ZtdZuejgd.kr�ejv�jd�kr�ehd�Zuyeujwet�Wnexk
r�Yq�Xeyd�euetf�dZuq�nNejd�kr�yd�jzet�Wq�e{k
r�ehd�jzetd��ZuYq�XndZ|xHd/D]@Zgyegjzet�Wqe{k
rJejneh�egZ|PYqXqWekrfehd�ekZ}ndZ}ej~�Zej/ddYd�d���Z�ej/dYd�d���Z�ej/d�dYd�d��Z�e�ed��r�ej/d�dB��Z�nej�j�ej�j�e���Z�ej�j�e��Z�ej�j�e�d��Z�dd�d�Z�d�d�Z�d�dQ�Z�d�d��Z�d�d%�Z�d�dA�Z�Gd�d��d�e��Z�dYd�d��Z�ej/d�dI��Z�Gd�d�de��Z�Gd�dJ�dJej�j��Z�Gd�d��d�e��Z�Gd�d&�d&e��Z�e�e�d�ej��Z�e�e�d�ej��Z�e�e�d�ej��Z�ej/d�d�d�fd�d*��Z�ej/d�d���Z�d�d�Z�d�d�Z�d�d�Z�d�d��Z�ej/d�d���Z�d�d��Z�d�Z�d�Z�e�ed��r d�e�Z�d�Z�ne�d�Z�d�d��Z�d�d��Z�d0Z�d1Z�d�d��Z�d�dK�Z�d�dR�Z�d2Z�d�e�Z�d�e�Z�d�e�Z�ej�Z�d�dO�Z�Gd�d��d��Z�dVd�d2�Z�d�d3�Z�Gd�d+�d+�Z�d�d��Z�d�d��Z�d�d4�Z�dd�d��Z�d�d��Z�d�d<�Z�d�d��Z�d�d��Z�dd�Z�dd�Z�dd,�Z�dd�Z�e��o�ejdko�ej�d�Z�e�jdk o�e�Z�ej^e�d �Z�ddd
d-�Z�dd�Z�d
d�Z�ddE�Z�ddF�Z�ddG�Z�ddC�Z�ej/dddH��Z�ej/ddM��Z�ej/ddL��Z�dd�Z�dd�Z�GddD�dDej�j��Z�GddN�dNe��Z�da�dd�Z�dd.�Z�da�dd�Z�d d7�Z�d!d�Z�Gd"dP�dP�Z�d#d$�Z�d%d&�Z�dS(3z7Supporting definitions for the Python regression tests.ztest.supportz.support must be imported from the test package�N�
PIPE_MAX_SIZE�verbose�
max_memuse�
use_resources�failfast�Error�
TestFailed�ResourceDenied�
import_module�import_fresh_module�CleanImport�unload�forget�record_original_stdout�get_original_stdout�captured_stdout�captured_stdin�captured_stderr�TESTFN�SAVEDCWD�unlink�rmtree�temp_cwd�findfile�create_empty_file�can_symlink�fs_is_case_insensitive�is_resource_enabled�requires�requires_freebsd_version�requires_linux_version�requires_mac_ver�check_syntax_error�TransientResource�time_out�socket_peer_reset�ioerror_peer_reset�transient_internet�BasicTestRunner�run_unittest�run_doctest�skip_unless_symlink�
requires_gzip�requires_bz2�
requires_lzma�
bigmemtest�bigaddrspacetest�cpython_only�
get_attribute�requires_IEEE_754�skip_unless_xattr�
requires_zlib�anticipate_failure�load_package_tests� is_jython�check_impl_detail�HOST�IPV6_ENABLED�find_unused_port� bind_port�open_urlresource�
temp_umask�
reap_children�TestHandler�threading_setup�threading_cleanup�reap_threads�
start_threads�check_warnings�EnvironmentVarGuard�run_with_locale� swap_item� swap_attr�Matcher�set_memlimit�SuppressCrashReport�sortdict�run_with_tzc@seZdZdZdS)rz*Base class for regression test exceptions.N)�__name__�
__module__�__qualname__�__doc__�rTrT�:/opt/alt/python34/lib64/python3.4/test/support/__init__.pyrlsc@seZdZdZdS)rzTest failed.N)rPrQrRrSrTrTrTrUrosc@seZdZdZdS)r z�Test skipped because it requested a disallowed resource.
This is raised when a test calls requires() for a resource that
has not be enabled. It is used to distinguish between expected
and unexpected skips.
N)rPrQrRrSrTrTrTrUr rsTccs=|r4tj��tjddt�dVWdQXndVdS)z�Context manager to suppress package and module deprecation
warnings when importing them.
If ignore is False, this context manager has no effect.
�ignorez.+ (module|package)N)�warnings�catch_warnings�filterwarnings�DeprecationWarning)rVrTrTrU�_ignore_deprecated_importszs
r[F�required_oncCs�t|��qytj|�SWnXtk
rx}z8tjjt|��rQ�ntj t
|���WYdd}~XnXWdQXdS)acImport and return the module to be tested, raising SkipTest if
it is not available.
If deprecated is True, any module or package deprecation messages
will be suppressed. If a module is required on a platform but optional for
others, set required_on to an iterable of platform prefixes which will be
compared against sys.platform.
N)r[� importlibr
�ImportError�sys�platform�
startswith�tuple�unittest�SkipTest�str)�name�
deprecatedr\�msgrTrTrUr
�s
cCs�|tjkr&t|�tj|=nxTttj�D]C}||ks[|j|d�r6tj|||<tj|=q6q6WdS)zyHelper function to save and remove a module from sys.modules
Raise ImportError if the module can't be imported.
�.N)r_�modules�
__import__�listra)rf�orig_modules�modnamerTrTrU�_save_and_remove_module�s
rocCsGd}ytj|||<Wntk
r5d}YnXdtj|<|S)z�Helper function to save and block a module in sys.modules
Return True if the module was in sys.modules, False otherwise.
TFN)r_rj�KeyError)rfrmZsavedrTrTrU�_save_and_block_module�s
rqcCs|r
tjSdd�S)z�Decorator to mark a test that is known to be broken in some cases
Any use of this decorator should have a comment identifying the
associated tracker issue.
cSs|S)NrT)�frTrTrU�<lambda>�sz$anticipate_failure.<locals>.<lambda>)rcZexpectedFailure)Z conditionrTrTrUr6�scCsn|dkrd}ntjjtjjtjjt���}|jd|d|d|�}|j|�|S)z�Generic load_tests implementation for simple test packages.
Most packages can implement load_tests using this function as follows:
def load_tests(*args):
return load_package_tests(os.path.dirname(__file__), *args)
Nztest*Z start_dirZ
top_level_dir�pattern)�os�path�dirname�__file__ZdiscoverZaddTests)Zpkg_dir�loaderZstandard_testsrtZtop_dirZ
package_testsrTrTrUr7�s
cCs�t|���i}g}t||�z�yax|D]}t||�q3Wx-|D]%}t||�sQ|j|�qQqQWtj|�}Wntk
r�d}YnXWdx'|j�D]\} }
|
tj | <q�Wx|D]}tj |=q�WX|SWdQXdS)a�Import and return a module, deliberately bypassing sys.modules.
This function imports and returns a fresh copy of the named Python module
by removing the named module from sys.modules before doing the import.
Note that unlike reload, the original module is not affected by
this operation.
*fresh* is an iterable of additional module names that are also removed
from the sys.modules cache before doing the import.
*blocked* is an iterable of module names that are replaced with None
in the module cache during the import to ensure that attempts to import
them raise ImportError.
The named module and any modules named in the *fresh* and *blocked*
parameters are saved before starting the import and then reinserted into
sys.modules when the fresh import is complete.
Module and package deprecation messages are suppressed during this import
if *deprecated* is True.
This function will raise ImportError if the named module cannot be
imported.
N)
r[rorq�appendr]r
r^�itemsr_rj)rfZfreshZblockedrgrmZnames_to_removeZ
fresh_nameZblocked_nameZfresh_moduleZ orig_name�moduleZname_to_removerTrTrUr�s$
cCsIyt||�}Wn+tk
r@tjd||f��YnX|SdS)z?Get an attribute, raising SkipTest if AttributeError is raised.zobject %r has no attribute %rN)�getattr�AttributeErrorrcrd)�objrfZ attributerTrTrUr2s
�cCs
|adS)N)�_original_stdout)�stdoutrTrTrUrscCs
tptjS)N)r�r_r�rTrTrTrUr!scCs'ytj|=Wntk
r"YnXdS)N)r_rjrp)rfrTrTrUr
$s
�wincCs�||�|r|}n$tjj|�\}}|p:d}d}xR|dkr�tj|�}|rm|n ||ks}dStj|�|d9}qFWtjd|tdd�dS)Nrig����MbP?g�?�z)tests may fail, delete still pending for �
stacklevel�) rurv�split�listdir�time�sleeprW�warn�RuntimeWarning)�func�pathname�waitallrwrf�timeout�LrTrTrU�_waitfor+s
r�cCsttj|�dS)N)r�rur)�filenamerTrTrU�_unlinkLsr�cCsttj|�dS)N)r�ru�rmdir)rwrTrTrU�_rmdirOsr�cs9�fdd��t�|dd�ttj|�dS)Ncs�x�tj|�D]�}tjj||�}ytj|�j}WnHtk
r�}z(td||fdtj �d}WYdd}~XnXt
j|�r�t�|dd�tj
|�qtj|�qWdS)Nz-support.rmtree(): os.lstat(%r) failed with %s�filerr�T)rur�rv�join�lstat�st_mode�OSError�printr_�
__stderr__�stat�S_ISDIRr�r�r)rvrf�fullname�mode�exc)�
_rmtree_innerrTrUr�Ss
z_rmtree.<locals>._rmtree_innerr�T)r�rur�)rvrT)r�rU�_rmtreeRsr�cCs-yt|�Wnttfk
r(YnXdS)N)r��FileNotFoundError�NotADirectoryError)r�rTrTrUrhscCs'yt|�Wntk
r"YnXdS)N)r�r�)rwrTrTrUr�ns
r�cCs'yt|�Wntk
r"YnXdS)N)r�r�)rvrTrTrUrts
cCsitjj|�}tjjtjj|��}tjj||trKdnd�}tj ||�|S)alMove a PEP 3147 pyc/pyo file to its legacy pyc/pyo location.
The choice of .pyc or .pyo extension is done based on the __debug__ flag
value.
:param source: The file system path to the source file. The source file
does not need to exist, however the PEP 3147 pyc file must exist.
:return: The file system path to the legacy pyc file.
�c�o)
r]�util�cache_from_sourcerurvrw�abspathr�� __debug__�rename)�sourceZpyc_fileZup_oneZ
legacy_pycrTrTrU�make_legacy_pyczs
%r�cCs�t|�x~tjD]s}tjj||d�}t|d�t|d�ttjj|dd��ttjj|dd��qWdS)z�'Forget' a module was ever imported.
This removes the module from sys.modules and deletes any PEP 3147 or
legacy .pyc and .pyo files.
z.pyr�r��debug_overrideTFN) r
r_rvrur�rr]r�r�)rnrwr�rTrTrUr�s
cs�ttd�rtjSd}tjjd�r ddl�ddl�d}d}G�fdd�d�j�}�j j
}|j�}|s��j��n|�}�j
j�}|j||�j|��j|��j|��}|s�j��nt|j|@�s�d}q�n�tjdkr�dd lm} m�m}
m}dd
lm}| j|d��}
|
j�dkr�d}q�G�fd
d�d|�}|�}|
|�}|
j|�dks�|
j|�dkr�d}q�n|s�y1ddlm}|�}|j�|j �Wq�t!k
r�}zUt"|�}t#|�dkry|dd�d}ndj$t%|�j&|�}WYdd}~Xq�Xn|t_'|t_tjS)N�resultr�rr�csCeZdZd�jjfd�jjfd�jjfgZdS)z*_is_gui_available.<locals>.USEROBJECTFLAGSZfInheritZ fReserved�dwFlagsN)rPrQrR�wintypesZBOOL�DWORD�_fields_rT)�ctypesrTrU�USEROBJECTFLAGS�sr�z,gui not available (WSF_VISIBLE flag not set)�darwin)�cdll�c_int�pointer� Structure)�find_libraryZApplicationServicesz0gui tests cannot run without OS X window managercs(eZdZd�fd�fgZdS)z._is_gui_available.<locals>.ProcessSerialNumberZ
highLongOfPSNZlowLongOfPSNN)rPrQrRr�rT)r�rTrU�ProcessSerialNumber�s r�z#cannot run without OS X gui process)�Tk�2z [...]zTk unavailable due to {}: {})(�hasattr�_is_gui_availabler�r_r`rar�Zctypes.wintypesr��windllZuser32ZGetProcessWindowStationZWinErrorr�r�ZGetUserObjectInformationWZbyref�sizeof�boolr�r�r�r�Zctypes.utilr�ZLoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterr��updateZdestroy� Exceptionre�len�format�typerP�reason)r�Z UOI_FLAGSZWSF_VISIBLEr�Zdll�hZuofZneeded�resr�r�r�r�Zapp_servicesr�ZpsnZpsn_pr��root�eZ
err_stringrT)r�r�rUr��sf "
r�cCstdkp|tkS)z�Test whether a resource is enabled.
Known resources are set by regrtest.py. If not running under regrtest.py,
all resources are assumed enabled unless use_resources has been set.
N)r)�resourcerTrTrUr�scCs`|dkr(t�r(ttj��nt|�s\|dkrMd|}nt|��ndS)z@Raise ResourceDenied if the specified resource is not available.�guiNz"Use of the %r resource not enabled)r�r r�r)r�rhrTrTrUr�s
cs��fdd�}|S)z�Decorator raising SkipTest if the OS is `sysname` and the version is less
than `min_version`.
For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if
the FreeBSD version is less than 7.2.
cs4tj�����fdd��}�|_|S)Nc
s�tj��kr�tj�jdd�d}y"ttt|jd���}Wntk
rdYq�X|�kr�djtt ���}t
jd�||f��q�n�||�S)N�-r�rriz(%s version %s or higher required, not %s)r`�system�releaser�rb�map�int�
ValueErrorr�rercrd)�args�kw�version_txt�version�min_version_txt)r��min_version�sysnamerTrU�wrapper�s"
z:_requires_unix_version.<locals>.decorator.<locals>.wrapper)� functools�wrapsr�)r�r�)r�r�)r�rU� decorator�s' z)_requires_unix_version.<locals>.decoratorrT)r�r�r�rT)r�r�rU�_requires_unix_version�sr�cGs
td|�S)z�Decorator raising SkipTest if the OS is FreeBSD and the FreeBSD version is
less than `min_version`.
For example, @requires_freebsd_version(7, 2) raises SkipTest if the FreeBSD
version is less than 7.2.
ZFreeBSD)r�)r�rTrTrUrscGs
td|�S)z�Decorator raising SkipTest if the OS is Linux and the Linux version is
less than `min_version`.
For example, @requires_linux_version(2, 6, 32) raises SkipTest if the Linux
version is less than 2.6.32.
ZLinux)r�)r�rTrTrUr scs�fdd�}|S)z�Decorator raising SkipTest if the OS is Mac OS X and the OS X
version if less than min_version.
For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
is lesser than 10.5.
cs1tj����fdd��}�|_|S)Ncs�tjdkr�tj�d}y"ttt|jd���}Wntk
rUYq�X|�kr�djtt ���}t
jd||f��q�n�||�S)Nr�rriz&Mac OS X %s or higher required, not %s)r_r`Zmac_verrbr�r�r�r�r�rercrd)r�r�r�r�r�)r�r�rTrUr�*s"
z4requires_mac_ver.<locals>.decorator.<locals>.wrapper)r�r�r�)r�r�)r�)r�rUr�)s$ z#requires_mac_ver.<locals>.decoratorrT)r�r�rT)r�rUr!"sz 127.0.0.1z::1cCs/tj||�}t|�}|j�~|S)a�
Returns an unused port that should be suitable for binding. This is
achieved by creating a temporary socket with the same family and type as
the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
the specified host address (defaults to 0.0.0.0) with the port set to 0,
eliciting an unused ephemeral port from the OS. The temporary socket is
then closed and deleted, and the ephemeral port is returned.
Either this method or bind_port() should be used for any tests where a
server socket needs to be bound to a particular port for the duration of
the test. Which one to use depends on whether the calling code is creating
a python socket, or if an unused port needs to be provided in a constructor
or passed to an external program (i.e. the -accept argument to openssl's
s_server mode). Always prefer bind_port() over find_unused_port() where
possible. Hard coded ports should *NEVER* be used. As soon as a server
socket is bound to a hard coded port, the ability to run multiple instances
of the test simultaneously on the same host is compromised, which makes the
test a ticking time bomb in a buildbot environment. On Unix buildbots, this
may simply manifest as a failed test, which can be recovered from without
intervention in most cases, but on Windows, the entire python process can
completely and utterly wedge, requiring someone to log in to the buildbot
and manually kill the affected process.
(This is easy to reproduce on Windows, unfortunately, and can be traced to
the SO_REUSEADDR socket option having different semantics on Windows versus
Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
listen and then accept connections on identical host/ports. An EADDRINUSE
OSError will be raised at some point (depending on the platform and
the order bind and listen were called on each socket).
However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
will ever be raised when attempting to bind two identical host/ports. When
accept() is called on each socket, the second caller's process will steal
the port from the first caller, leaving them both in an awkwardly wedged
state where they'll no longer respond to any signals or graceful kills, and
must be forcibly killed via OpenProcess()/TerminateProcess().
The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
instead of SO_REUSEADDR, which effectively affords the same semantics as
SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
Source world compared to Windows ones, this is a common mistake. A quick
look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
openssl.exe is called with the 's_server' option, for example. See
http://bugs.python.org/issue2550 for more info. The following site also
has a very thorough description about the implications of both REUSEADDR
and EXCLUSIVEADDRUSE on Windows:
http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
XXX: although this approach is a vast improvement on previous attempts to
elicit unused ports, it rests heavily on the assumption that the ephemeral
port returned to us by the OS won't immediately be dished back out to some
other process when we close and delete our temporary socket but before our
calling code has a chance to bind the returned port. We can deal with this
issue if/when we come across it.
)�socketr=�close)�familyZsocktypeZtempsock�portrTrTrUr<Ds
8
cCs|jtjkr�|jtjkr�ttd�rc|jtjtj�dkrct d��qcnttd�r�dt
jkr�y1|jtjtj�dkr�t d��nWq�t
k
r�Yq�Xnttd�r�|jtjtjd�q�n|j|df�|j�d}|S) a%Bind the socket to a free port and return the port number. Relies on
ephemeral ports in order to ensure we are using an unbound port. This is
important as many tests may be running simultaneously, especially in a
buildbot environment. This method raises an exception if the sock.family
is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
or SO_REUSEPORT set on it. Tests should *never* set these socket options
for TCP/IP sockets. The only case for setting these options is testing
multicasting via multiple UDP sockets.
Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
on Windows), it will be set on the socket. This will prevent anyone else
from bind()'ing to our host/port for the duration of the test.
�SO_REUSEADDRr�zHtests should never set the SO_REUSEADDR socket option on TCP/IP sockets!�SO_REUSEPORTZWITHIN_PYTHON_RPM_BUILDzHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!�SO_EXCLUSIVEADDRUSEr)r�r��AF_INETr��SOCK_STREAMr�Z
getsockoptZ
SOL_SOCKETr�rru�environr�r�Z
setsockoptr��bindZgetsockname)�sock�hostr�rTrTrUr=�s $
cCsytjrud}zLy3tjtjtj�}|jtdf�dSWntk
rYYnXWd|rq|j�nXndS)z+Check whether IPv6 is enabled on this host.NrTF)r�Zhas_ipv6ZAF_INET6r�r��HOSTv6r�r�)r�rTrTrU�_is_ipv6_enabled�s
r�cs%tj���fdd��}|S)z5Skip the test on TLS certificate validation failures.csdy�||�WnLtk
r_}z,dt|�krJtjd��n�WYdd}~XnXdS)NZCERTIFICATE_VERIFY_FAILEDz.system does not contain necessary certificates)�IOErrorrercrd)r��kwargsr�)rrrTrU�dec�sz&system_must_validate_cert.<locals>.dec)r�r�)rrr�rT)rrrU�system_must_validate_cert�s! r�r�i�ZdoubleZIEEEztest requires IEEE 754 doublesz
requires zlibz
requires gzipzrequires bz2z
requires lzma�javaz$testz@testz {}_{}_tmp�æ�İ�Ł�φ�К�א�،�ت�ก� �€u-àòɘŁğr�ZNFD�nt�cer�u-共Ł♡ͣ�ztWARNING: The filename %r CAN be encoded by the filesystem encoding (%s). Unicode filename tests may not be effective��s-��surrogateescape��w����������r�ccs�d}|dkr9tj�}d}tjj|�}nRytj|�d}Wn8tk
r�|sl�ntjd|t dd�YnXz |VWd|r�t
j|�nXdS)a�Return a context manager that creates a temporary directory.
Arguments:
path: the directory to create temporarily. If omitted or None,
defaults to creating a temporary directory using tempfile.mkdtemp.
quiet: if False (the default), the context manager raises an exception
on error. Otherwise, if the path is specified and cannot be
created, only a warning is issued.
FNTz+tests may fail, unable to create temp dir: r��)�tempfileZmkdtemprurv�realpath�mkdirr�rWr�r��shutilr)rv�quietZdir_createdrTrTrU�temp_dirks"
rccs|tj�}ytj|�Wn8tk
rW|s9�ntjd|tdd�YnXztj�VWdtj|�XdS)agReturn a context manager that changes the current working directory.
Arguments:
path: the directory to use as the temporary current working directory.
quiet: if False (the default), the context manager raises an exception
on error. Otherwise, it issues only a warning and keeps the current
working directory the same.
z)tests may fail, unable to change CWD to: r�rN)ru�getcwd�chdirr�rWr�r�)rvrZ saved_dirrTrTrU�
change_cwd�s
rZtempcwdccsBtd|d|��'}t|d|��}|VWdQXWdQXdS)a�
Context manager that temporarily creates and changes the CWD.
The function temporarily changes the current working directory
after creating a temporary directory in the current directory with
name *name*. If *name* is None, the temporary directory is
created using tempfile.mkdtemp.
If *quiet* is False (default) and it is not possible to
create or change the CWD, an error is raised. If *quiet* is True,
only a warning is raised and the original CWD is used.
rvrN)rr)rfrZ temp_pathZcwd_dirrTrTrUr�s�umaskccs-tj|�}z dVWdtj|�XdS)z8Context manager that temporarily sets the process umask.N)rur)rZoldmaskrTrTrUr?�s �datacCs�tjj|�r|S|dk r:tjj||�}ntgtj}x9|D]1}tjj||�}tjj|�rQ|SqQW|S)a[Try to find a file on sys.path or in the test directory. If it is not
found the argument passed to the function is returned (this does not
necessarily signal failure; could still be the legitimate path).
Setting *subdir* indicates a relative path to use to find the file
rather than looking directly in the path directories.
N)rurv�isabsr��
TEST_HOME_DIRr_�exists)r�ZsubdirrvZdn�fnrTrTrUr�s
cCs4tj|tjtjBtjB�}tj|�dS)z>Create an empty file. If the file already exists, truncate it.N)ru�open�O_WRONLY�O_CREAT�O_TRUNCr�)r��fdrTrTrUr�s#cCs<t|j��}dd�|D�}dj|�}d|S)z%Like repr(dict), but in sorted order.cSsg|]}d|�qS)z%r: %rrT)�.0ZpairrTrTrU�
<listcomp>�s zsortdict.<locals>.<listcomp>z, z{%s})�sortedr{r�)�dictr{Z reprpairsZ
withcommasrTrTrUrN�scCs9ttd�}z|j�SWd|j�tt�XdS)z`
Create an invalid file descriptor by opening and closing a file and return
its fd.
�wbN)rr�filenor�r)r�rTrTrU�make_bad_fd�s
r'cCs|jtt|dd�dS)Nz
<test string>�exec)ZassertRaises�SyntaxError�compile)ZtestcaseZ statementrTrTrUr"�scs�ddl}ddl}�jdd��|jj|�djd�d}tjjt |�}���fdd�}tjj
|�r�||�}|dk r�|St|�ntd�t
d |d
t��|jj�}tr�|jjd�n|j|d
d�}trF|jjd�dkrFtjd|�}nzNt|d��9} |j�}
x#|
r�| j|
�|j�}
qjWWdQXWd|j�X||�}|dk r�|Std|��dS)Nr�checkr��/r�csMt|���}�dkr"|S�|�r?|jd�|S|j�dS)Nr)r�seekr�)rrr)r�r+r�rTrU�check_valid_files
z*open_urlresource.<locals>.check_valid_fileZurlfetchz fetching %s ...r��Accept-Encoding�gzipr��zContent-EncodingZfileobjr%zinvalid resource %r���)r/zgzip)Zurllib.requestZurllib.parse�pop�parseZurlparser�rurvr��
TEST_DATA_DIRrrrr�rZrequestZbuild_openerr0Z
addheadersrzrZheaders�getZGzipFile�read�writer�r)Zurlr�r��urllibr�rr.rrZopener�out�srT)r�r+r�rUr>�s:#
c@sLeZdZdZdd�Zdd�Zedd��Zdd �Zd
S)�WarningsRecorderzyConvenience wrapper for the warnings list returned on
entry to the warnings.catch_warnings() context manager.
cCs||_d|_dS)Nr)� _warnings�_last)�selfZ
warnings_listrTrTrU�__init__0s zWarningsRecorder.__init__cCs\t|j�|jkr,t|jd|�S|tjjkrBdStd||f��dS)Nr�z%r has no attribute %rr2)r�r=r>r}rW�WarningMessage�_WARNING_DETAILSr~)r?�attrrTrTrU�__getattr__4s
zWarningsRecorder.__getattr__cCs|j|jd�S)N)r=r>)r?rTrTrUrW;szWarningsRecorder.warningscCst|j�|_dS)N)r�r=r>)r?rTrTrU�reset?szWarningsRecorder.resetN) rPrQrRrSr@rD�propertyrWrErTrTrTrUr<,s
r<ccsltjd�}|jjd�}|r4|j�ntjdd��&}tjdjd�t |�VWdQXt
|�}g}x�|D]�\}}d} xg|dd�D]U}|j}
tj
|t|
�tj�r�t|
j|�r�d} |j|�q�q�W| r�|r�|j||jf�q�q�W|rKtd |d
��n|rhtd|d
��ndS)z�Catch the warnings, then check if all the expected
warnings have been raised and re-raise unexpected warnings.
If 'quiet' is True, only re-raise the unexpected warnings.
r�Z__warningregistry__�recordTrW�alwaysNFzunhandled warning %srz)filter (%r, %s) did not catch any warning)r_� _getframe� f_globalsr6�clearrWrXrj�simplefilterr<rl�message�re�matchre�I�
issubclass� __class__�removerzrP�AssertionError)�filtersrZframe�registry�wZreraiseZmissingrh�cat�seenZwarningrTrTrU�_filterwarningsCs0
rZcOsI|jd�}|s<dtff}|dkr<d}q<nt||�S)a�Context manager to silence warnings.
Accept 2-tuples as positional arguments:
("message regexp", WarningCategory)
Optional argument:
- if 'quiet' is True, it does not fail if a filter catches nothing
(default True without argument,
default False if some filters are defined)
Without argument, it defaults to:
check_warnings(("", Warning), quiet=True)
r�NT)r6�WarningrZ)rUr�rrTrTrUrFjsc@s:eZdZdZdd�Zdd�Zdd�ZdS) ra,Context manager to force import to return a new module reference.
This is useful for testing module-level behaviours, such as
the emission of a DeprecationWarning on import.
Use like this:
with CleanImport("foo"):
importlib.import_module("foo") # new reference
cGsotjj�|_xV|D]N}|tjkrtj|}|j|krZtj|j=ntj|=qqWdS)N)r_rj�copy�original_modulesrP)r?Zmodule_namesZmodule_namer|rTrTrUr@�s
zCleanImport.__init__cCs|S)NrT)r?rTrTrU� __enter__�szCleanImport.__enter__cGstjj|j�dS)N)r_rjr�r^)r?�
ignore_excrTrTrU�__exit__�szCleanImport.__exit__N)rPrQrRrSr@r_rarTrTrTrUr�s
c@s�eZdZdZdd�Zdd�Zdd�Zdd �Zd
d�Zdd
�Z dd�Z
dd�Zdd�Zdd�Z
dd�ZdS)rGz_Class to help protect the environment variable properly. Can be used as
a context manager.cCstj|_i|_dS)N)rur��_environ�_changed)r?rTrTrUr@�szEnvironmentVarGuard.__init__cCs|j|S)N)rb)r?�envvarrTrTrU�__getitem__�szEnvironmentVarGuard.__getitem__cCs<||jkr+|jj|�|j|<n||j|<dS)N)rcrbr6)r?rd�valuerTrTrU�__setitem__�szEnvironmentVarGuard.__setitem__cCsK||jkr+|jj|�|j|<n||jkrG|j|=ndS)N)rcrbr6)r?rdrTrTrU�__delitem__�szEnvironmentVarGuard.__delitem__cCs
|jj�S)N)rb�keys)r?rTrTrUri�szEnvironmentVarGuard.keyscCs
t|j�S)N)�iterrb)r?rTrTrU�__iter__�szEnvironmentVarGuard.__iter__cCs
t|j�S)N)r�rb)r?rTrTrU�__len__�szEnvironmentVarGuard.__len__cCs|||<dS)NrT)r?rdrfrTrTrU�set�szEnvironmentVarGuard.setcCs||=dS)NrT)r?rdrTrTrU�unset�szEnvironmentVarGuard.unsetcCs|S)NrT)r?rTrTrUr_�szEnvironmentVarGuard.__enter__cGshxU|jj�D]D\}}|dkrG||jkrT|j|=qTq||j|<qW|jt_dS)N)rcr{rbrur�)r?r`�k�vrTrTrUra�szEnvironmentVarGuard.__exit__N)rPrQrRrSr@rergrhrirkrlrmrnr_rarTrTrTrUrG�sc@s:eZdZdZdd�Zdd�Zdd�ZdS) �
DirsOnSysPatha�Context manager to temporarily add directories to sys.path.
This makes a copy of sys.path, appends any directories given
as positional arguments, then reverts sys.path to the copied
settings when the context ends.
Note that *all* sys.path modifications in the body of the
context manager, including replacement of the object,
will be reverted at the end of the block.
cGs6tjdd�|_tj|_tjj|�dS)N)r_rv�original_value�original_object�extend)r?�pathsrTrTrUr@�szDirsOnSysPath.__init__cCs|S)NrT)r?rTrTrUr_�szDirsOnSysPath.__enter__cGs&|jt_|jtjdd�<dS)N)rsr_rvrr)r?r`rTrTrUra�szDirsOnSysPath.__exit__N)rPrQrRrSr@r_rarTrTrTrUrq�s
rqc@sCeZdZdZdd�Zdd�Zddddd�ZdS) r#z�Raise ResourceDenied if an exception is raised while the context manager
is in effect that matches the specified exception and attributes.cKs||_||_dS)N)r��attrs)r?r�r�rTrTrUr@�s zTransientResource.__init__cCs|S)NrT)r?rTrTrUr_�szTransientResource.__enter__NcCs}|dk ryt|j|�ryxX|jj�D]8\}}t||�sMPnt||�|kr.Pq.q.Wtd��ndS)z�If type_ is a subclass of self.exc and value has attributes matching
self.attrs, raise ResourceDenied. Otherwise let the exception
propagate (if any).Nz%an optional resource is not available)rQr�rvr{r�r}r )r?Ztype_rf� tracebackrCZ
attr_valuerTrTrUra�szTransientResource.__exit__)rPrQrRrSr@r_rarTrTrTrUr#�s�errnor�g>@�errnosc #s�dd d!d"d#g}d%d'd)d+d,g}td|��|�g��sudd�|D��dd�|D��n���fdd�}tj�}z'y%|dk r�tj|�ndVWn�tjk
r}z2tr�tjj �j
dd�n�|�WYdd}~Xn�tk
r�}z�xr|j
}t|�dkrht
|dt�rh|d}q-t|�dkr�t
|dt�r�|d}q-Pq-W||��WYdd}~XnXWdtj|�XdS)-z�Return a context manager that raises ResourceDenied when various issues
with the Internet connection manifest themselves as exceptions.�ECONNREFUSED�o�
ECONNRESET�h�EHOSTUNREACH�q�ENETUNREACH�e� ETIMEDOUT�n� EAI_AGAINr�EAI_FAILr��
EAI_NONAMEr��
EAI_NODATA��
WSANO_DATA�*zResource %r is not availablecSs(g|]\}}tt||��qSrT)r}rx)r!rf�numrTrTrUr")s z&transient_internet.<locals>.<listcomp>cSs(g|]\}}tt||��qSrT)r}r�)r!rfr�rTrTrUr"+s cs�t|dd�}t|tj�s�t|tj�rB|�ks�t|tjj�rvd|jkoqdkns�t|tjj �r�d|j
ks�d|j
ks�|�kr�ts�tj
j�jdd�n�|�ndS)Nrxi�iW�ConnectionRefusedError�TimeoutErrorr�
)r}�
isinstancer�r�Zgaierrorr9�errorZ HTTPError�codeZURLErrorr�rr_�stderrr8r�)�err�n)�captured_errnos�denied�
gai_errnosrTrU�filter_error.sz(transient_internet.<locals>.filter_errorNrr�r�)rzr{)z
ECONNRESETr})r~r)r�r�)z ETIMEDOUTr����)r�r����)r�r����)r�r����)r�r�)r�r�)r r�ZgetdefaulttimeoutZsetdefaulttimeout�nntplibZNNTPTemporaryErrorrr_r�r8r�r�r�r�) Z
resource_namer�ryZdefault_errnosZdefault_gai_errnosr�Zold_timeoutr��arT)r�r�r�rUr'sN
%
%
c
cs[ddl}tt|�}tt||j��ztt|�VWdtt||�XdS)z�Return a context manager used by captured_stdout/stdin/stderr
that temporarily replaces the sys stream *stream_name* with a StringIO.rN)�ior}r_�setattr�StringIO)Zstream_namer�Zorig_stdoutrTrTrU�captured_output[sr�cCs
td�S)z�Capture the output of sys.stdout:
with captured_stdout() as stdout:
print("hello")
self.assertEqual(stdout.getvalue(), "hello\n")
r�)r�rTrTrTrUrgscCs
td�S)z�Capture the output of sys.stderr:
with captured_stderr() as stderr:
print("hello", file=sys.stderr)
self.assertEqual(stderr.getvalue(), "hello\n")
r�)r�rTrTrTrUrpscCs
td�S)a Capture the input to sys.stdin:
with captured_stdin() as stdin:
stdin.write('hello\n')
stdin.seek(0)
# call test code that consumes from sys.stdin
captured = input()
self.assertEqual(captured, "hello")
�stdin)r�rTrTrTrUrys
cCs8tj�tr tjd�ntj�tj�dS)a�Force as many objects as possible to be collected.
In non-CPython implementations of Python, this is needed because timely
deallocation is not guaranteed by the garbage collector. (Even in CPython
this can be the case in case of reference cycles.) This means that __del__
methods may be called later than expected and weakrefs may remain alive for
longer than expected. This function tries its best to force all garbage
objects to disappear.
g�������?N)�gcZcollectr8r�r�rTrTrTrU�
gc_collect�s
r�c
cs:tj�}tj�z dVWd|r5tj�nXdS)N)r�� isenabled�disable�enable)Zhave_gcrTrTrU�
disable_gc�s
r�cCsTtjd�pd}d}x,|j�D]}|jd�r(|}q(q(W|dkS)z,Find if Python was built with optimizations.� PY_CFLAGSr[z-O�-O0�-Og)r[r�r�)� sysconfig�get_config_varr�ra)ZcflagsZ final_optZoptrTrTrU�python_is_optimized�s
r�ZnPZ0n�gettotalrefcountZ2PZ0Pr�cCstjt|t�S)N)�struct�calcsize�_header�_align)�fmtrTrTrU�calcobjsize�sr�cCstjt|t�S)N)r�r��_vheaderr�)r�rTrTrU�calcvobjsize�sr��� cCs�ddl}tj|�}t|�tkr:|jt@s_t|�tkrot|�jt@ro||j7}ndt|�||f}|j|||�dS)Nrz&wrong size for %s: got %d, expected %d) � _testcapir_� getsizeofr�� __flags__�_TPFLAGS_HEAPTYPE�_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADZassertEqual)�testr��sizer�r�rhrTrTrU�check_sizeof�s%r�cs��fdd�}|S)Ncs4���fdd�}�j|_�j|_|S)Ncs�y.ddl}t|��}|j|�}Wn&tk
rE�YnCd}}Yn2Xx.�D]&}y|j||�PWq^Yq^Xq^Wz�||�SWd|r�|r�|j||�nXdS)Nr)�localer}� setlocaler~)r��kwdsr��categoryZorig_locale�loc)�catstrr��localesrTrU�inner�s$
z1run_with_locale.<locals>.decorator.<locals>.inner)rPrS)r�r�)r�r�)r�rUr��sz"run_with_locale.<locals>.decoratorrT)r�r�r�rT)r�r�rUrH�scs�fdd�}|S)Ncs1��fdd�}�j|_�j|_|S)Ncs�y
tj}Wn!tk
r0tjd��YnXdtjkrPtjd}nd}�tjd<|�z�||�SWd|dkr�tjd=n
|tjd<tj�XdS)Nztzset requiredZTZ)r��tzsetr~rcrdrur�)r�r�r�Zorig_tz)r��tzrTrUr��s
z-run_with_tz.<locals>.decorator.<locals>.inner)rPrS)r�r�)r�)r�rUr��szrun_with_tz.<locals>.decoratorrT)r�r�rT)r�rUrO�scCs�idd6td6td6dtd6}tjd|tjtjB�}|dkrgtd|f��ntt|j d��||j d �j
��}|a|tkr�t}n|t
dkr�td
|f��n|adS)Niro�m�g�tz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit %rr�rz$Memory limit %r too low to be useful)�_1M�_1GrNrO�
IGNORECASE�VERBOSEr�r��float�group�lower�real_max_memuse�MAX_Py_ssize_t�_2Gr)�limitZsizesr�ZmemlimitrTrTrUrLs 2 c@s:eZdZdZdd�Zdd�Zdd�ZdS) �_MemoryWatchdogz`An object which periodically watches the process' memory consumption
and prints it out.
cCs(djdtj��|_d|_dS)Nz/proc/{pid}/statm�pidF)r�ru�getpid�procfile�started)r?rTrTrUr@3sz_MemoryWatchdog.__init__cCs�yt|jd�}WnOtk
rg}z/tjdj|�t�tjj �dSWYdd}~XnXt
d�}tjtj
|gd|dtj�|_|j�d|_dS)N�rz!/proc not available for stats: {}zmemory_watchdog.pyr�r�T)rr�r�rWr�r�r�r_r��flushr�
subprocess�Popen�
executableZDEVNULL�mem_watchdogr�r�)r?rrr�Zwatchdog_scriptrTrTrU�start7s
z_MemoryWatchdog.startcCs*|jr&|jj�|jj�ndS)N)r�r�Z terminate�wait)r?rTrTrU�stopFs
z_MemoryWatchdog.stopN)rPrQrRrSr@r�r�rTrTrTrUr�.sr�cs���fdd�}|S)aADecorator for bigmem tests.
'minsize' is the minimum useful size for the test (in arbitrary,
test-interpreted units.) 'memuse' is the number of 'bytes per size' for
the test, or a good estimate of it.
if 'dry_run' is False, it means the test doesn't support dummy runs
when -M is not specified.
cs.���fdd����_��_�S)Nc
s��j}�j}ts!d}n|}ts4�rbt||krbtjd||d��ntr�tr�t�tdjd||d��t�}|j �nd}z�||�SWd|r�|j
�nXdS) Niz'not enough memory: %.1fG minimum neededirz* ... expected peak memory use: {peak:.1f}GZpeaki@i@)r��memuser�rcrdrr�r�r�r�r�)r?r�r��maxsizeZwatchdog)�dry_runrrr�rTrUr�Ws*
z.bigmemtest.<locals>.decorator.<locals>.wrapper)r�r�)rr)r�r�r�)rrr�rUr�Vs zbigmemtest.<locals>.decoratorrT)r�r�r�r�rT)r�r�r�rUr/Ls
!cs�fdd�}|S)z0Decorator for tests that fill the address space.cs^ttkrPtd
kr6tdkr6tjd��qZtjdtd��n
�|�SdS)
Nr��?r��z-not enough memory: try a 32-bit build insteadz'not enough memory: %.1fG minimum neededirll����li@)rr�rcrd)r?)rrrTrUr�{sz!bigaddrspacetest.<locals>.wrapperrT)rrr�rT)rrrUr0ysc@seZdZdd�ZdS)r(cCstj�}||�|S)N)rcZ
TestResult)r?r�r�rTrTrU�run�s
zBasicTestRunner.runN)rPrQrRr�rTrTrTrUr(�scCs|S)NrT)rrTrTrU�_id�sr�cCsP|dkr&t�r&tjtj�St|�r6tStjdj|��SdS)Nr�zresource {0!r} is not enabled)r�rc�skipr�rr�r�)r�rTrTrU�requires_resource�s
r�cCstdd�|�S)z9
Decorator for tests only applicable on CPython.
�cpythonT)�impl_detail)r�rTrTrUr1�scKs}t|�rtS|dkrpt|�\}}|r=d}nd}t|j��}|jdj|��}ntj|�S)Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or ) r9r��
_parse_guardsr#rir�r�rcr�)rh�guardsZ
guardnames�defaultrTrTrUr��s r�cCsc|sidd6dfSt|j��d}t|j��|gt|�ksXt�||fS)NTr�Fr)rl�valuesr�rT)r�Zis_truerTrTrUr��s
+r�cKs.t|�\}}|jtj�j�|�S)a5This function returns True or False depending on the host platform.
Examples:
if check_impl_detail(): # only on CPython (default)
if check_impl_detail(jython=True): # only on Jython
if check_impl_detail(cpython=False): # everywhere except on CPython
)r�r6r`Zpython_implementationr�)r�r�rTrTrUr9�scs<ttd�s�Stj���fdd��}|SdS)zEDecorator to temporarily turn off tracing for the duration of a test.�gettracecs?tj�}ztjd��||�SWdtj|�XdS)N)r_r��settrace)r�r�Zoriginal_trace)r�rTrUr��s
zno_tracing.<locals>.wrapperN)r�r_r�r�)r�r�rT)r�rU�
no_tracing�s!r�cCstt|��S)aDecorator for tests which involve reference counting.
To start, the decorator does not run the test if is not run by CPython.
After that, any trace function is unset during the test to prevent
unexpected refcounts caused by the trace function.
)r�r1)r�rTrTrU�
refcount_test�sr�cCsrg}x\|jD]Q}t|tj�rEt||�|j|�q||�r|j|�qqW||_dS)z>Recursively filter test cases in a suite based on a predicate.N)Z_testsr�rc� TestSuite�
_filter_suiterz)�suiteZpredZnewtestsr�rTrTrUr��s
r�cCs�tr'tjtjdddt�}n t�}|j|�}|j�s�t |j
�dkr~|jr~|j
dd}nLt |j�dkr�|j
r�|jdd}nd}ts�|d7}nt|��ndS) z2Run tests from a unittest.TestSuite-derived class.� verbosityr�rr�rzmultiple errors occurredz!; run in verbose mode for detailsN)
rrcZTextTestRunnerr_r�rr(r�Z
wasSuccessfulr��errorsZfailuresr)r�Zrunnerr�r�rTrTrU�
_run_suite�s
rcGs�tjtjf}tj�}x�|D]�}t|t�rx|tjkri|jtjtj|��q�t d��q%t||�r�|j|�q%|jtj
|��q%Wdd�}t||�t|�dS)z1Run tests from unittest.TestCase-derived classes.z)str arguments must be keys in sys.modulescSsJtdkrdSx3|j�jd�D]}tj|t�r&dSq&WdS)NTriF)�match_tests�idr��fnmatchZfnmatchcase)r�rfrTrTrU� case_pred
szrun_unittest.<locals>.case_predN)
rcr�ZTestCaser�rer_rjZaddTestZ
findTestCasesr�Z makeSuiter�r)ZclassesZvalid_typesr��clsrrTrTrUr)�s
cCsdS)z,Just used to check if docstrings are enabledNrTrTrTrTrU�_check_docstringssr�win32�WITH_DOC_STRINGSztest requires docstringscCs�ddl}|dkr!t}nd}|j|d|d|�\}}|rgtd||f��ntr�td|j|f�n||fS)aRun doctest on the given module. Return (#failures, #tests).
If optional argument verbosity is not specified (or is None), pass
support's belief about verbosity on to doctest. Else doctest's
usual behavior is used (it searches sys.argv for -v).
rNr�optionflagsz%d of %d doctests failedz,doctest (%s) ... %d tests with zero failures)�doctestrZtestmodrr�rP)r|r�r
rrrr�rTrTrUr*.s !cCstjj�fS)N)r_rjr]rTrTrTrU�
modules_setupIsrcCsMdd�tjj�D�}tjj�tjj|�tjj|�dS)NcSs1g|]'\}}|jd�r||f�qS)z
encodings.)ra)r!rorprTrTrUr"Ps z#modules_cleanup.<locals>.<listcomp>)r_rjr{rKr�)Z
oldmodules� encodingsrTrTrU�modules_cleanupLs
rcCs-trtj�tjj�fSdffSdS)Nr�)�_thread�_count� threading� _danglingr]rTrTrTrUrBgscGsdts
dSd}xMt|�D]?}tj�tjf}||krHPntjd�t�qWdS)N�dg{�G�z�?)r�rangerrrr�r�r�)Zoriginal_valuesZ
_MAX_COUNT�countr�rTrTrUrCms
cs/ts
�Stj���fdd��}|S)z�Use this function when threads are being used. This will
ensure that the threads are cleaned up even when the test fails.
If threading is unavailable this function does nothing.
cs)t�}z�|�SWdt|�XdS)N)rBrC)r��key)r�rTrUr��s zreap_threads.<locals>.decorator)rr�r�)r�r�rT)r�rUrDys!c Cs^ttd�rZd}xBy/tj|tj�\}}|dkrFPnWqPYqXqWndS)z�Use this function at the end of test_main() whenever sub-processes
are started. This will help ensure that no extra children (zombies)
stick around to hog resources and create problems when looking
for refleaks.
�waitpidr�rNr2)r�rur�WNOHANG)Zany_processr�ZstatusrTrTrUr@�s ccs�t|�}g}zly,x%|D]}|j�|j|�qWWn4trptdt|�t|�f�n�YnXdVWdz�|r�|�ntj�}}x�tdd�D]�}|d7}x.|D]&}|jt |tj�d��q�Wdd�|D�}|sPntr�tdt|�|f�q�q�WWdd d�|D�}|rt
jtj
�td
t|���nXXdS)Nz/Can't start %d threads, only %d threads startedr�r��<g{�G�z�?cSs"g|]}|j�r|�qSrT)�isAlive)r!r�rTrTrUr"�s z!start_threads.<locals>.<listcomp>z7Unable to join %d threads during a period of %d minutescSs"g|]}|j�r|�qSrT)r)r!r�rTrTrUr"�s zUnable to join %d threads)rlr�rzrr�r�r�rr��max�faulthandlerZdump_tracebackr_r�rT)ZthreadsZunlockr�r�ZendtimeZ starttimer�rTrTrUrE�s>
$c
cs|t||�rNt||�}t|||�z dVWdt|||�Xn*t|||�z dVWdt||�XdS)amTemporary swap out an attribute with a new object.
Usage:
with swap_attr(obj, "attr", 5):
...
This will set obj.attr to 5 for the duration of the with: block,
restoring the old value at the end of the block. If `attr` doesn't
exist on `obj`, it will be created and then deleted at the end of the
block.
N)r�r}r��delattr)rrC�new_val�real_valrTrTrUrJ�s
ccs\||kr:||}|||<z dVWd|||<Xn|||<z dVWd||=XdS)akTemporary swap out an item with a new object.
Usage:
with swap_item(obj, "item", 5):
...
This will set obj["item"] to 5 for the duration of the with: block,
restoring the old value at the end of the block. If `item` doesn't
exist on `obj`, it will be created and then deleted at the end of the
block.
NrT)r�itemrrrTrTrUrI�s
cCstjdd|�j�}|S)z�Strip the stderr of a Python process from potential debug output
emitted by the interpreter.
This will typically be run on the result of the communicate() method
of a subprocess.Popen object.
s\[\d+ refs, \d+ blocks\]\r?\n?�)rN�sub�strip)r�rTrTrU�strip_python_stderr�sr$cCs
tj�S)znReturn a list of command-line arguments reproducing the current
settings in sys.flags and sys.warnoptions.)r�Z_args_from_interpreter_flagsrTrTrTrU�args_from_interpreter_flagssr%c@s@eZdZdd�Zdd�Zdd�Zdd�Zd S)
rAcCs#tjjj|d�||_dS)Nr)�logging�handlers�BufferingHandlerr@�matcher)r?r)rTrTrUr@szTestHandler.__init__cCsdS)NFrT)r?rTrTrU�shouldFlushszTestHandler.shouldFlushcCs$|j|�|jj|j�dS)N)r��bufferrz�__dict__)r?rGrTrTrU�emits
zTestHandler.emitcKs=d}x0|jD]%}|jj||�rd}PqqW|S)zW
Look for a saved dict whose keys/values match the supplied arguments.
FT)r+r)�matches)r?r�r��drTrTrUr.szTestHandler.matchesN)rPrQrRr@r*r-r.rTrTrTrUrAs c@s.eZdZdZdd�Zdd�ZdS) rKrhrMcKsSd}xF|D]>}||}|j|�}|j|||�s
d}Pq
q
W|S)a.
Try to match a single dict with the supplied arguments.
Keys whose values are strings and which are in self._partial_matches
will be checked for partial (i.e. substring) matches. You can extend
this scheme to (for example) do regular expression matching, etc.
TF)r6�match_value)r?r/r�r�rorp�dvrTrTrUr.+s
zMatcher.matchescCsjt|�t|�kr!d}nEt|�tk sB||jkrQ||k}n|j|�dk}|S)zT
Try to match a single stored value (dv) with a supplied value (v).
Fr)r�re�_partial_matches�find)r?ror1rpr�rTrTrUr0<s !zMatcher.match_valueN)zmsgzmessage)rPrQrRr2r.r0rTrTrTrUrK'sc
Csotdk rtStd}ytjt|�d}Wn!tttfk
rWd}YnXtj|�|a|S)NrTF)�_can_symlinkrru�symlinkr��NotImplementedErrorr~rS)Zsymlink_path�canrTrTrUrJs
cCs,t�}d}|r|Stj|�|�S)z8Skip decorator for tests that require functional symlinkz*Requires functional symlink implementation)rrcr�)r��okrhrTrTrUr+Ys cCstdk rtSttd�s(d}n�tj�\}}z�ttd���}yutj|dd�tj|j�dd�t j
�}tjd|�}|dkp�t
|jd��dk}Wntk
r�d}YnXWdQXWdtt�t|�X|a|S) N�setxattrFr%s user.testr!z
2.6.(\d{1,2})r��')�
_can_xattrr�rur
Zmkstemprrr9r&r`r�rNrOr�r�r�r)r7Ztmp_fpZtmp_name�fpZkernel_versionr�rTrTrU� can_xattr`s& +
r=cCs,t�}d}|r|Stj|�|�S)zDSkip decorator for tests that require functional extended attributesz(no non-broken extended attribute support)r=rcr�)r�r8rhrTrTrUr4{s cCstjd|��g}|j}|j�}||krE|j�}nytjj||�SWntk
rtdSYnXWdQXdS)zKDetects if the file system for the specified directory is case-insensitive.�dirFN) r
ZNamedTemporaryFilerf�upperr�rurv�samefiler�)Z directory�base� base_pathZ case_pathrTrTrUr�s
c@s4eZdZdZdZdd�Zdd�ZdS)rMz�Try to prevent a crash report from popping up.
On Windows, don't display the Windows Error Reporting dialog. On UNIX,
disable the creation of coredump file.
NcCs4tjjd�rbddl}|jj|_d}|jj|�|_|jj|j|B�n�t dk r�y9t j
t j�|_t jt jd|jdf�Wq�t
tfk
r�Yq�Xntjdkr0tjddd d
gdtj�j�d}|j�dkr0td
dddd�q0n|S)z�On Windows, disable Windows Error Reporting dialogs using
SetErrorMode.
On UNIX, try to save the previous core file size limit, then set
soft limit to 0.
r�rNr�r�r�z/usr/bin/defaultsr7zcom.apple.CrashReporterZ
DialogTyper�s developerz:this test triggers the Crash Reporter, that is intentional�endr[r�T)r_r`rar�r�Zkernel32�_k32�SetErrorMode� old_valuer�Z getrlimit�RLIMIT_CORE� setrlimitr�r�r�r��PIPEZcommunicater#r�)r?r�ZSEM_NOGPFAULTERRORBOXrfrTrTrUr_�s* zSuppressCrashReport.__enter__cGs�|jdkrdStjjd�r;|jj|j�nDtdk rytjtj|j�Wqt t
fk
r{YqXndS)zARestore Windows ErrorMode or core file behavior to initial value.Nr�)rFr_r`rarDrEr�rHrGr�r�)r?r`rTrTrUra�szSuppressCrashReport.__exit__)rPrQrRrSrFr_rarTrTrTrUrM�s(cs�t���d�y�j��Wn*ttfk
rPt��d��YnXd�����fdd�}|j|�t��|�dS)z�Override 'object_to_patch'.'attr_name' with 'new_value'.
Also, add a cleanup procedure to 'test_instance' to restore
'object_to_patch' value for 'attr_name'.
The 'attr_name' should be a valid attribute for 'object_to_patch'.
FNTcs*�rt����n
t���dS)N)r�rrT)�
attr_is_local� attr_name�object_to_patchrFrTrU�cleanup�szpatch.<locals>.cleanup)r}r,r~rpZ
addCleanupr�)Z
test_instancerLrKZ new_valuerMrT)rJrKrLrFrU�patch�s
rNcCs\yddl}Wntk
r$YnX|j�rCtjd��nddl}|j|�S)zi
Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc
module is enabled.
rNzUrun_in_subinterp() cannot be used if tracemalloc module is tracing memory allocations)�tracemallocr^Z
is_tracingrcrdr��run_in_subinterp)r�rOr�rTrTrUrP�s
rPii@i@i@ii)r�r�r�r�r�r�r�rrrr)zntr)rrr r
ri@ii)�rSrPr^Zcollections.abc�collections�
contextlibrxrrr�r�r]�importlib.utilZlogging.handlersr&r�rur`rNrr�r�r�r�r_r�r
r�rcZurllib.errorr9rWrrZmultiprocessing.processZmultiprocessing�zlibr0�bz2Zlzmar��__all__r�rrrdr �contextmanagerr[r
rorqr6r7rr2rrrr�rrr�rrr
rar�r�r�r�rr�rr�rr�rrr�rr r!r:r�r�r�r<r=r�r;r�rZ
SOCK_MAX_SIZEZ
skipUnlessr��
__getformat__r3r5r,r-r.r8rfrr�r�ZFS_NONASCII� character�fsdecode�fsencode�UnicodeErrorZTESTFN_UNICODEZunicodedata� normalize�getfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversion�encode�UnicodeEncodeErrorr��decode�UnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIrrrrrr�r?rvrwr�rxZTEST_SUPPORT_DIRrr�r5rrrNr'r"r>�objectr<rZrFr�abc�MutableMappingrGrqr#r�r�r$r|r%r&r'r�rrrr�r�r�r�r�r�r�r�r�r�r�rHrOr�r�r�Z_4Gr�r�rLr�r/r0r(r�r�r1r�r�r9r�r�r�rr)rr�ZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr*rrrBrCrDr@rErJrIr$r%r'r(rArKr4rr+r;r=r4rrMrNrPrTrTrTrU�<module>sb
2 ! I >&
!1' 5 I
$#
-
#
"
?"
?>