U
    (c                  G   @   s  d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZ ddlmZ ddlmZ ddlZddlm Z  ddlm!Z! dd	lm"Z" dd
lm#Z# ddlm$Z$ ddlm%Z% ddlm&Z& ddl'm(Z( ddl'm)Z) ddl'm*Z* ddl'm+Z+ ddl,m-Z- ddl,m.Z. ddl,m/Z/ ddl,m0Z0 ddl,m1Z1 ddl,m2Z2 ddl,m3Z3 ddl,m4Z4 zddlm5Z5 W n< e6k
r4   e7  e8d ddl5Z5W 5 Q R X Y nX ej9dkrLddl:Z:ndZ:e$rbddl;m<Z< ddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcddgGZ=deej>kZ?de
j@kZAdfe
j@kpdge
j@kZBeAp&eBZCejDdhkZEe)didj ZFe#rZeF dkkZGeF dlkZHndmZGdmZHdnZIdoZJdpZKdqZLeCreIdr9 ZIeLdr9 ZLeJds9 ZJeKdr9 ZKe
jMdtkrdue
N  ZOndve
N  ZOe2dwZPe-rdxQdydzZRnd{ZReS T d|kZUe
jVWe
jVXe
jVYeZd}d}Z[e
jVXe[d~Z\e
jVWe
jVYeZZ]e$o:e% Z^e_ej`dZae_edZbe_edZce_ej`dZde_ej`dZee_ej`dZfe_edZge_ej`dZhe_ej`dZie_ej`dZje_edZkzekoelem ZnW n eok
r   dmZnY nX e_edZpe_edZqe_ej`dZre#se o e
s dkZtdd Zueu Zvewe
jxdZyezeyj{ dd e|eD Z}e~ede Ze Ze ZG dd dejZdd Zeddd@ZeddB ZddA Zedd= Zedd ZejeLfdd>Zddd?ZddU ZddT ZG dd deZeejdeLddddW Zee/efdeLdddddXZeedeLddddV ZddO Zdd ZejddN ZdddPZdddSZG dd dejZee_G ddH dHeZee?dG ddG dGeZddK Zdd ZG ddI dIZG ddJ dJZdd ZeIfddFZdddDZdddEZdddZZeedfdd[Zejfdd\Zddd]Zdd^ Zejdd_ ZddY ZddɄ Zdd` Zdda Zddb Zddd Ze$rejdddcZnejdddcZejzddф Ze$reejddӄ  dS )z
Test utilities.
    )print_functionN)AF_INET)AF_INET6)SOCK_STREAM)AIX)FREEBSD)LINUX)MACOS)POSIX)SUNOS)WINDOWS)bytes2human)memoize)print_color)supports_ipv6)PY3)FileExistsError)FileNotFoundError)range)super)u)unicode)which)mockignore      )wait_pidAPPVEYORDEVNULLGLOBAL_TIMEOUTTOLERANCE_SYS_MEM
NO_RETRIESPYPY
PYTHON_EXEROOT_DIRSCRIPTS_DIRTESTFN_PREFIXUNICODE_SUFFIXINVALID_UNICODE_SUFFIX
CI_TESTINGVALID_PROC_STATUSESTOLERANCE_DISK_USAGEIS_64BITHAS_CPU_AFFINITYHAS_CPU_FREQHAS_ENVIRONHAS_PROC_IO_COUNTERS
HAS_IONICEHAS_MEMORY_MAPSHAS_PROC_CPU_NUM
HAS_RLIMITHAS_SENSORS_BATTERYHAS_BATTERYHAS_SENSORS_FANSHAS_SENSORS_TEMPERATURESZHAS_MEMORY_FULL_INFOMACOS_11PLUSMACOS_12PLUSpyrun	terminatereap_childrenspawn_testprocspawn_zombiespawn_children_pairZThreadTaskunittestskip_on_access_deniedskip_on_not_implementedretry_on_failureTestMemoryLeakPsutilTestCaseprocess_namespacesystem_namespaceprint_sysinfoZinstall_pipZinstall_test_depschdirsafe_rmpath
create_exeZdecode_pathZencode_path
get_testfn
get_winverkernel_version
call_untilwait_for_pidwait_for_filecheck_net_addressget_free_portbind_socketbind_unix_sockettcp_socketpairunix_socketpaircreate_socketsreload_moduleimport_module_by_pathwarncopyload_shared_libis_namedtupleZ__pypy__GITHUB_ACTIONSZCIBUILDWHEELl        c                  C   sn   t  d } ttt| dd d }|dkrjtjtj	dddgdd	id
d} ttt| dd d }|S )Nr   .   )
      z-sS-cz-import platform; print(platform.mac_ver()[0])ZSYSTEM_VERSION_COMPAT0T)envuniversal_newlines)
platformmac_vertuplemapintsplit
subprocesscheck_outputsys
executable)version_strversion ru   9/tmp/pip-unpacked-wheel-l83rk7k5/psutil/tests/__init__.pymacos_version   s    
rw   )rc      )   r   Frc   i  P i      r   r   javaz$psutil-%s-z@psutil-%s-u   -ƒőős   futf8surrogateescapeu   fÀ)asciizus-asciiz..scriptscpu_affinitycpu_freq
getloadavgenvironionicememory_mapsnet_io_counterscpu_numio_countersrlimitsensors_batterysensors_fanssensors_temperaturesthreadsc                  C   s   dd } t r@tr$trtdS tdS tr6tjtj	S tdS nt
r| tj	p| tjtj	p| tdtjd d  p| t  }|std|S tjtj	}tj|st||S d S )	Nc                 S   s<   zt j| dgt jt jd W n tk
r2   Y d S X | S d S )Nz-V)stdoutstderr)ro   
check_callPIPE	Exception)exeru   ru   rv   attempt   s      
z_get_py_exe.<locals>.attemptZpypy3pypypythonzpython%s.%srb   z"can't find python exe real abspath)r`   r$   r   r   r   ospathrealpathrq   rr   r	   version_infopsutilProcessr   
ValueErrorexistsAssertionError)r   r   ru   ru   rv   _get_py_exe   s*    	

r   zr+c                 C   s    g | ]}| d rtt|qS )ZSTATUS_
startswithgetattrr   .0xru   ru   rv   
<listcomp>	  s    
r   AF_UNIXc                       sP   e Zd ZdZ fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
  ZS )
ThreadTaskz6A thread task which does nothing expect staying alive.c                    s$   t    d| _d| _t | _d S )NFMbP?)r   __init___running	_interval	threadingEvent_flagself	__class__ru   rv   r     s    
zThreadTask.__init__c                 C   s   | j j}d|| jt| f S )Nz<%s running=%s at %#x>)r   __name__r   id)r   nameru   ru   rv   __repr__  s    zThreadTask.__repr__c                 C   s   |    | S N)startr   ru   ru   rv   	__enter__#  s    zThreadTask.__enter__c                 O   s   |    d S r   )stop)r   argskwargsru   ru   rv   __exit__'  s    zThreadTask.__exit__c                 C   s(   | j rtdtj|  | j  dS )zStart thread and keep it running until an explicit
        stop() request. Polls for shutdown every 'timeout' seconds.
        zalready startedN)r   r   r   Threadr   r   waitr   ru   ru   rv   r   *  s    zThreadTask.startc                 C   s(   d| _ | j  | j r$t| j qd S )NT)r   r   settimesleepr   r   ru   ru   rv   run3  s    
zThreadTask.runc                 C   s    | j stdd| _ |   dS )z8Stop thread execution and and waits until it is stopped.zalready stoppedFN)r   r   joinr   ru   ru   rv   r   9  s    zThreadTask.stop)r   
__module____qualname____doc__r   r   r   r   r   r   r   __classcell__ru   ru   r   rv   r     s   	r   c                    s   t   fdd}|S )Nc                     s.   z | |W S  t k
r(   t   Y nX d S r   )r   r?   r   r   funru   rv   wrapperG  s
    z&_reap_children_on_err.<locals>.wrapper	functoolswrapsr   r   ru   r   rv   _reap_children_on_errF  s    r   c                 K   s   | dt | dt | dt  | dtj trJd}| d| | dkrt }zDt| d| }td	|g} t	j
| f|}t| t|d
d
d W 5 t| X n"t	j
| f|}t| t|j |S )a~  Creates a python subprocess which does nothing for 60 secs and
    return it as a subprocess.Popen instance.
    If "cmd" is specified that is used instead of python.
    By default stdin and stdout are redirected to /dev/null.
    It also attempts to make sure the process is in a reasonably
    initialized state.
    The process is registered for cleanup on reap_children().
    stdinr   cwdrg      creationflagsNz:from time import sleep;open(r'%s', 'w').close();sleep(60);re   Tdeleteempty)
setdefaultr    r   getcwdr   r   rN   rL   r%   ro   Popen_subprocesses_startedaddrS   rR   pid)cmdkwdsZCREATE_NO_WINDOWtestfnZpylinesprocru   ru   rv   r@   Q  s.    




c                  C   s   d} t t d}zztdtj|tf }t	rDt
|dd\}} nt
|\}} t|j}tt|ddd}t| t|}||fW S t| | dk	rt|  X dS )	a  Create a subprocess which creates another one as in:
    A (us) -> B (child) -> C (grandchild).
    Return a (child, grandchild) tuple.
    The 2 processes are fully initialized and will live for 60 secs
    and are registered for cleanup on reap_children().
    Ndira;              import subprocess, os, sys, time
            s = "import os, time;"
            s += "f = open('%s', 'w');"
            s += "f.write(str(os.getpid()));"
            s += "f.close();"
            s += "time.sleep(60);"
            p = subprocess.Popen([r'%s', '-c', s])
            p.wait()
            r   )r   TFr   )rN   r   r   rL   textwrapdedentr   basenamer%   r   r=   r   r   r   rm   rS   _pids_startedr   )tfiler   ssubpchildZgrandchild_pidZ
grandchildru   ru   rv   rB   y  s"    	

c                     s   t js
tt } td|  }d}t| }z|	t
 t|\}}| \}}zZt| gg g t
 t|d}t| t | t fddd | fW W S |  X W 5 |  t|  |dk	rt| X dS )zCreate a zombie process and return a (parent, zombie) process tuple.
    In order to kill the zombie parent must be terminate()d first, then
    zombie must be wait()ed on.
    a          import os, sys, time, socket, contextlib
        child_pid = os.fork()
        if child_pid > 0:
            time.sleep(3000)
        else:
            # this is the zombie process
            s = socket.socket(socket.AF_UNIX)
            with contextlib.closing(s):
                s.connect('%s')
                if sys.version_info < (3, ):
                    pid = str(os.getpid())
                else:
                    pid = bytes(str(os.getpid()), 'ascii')
                s.sendall(pid)
        N   c                      s      S r   )statusru   zombieru   rv   <lambda>      zspawn_zombie.<locals>.<lambda>zret == psutil.STATUS_ZOMBIE)r   r
   r   rN   r   r   rW   closerL   
settimeoutr!   r=   acceptselectfilenorm   recvr   r   r   rQ   )Z	unix_filesrcr   sockparentconn_Zzpidru   r   rv   rA     s.    



c              	   K   s   | dd | dd t }zFt|d}||  W 5 Q R X tt|jgf|}t|j ||fW S  t	k
r   t
|  Y nX dS )zRun python 'src' code string in a separate interpreter.
    Returns a subprocess.Popen instance and the test file where the source
    code was written.
    r   Nr   wt)r   rN   openwriter@   r%   r   rR   r   r   rL   )r   r   srcfilefr   ru   ru   rv   r=     s    

c                 K   s   t rdnd}|dtj |dtj |dd |d| t| trTt| } tj| f|}t	
| tr|jtd\}}n| \}}|jdkrt||rt| |d	r|d
d }|S )zUrun cmd in a subprocess and return its output.
    raises RuntimeError on error.
    r   r   r   r   rh   Tr   timeout
N)r   r   ro   r   
isinstancestrshlexrn   r   r   r   r   communicater!   
returncodeRuntimeErrorr]   endswith)r   r   flagspr   r   ru   ru   rv   sh  s&    




r  c              
      s   dd dd   fdd} fddfd	d
}dd }| }zbt |trb|||W LS t |tjtjfr||W ,S t |tjr|||W S t	d| W 5 t |tjtjfr|| t |tr|n|j}t|rt|X dS )a  Terminate a process and wait() for it.
    Process can be a PID or an instance of psutil.Process(),
    subprocess.Popen() or psutil.Popen().
    If it's a subprocess.Popen() or psutil.Popen() instance also closes
    its stdin / stdout / stderr fds.
    PID is wait()ed even if the process is already gone (kills zombies).
    Does nothing if the process does not exist.
    Return process exit status.
    c                 S   sd   t | tjrts|   n
| | tr`t | tjr`zt| j|W S  tj	k
r^   Y nX d S r   )
r	  ro   r   r   r   r   r   r   r   NoSuchProcessprocr  ru   ru   rv   r     s    

zterminate.<locals>.waitc                 S   s6   t rtrtj}tr(|tjkr(| tj | | d S r   )r	   r`   signalSIGKILLr
   send_signalSIGCONT)r  sigru   ru   rv   sendsig  s
    zterminate.<locals>.sendsigc              
      sZ   z |  W n@ t k
rN } z"tr0|jdkr0n|jtjkr> W 5 d }~X Y nX | |S )N   )OSErrorr   winerrorerrnoZESRCH)r  r  errr  r  r   ru   rv   term_subprocess_proc  s    z'terminate.<locals>.term_subprocess_procc                    s0   z |  W n t jk
r$   Y nX | |S r   )r   r  r  r!  ru   rv   term_psutil_proc'  s
    z#terminate.<locals>.term_psutil_procc                    sF   zt | }W n( t jk
r6   tr2t| | Y S Y nX  ||S d S r   )r   r   r  r
   r   )r   r  r  )r#  ru   rv   term_pid.  s    zterminate.<locals>.term_pidc                 S   s4   | j r| j   | jr | j  | jr0| j  d S r   )r   r   r   r   )r  ru   ru   rv   flush_popen8  s    

zterminate.<locals>.flush_popenzwrong type %rN)
r	  ro   r   r   rm   r   
pid_existsr   r   	TypeError)Zproc_or_pidr  wait_timeoutr"  r$  r%  r  r   ru   )r  r  r#  r   rv   r>     s&    



	
c                 C   s   t  j| d}tr&t }t| qtr<t }t| q&|r|D ]}t|dd qDt j|td\}}|D ]}t	d|  t|t
jd qldS )a  Terminate and wait() any subprocess started by this test suite
    and any children currently running, ensuring that no processes stick
    around to hog resources.
    If recursive is True it also tries to terminate and wait()
    all grandchildren started by this process.
    	recursiveN)r(  r  z0couldn't terminate process %r; attempting kill())r  )r   r   childrenr   popr>   r   
wait_procsr!   r]   r  r  )r*  r+  r   r   r  gonealiveru   ru   rv   r?   R  s    


c                  C   s   t stdd} t d }|D ]"}| s4|dkr>| |7 } q  qDq | sTtd| d}d}| d}t|d }t|dkrt|d }t|dkrt|d }|||fS )	z"Return a tuple such as (2, 6, 36).z	not POSIX rb   ra   zcan't parse %rr      r   )	r
   NotImplementedErrorr   unameisdigitr   rn   rm   len)r   r3  cminormicronumsmajorru   ru   rv   rP   w  s&    

c                  C   sd   t stdt } t| dr*| jp&d}n(td| d }|rNt|	d}nd}| d | d |fS )Nznot WINDOWSservice_pack_majorr   z\s\d$r   r1  )
r   r2  rq   getwindowsversionhasattrr;  researchrm   group)Zwvsprru   ru   rv   rO     s    
c                   @   s<   e Zd ZdZeddddfddZdd Zdd	 Zd
d ZdS )retryzA retry decorator.Nr   c                 C   s2   |r|rt d|| _|| _|| _|| _|| _d S )Nz/timeout and retries args are mutually exclusive)r   	exceptionr  retriesintervallogfun)r   rD  r  rE  rF  rG  ru   ru   rv   r     s    zretry.__init__c                 c   sT   | j r*t | j  }t |k rPd V  qn&| jrHt| jD ]
}d V  q:nd V  qHd S r   )r  r   rE  r   )r   stop_atr   ru   ru   rv   __iter__  s    

zretry.__iter__c                 C   s   | j d k	rt| j  d S r   )rF  r   r   r   ru   ru   rv   r     s    
zretry.sleepc                    s"   t   fdd}|_|S )Nc                     s|   d }D ]b}z | |W   S  j k
rh } z,|}jd k	rH|   W Y qW 5 d }~X Y qX qtrv|n d S r   )rD  rG  r   r   )r   r   excr   r   r   ru   rv   r     s    

zretry.__call__.<locals>.wrapper)r   r   	decorator)r   r   r   ru   rK  rv   __call__  s    zretry.__call__)	r   r   r   r   r   r   rI  r   rM  ru   ru   ru   rv   rC    s   
rC  r   )rD  rG  r  rF  c                 C   s   t |  trtd dS )zWait for pid to show up in the process list then return.
    Used in the test suite to give time the sub process to initialize.
    {Gz?N)r   r   r   r   r   )r   ru   ru   rv   rR     s    
Tc              	   C   s:   t | d}| }W 5 Q R X |s*|s*t|r6t|  |S )z8Wait for a file to be written on disk with some content.rb)r  readr   rL   )fnamer   r   r  dataru   ru   rv   rS     s    c                 C   s   |  }t |st|S )zVKeep calling function for timeout secs and exit if eval()
    expression is True.
    )evalr   )r   exprretru   ru   rv   rQ     s    c                 C   sn   dd }zLt | }t|jr0ttj| }ntt j| }t	rJ|  n|| W n t
k
rh   Y nX dS )z?Convenience function for removing temporary test files or dirs.c              
   S   s~   t   t }t   |k rvz|  W S  tk
r4   Y n6 tk
rh } z|}tdt|  W 5 d }~X Y nX t d q|d S )Nzignoring %srN  )r   r!   r   ZWindowsErrorr]   r
  r   )r   rH  r   r   ru   ru   rv   	retry_fun  s    "zsafe_rmpath.<locals>.retry_funN)r   statS_ISDIRst_moder   partialshutilrmtreeremover
   r   )r   rV  str   ru   ru   rv   rL     s    
c                 C   s(   zt |  W n tk
r"   Y nX dS )z.Convenience function for creating a directory.N)r   mkdirr   r   ru   ru   rv   
safe_mkdir'  s    r`  c              	   c   s.   t  }zt |  dV  W 5 t | X dS )z@Context manager which temporarily changes the current directory.N)r   r   rK   )dirnamecurdirru   ru   rv   rK   /  s
    

c              	   C   s   t j| rt| |rtds(tdt|tr<t	d}t|t
sNt|ttddd}|| W 5 Q R X ztd|jd| g W 5 t|j X n.tt|  trt | }t | |jtjB  dS )	z1Creates an executable file in the given location.gcczgcc is not installedz
                #include <unistd.h>
                int main() {
                    pause();
                    return 1;
                }
                z.csuffixr   z-oN)r   r   r   r   r   r   r	  boolr   r   r
  r  rN   r  rL   r   ro   r   r[  copyfiler%   r
   rW  chmodrY  S_IEXEC)ZoutpathZc_coder  r^  ru   ru   rv   rM   :  s$    

r0  c                 C   s.   t jt| |d}tj|s tj|S q dS )zReturn an absolute pathname of a file or dir that did not
    exist at the time this call is made. Also schedule it for safe
    deletion at interpreter exit. It's technically racy but probably
    not really due to the time variant.
    )prefixre  r   N)tempfilemktempr(   r   r   r   r   )re  r   r   ru   ru   rv   rN   X  s    c                   @   sB   e Zd Zdd Zeejds$ejjZe	s>dd Z
ejdd ZdS )	TestCasec                 C   s.   | j j}|dsd| }d|| j j| jf S )Nzpsutil.zpsutil.tests.z%s.%s.%s)r   r   r   r   Z_testMethodName)r   Zfqmodru   ru   rv   __str__m  s    
  zTestCase.__str__assertRaisesRegexc                 C   s   d S r   ru   r   ru   ru   rv   runTest{  s    zTestCase.runTestc                 o   s
   d V  d S r   ru   )r   r   kwru   ru   rv   subTest~  s    zTestCase.subTestN)r   r   r   rn  r=  unittestrm  ZassertRaisesRegexpro  r   rp  
contextlibcontextmanagerrr  ru   ru   ru   rv   rm  i  s   	rm  c                   @   sB   e Zd ZdZdddZdd Zdd	 Zd
d Zdd Zdd Z	dS )rG   zUTest class providing auto-cleanup wrappers on top of process
    test utilities.
    r0  Nc                 C   s   t ||d}| t| |S )N)re  r   )rN   
addCleanuprL   )r   re  r   rQ  ru   ru   rv   rN     s    zPsutilTestCase.get_testfnc                 O   s   t ||}| t| |S r   )r@   rv  r>   )r   r   r   r   ru   ru   rv   r@     s    
zPsutilTestCase.spawn_testprocc                 C   s*   t  \}}| t| | t| ||fS r   )rB   rv  r>   )r   Zchild1Zchild2ru   ru   rv   rB     s    
z"PsutilTestCase.spawn_children_pairc                 C   s*   t  \}}| t| | t| ||fS r   )rA   rv  r>   )r   r   r   ru   ru   rv   rA     s    
zPsutilTestCase.spawn_zombiec                 O   s*   t ||\}}| t| | t| |S r   )r=   rv  rL   r>   )r   r   r   r   r  ru   ru   rv   r=     s    zPsutilTestCase.pyrunc                 C   s   |  tjtj|j t|tjtjfrn| r2tz|	 }W n tjk
rT   Y nX td| |j
dd t|jrt|j| |jt  d S )Nz3Process.status() didn't raise exception (status=%s)r   r  )assertRaisesr   r  r   r   r	  r   
is_runningr   r   r   r&  ZassertNotInpids)r   r  r   ru   ru   rv   assertProcessGone  s    z PsutilTestCase.assertProcessGone)r0  N)
r   r   r   r   rN   r@   rB   rA   r=   rz  ru   ru   ru   rv   rG     s   
zunreliable on PYPYc                   @   s   e Zd ZdZdZdZdZer dndZdZ	e
 ZeeddZedd	 Zed
d Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZdddZdd ZdS ) rF   a  Test framework class for detecting function memory leaks,
    typically functions implemented in C which forgot to free() memory
    from the heap. It does so by checking whether the process memory
    usage increased before and after calling the function many times.

    Note that this is hard (probably impossible) to do reliably, due
    to how the OS handles memory, the GC and so on (memory can even
    decrease!). In order to avoid false positives, in case of failure
    (mem > 0) we retry the test for up to 5 times, increasing call
    repetitions each time. If the memory keeps increasing then it's a
    failure.

    If available (Linux, OSX, Windows), USS memory is used for comparison,
    since it's supposed to be more precise, see:
    https://gmpy.dev/blog/2016/real-process-memory-and-environ-in-python
    If not, RSS memory is used. mallinfo() on Linux and _heapwalk() on
    Windows may give even more precision, but at the moment are not
    implemented.

    PyPy appears to be completely unstable for this framework, probably
    because of its JIT, so tests on PYPY are skipped.

    Usage:

        class TestLeaks(psutil.tests.TestMemoryLeak):

            def test_fun(self):
                self.execute(some_function)
       rc   r   rz   TZPSUTIL_DEBUGc                 C   s   t d d S )NF)r   
_set_debugclsru   ru   rv   
setUpClass  s    zTestMemoryLeak.setUpClassc                 C   s   t | j d S r   )r   r|  _psutil_debug_origr}  ru   ru   rv   tearDownClass  s    zTestMemoryLeak.tearDownClassc                 C   s   | j  }t|d|jS )NZuss)	_thisprocmemory_full_infor   Zrss)r   memru   ru   rv   _get_mem  s    
zTestMemoryLeak._get_memc                 C   s   t r| j S | j S d S r   )r
   r  num_fdsnum_handlesr   ru   ru   rv   _get_num_fds  s    
zTestMemoryLeak._get_num_fdsc                 C   s   | j rt|dtjd d S )NZyellow)colorfile)verboser   rq   r   )r   msgru   ru   rv   _log  s    zTestMemoryLeak._logc                 C   sx   |   }| | |   }|| }|dk r8| d| |dkrttrHdnd}|dkr\|d7 }d|||f }| |dS )	zMakes sure num_fds() (POSIX) or num_handles() (Windows) does
        not increase after calling a function.  Used to discover forgotten
        close(2) and CloseHandle syscalls.
        r   zHnegative diff %r (gc probably collected a resource from a previous test)fdhandler1  r   z%s unclosed %s after calling %rN)r  callfailr
   )r   r   beforeafterdifftype_r  ru   ru   rv   
_check_fds  s    
zTestMemoryLeak._check_fdsc                 C   s^   t jdd |  }t|D ]}| |}~~qt jdd |  }| t jg  || }|S )zGet 2 distinct memory samples, before and after having
        called fun repeatedly, and return the memory difference.
        r1  )Z
generation)gcZcollectr  r   r  assertEqualgarbage)r   r   timesZmem1r   rU  Zmem2r  ru   ru   rv   _call_ntimes  s    
zTestMemoryLeak._call_ntimesc                 C   s   g }d}|}t d|d D ]}	| ||}
d|	t|
t|
| |f }|| |
|kp^|
|k}|r||	dkrv| |  d S |	dkrt  | | ||7 }|
}q| d|d S )Nr   r1  z,Run #%s: extra-mem=%s, per-call=%s, calls=%sz. )r   r  r   appendr  printr  r   )r   r   r  warmup_timesrE  	tolerancemessagesZprev_memZincreaseidxr  r  successru   ru   rv   
_check_mem  s.      
 


zTestMemoryLeak._check_memc                 C   s   | S r   ru   )r   r   ru   ru   rv   r  3  s    zTestMemoryLeak.callNc              
   C   s   |dk	r|n| j }|dk	r|n| j}|dk	r0|n| j}|dk	rB|n| j}zD|dksZtd|dksjtd|dksztd|dkstdW n. tk
r } ztt|W 5 d}~X Y nX | || | | | j	|||||d dS )	zTest a callable.Nr1  ztimes must be >= 1r   zwarmup_times must be >= 0zretries must be >= 0ztolerance must be >= 0)r  r  rE  r  )
r  r  rE  r  r   r   r
  r  r  r  )r   r   r  r  rE  r  r   ru   ru   rv   execute6  s&    

 zTestMemoryLeak.executec                    s"    fdd}j |f| dS )znConvenience method to test a callable while making sure it
        raises an exception on every call.
        c                      s      d S r   )rw  ru   rJ  r   r   ru   rv   r  O  s    z*TestMemoryLeak.execute_w_exc.<locals>.callN)r  )r   rJ  r   r   r  ru   r  rv   execute_w_excK  s    zTestMemoryLeak.execute_w_exc)NNNN)r   r   r   r   r  r  r  r+   rE  r  r   r   r  rf  r   getenvr  classmethodr  r  r  r  r  r  r  r  r  r  r  ru   ru   ru   rv   rF     s.   

  
c                  C   s  dd l } dd l}dd l}dd l}dd l}dd l}zdd l}W n tk
rT   d }Y nX zdd l}W n tk
rz   d }Y nX | 	 }t
jrtdrtd|d< n~t
jrd| d  |d< nbt
jrddtt|  |d< t|dr|d  d	|  7  < nd
| | f |d< d	t| | g |d< t
jrV| d |d< d	| | |  g|d< t!|dd|d< |d k	r|d  d|j" 7  < t
jrtdrtddg}	t|	#dd |d< nd|d< |$ d }
|
r|
|d< t%& |d< |' }d|d |d f |d< |j(t
) *d|d< |j+ *d|d< |, |d< t-j./d|d < t-0 |d!< t1|d"< |2 |d#< t-3 |d$< t
4 |d%< d&t5d'd( t
6 D  |d)< t
7 }d*t8|j9t:|j;t:|j<f |d+< t
= }d*t8|j9t:|j;t:|j<f |d,< t>t
? |d-< t
@ A }|Bd.d  |C||d/< tDd0t%jEd1 |F D ]$\}}tDd2|d3 |f t%jEd1 qntDd0t%jEd1 t%jGH  d S )4Nr   lsb_releasezlsb_release -d -sZOSz	Darwin %szWindows  win32_editionz, z%s %sarchrb   kernelr   __version__znot installedpipz (wheel=%s)rc  z	--versionr  r1  glibczfs-encodingz%s, %slangz%Y-%m-%d %H:%M:%Sz	boot-timer   user~homer   ZpyexehostnameZPIDZcpusz%.1f%%, %.1f%%, %.1f%%c                 S   s   g | ]}|t   d  qS )d   )r   	cpu_countr   ru   ru   rv   r     s     z!print_sysinfo.<locals>.<listcomp>Zloadavgz%s%%, used=%s, total=%sZmemoryswapry  r   r  zF======================================================================r  z%-17s %s:)Icollectionsdatetimegetpasslocaleri   pprintr  ImportErrorwheelOrderedDictr   r   r   r  ZOSXrj   r   r   rl   r
  	win32_verr=  r  systemrt   listarchitecturemachiner
   r3  python_implementationpython_versionpython_compilerr   r  rn   libc_verrq   getfilesystemencoding	getlocalefromtimestamp	boot_timestrftimenowgetuserr   r   
expanduserr   r%   nodegetpidr  rk   r   virtual_memoryrm   percentr   usedtotalswap_memoryr5  ry  r   as_dictr,  pformatr  r   itemsr   flush)r  r  r  r  ri   r  r  r  infooutr   r  r  r  Zpinfokvru   ru   rv   rJ   U  s    





  
  
c                  C   s6   t  } t| dr|  S t| dr2t|  S dS )Nr   r   r   )r   r   r=  r   randomchoicer   )r  ru   ru   rv   _get_eligible_cpu  s    

r  c                   @   sB  e Zd ZdZddi fddi fgZddi fddddifd	di fd
di fddi fddi fddi fddi fddi fg	Zddi fddddifddi fddi fddi fddi fddi fddi fddi fddi fddi fddi fddi fd di fd!di fd"di fd#di fgZerFed$di fg7 Zed%di fg7 Zed&di fg7 Zed'di fg7 Zer\ed(di fg7 Ze	rred)di fg7 Ze
red*ejfi fg7 Zered+di fg7 Zered,di fg7 Zered-di fg7 Zered.di fg7 Zered/dd0d1ifg7 Zg Zereddi fg7 Znedejfi fg7 Ze
rJed*ejd2fi fg7 Ze	rerned)ejd3fi fg7 Zned)ejfi fg7 Zered+e gfi fg7 Zd4ejfi fd5di fd6di fd7di fd8di fgZered4ejfi fg7 Zed4ejfi fg7 Zee e e Zd9d: ZdDd;d<Zd=d> Z e!d?d@ Z"e!dAdB Z#dCS )ErH   a  A container that lists all Process class method names + some
    reasonable parameters to be called with. Utility methods (parent(),
    children(), ...) are excluded.

    >>> ns = process_namespace(psutil.Process())
    >>> for fun, name in ns.iter(ns.getters):
    ...    fun()
    cpu_percentru   Zmemory_percentr  r+  r*  Trx  Zmemory_info_exZoneshotr   parentsr   r   r   Zcmdlineconnectionskindall	cpu_timesZcreate_timer   r   r  Zmemory_infor   niceZnum_ctx_switchesZnum_threadsZ
open_filesZppidr   r   usernameZuidsZgidsZterminalr  r   r   r   r   r   r   r  r   ZgroupedF)r   i   r   r  Zsuspendresumer>   killc                 C   s
   || _ d S r   )_proc)r   r  ru   ru   rv   r     s    zprocess_namespace.__init__c                 c   sZ   t |}t| |D ]>\}}}|r,|   t| j|}tj|f||}||fV  qdS z_Given a list of tuples yields a set of (fun, fun_name) tuples
        in random order.
        N)r  r  shuffleclear_cacher   r  r   rZ  )r   lsr  fun_namer   r   r   ru   ru   rv   iter  s    
zprocess_namespace.iterc                 C   s   | j j| j jdd dS )z&Clear the cache of a Process instance.T)Z_ignore_nspN)r  _initr   r   ru   ru   rv   r  (  s    zprocess_namespace.clear_cachec                 C   s>   |D ]4\}}}d| }t ||sd|jj|f }t|qdS )z}Given a TestCase instance and a list of tuples checks that
        the class defines the required test method names.
        Ztest_z$%r class should define a '%s' methodN)r=  r   r   AttributeError)r~  Z
test_classr  r  r   	meth_namer  ru   ru   rv   test_class_coverage,  s    
 z%process_namespace.test_class_coveragec                 C   s`   t dd | jD }t dd | jD }t dd ttjD }||B |A }|r\td| d S )Nc                 S   s   g | ]}|d  qS r  ru   r   ru   ru   rv   r   :  s     z*process_namespace.test.<locals>.<listcomp>c                 S   s   g | ]}|d  qS r  ru   r   ru   ru   rv   r   ;  s     c                 S   s   g | ]}|d  dkr|qS )r   r   ru   r   ru   ru   rv   r   <  s      z!uncovered Process class names: %r)r   r  ignoredr   r   r   r   )r~  thisr  klassZleftoutru   ru   rv   test8  s    zprocess_namespace.testN)T)$r   r   r   r   utilsr  gettersr
   r2   r3   r6   r   ZRLIMIT_NOFILEr/   r5   r1   r   r4   ZsettersZNORMAL_PRIORITY_CLASSr   ZIOPRIO_CLASS_NONEZIOPRIO_NORMALr  r  SIGTERMZkillersZCTRL_C_EVENTZCTRL_BREAK_EVENTr  r   r  r  r  r  r  ru   ru   ru   rv   rH     s   	

c                   @   s  e Zd ZdZddi fddddifddddifddi fd	dd
difd	dd
difddddifddddifde fi fddddifddi fddi fddddifde fi fddi fddi fddi fddi fgZereddd
difg7 Ze	reddi fg7 Ze
reddi fg7 Zer$eddi fg7 Zer:eddi fg7 Zer`ed di fg7 Zed!d"i fg7 Zd#di fd$e gfi fd%di fd&di fgZeZed'd( ZejZd)S )*rI   zA container that lists all the module-level, system-related APIs.
    Utilities such as cpu_percent() are excluded. Usage:

    >>> ns = system_namespace
    >>> for fun, name in ns.iter(ns.getters):
    ...    fun()
    r  ru   r  logicalFTZ	cpu_statsr  ZpercpuZdisk_io_countersZperdiskZdisk_partitionsr  
disk_usageZnet_connectionsr  Znet_if_addrsZnet_if_statsr   Zpernicr&  ry  r  Zusersr  r   r   r   r   r   Zwin_service_iterZwin_service_get)ZalgZprocess_iterr-  r  Zcpu_times_percentc                 c   sL   t | } t|  | D ]0\}}}tt|}tj|f||}||fV  qdS r  )r  r  r  r   r   r   rZ  )r  r  r   r   r   ru   ru   rv   r  u  s    

zsystem_namespace.iterN)r   r   r   r   r   r   r  r  r0   HAS_GETLOADAVGr:   r9   r7   r   r   r   r  r  staticmethodr  rH   r  ru   ru   ru   rv   rI   B  sT   
c                 C   s   t | st| d| _| S )zA decorator to mark a TestCase class. When running parallel tests,
    class' unit tests will be run serially (1 process).
    T)inspectisclassr   Z
_serialrun)r  ru   ru   rv   	serialrun  s    r	  c                 C   s   dd }t td| |dS )zZDecorator which runs a test function and retries N times before
    actually failing.
    c                 S   s   t d|  tjd d S )Nz%r, retryingr  )r  rq   r   )rJ  ru   ru   rv   rG    s    z retry_on_failure.<locals>.logfunN)rD  r  rE  rG  )rC  r   )rE  rG  ru   ru   rv   rE     s    c                    s    fdd}|S )z,Decorator to Ignore AccessDenied exceptions.c                    s   t   fdd}|S )Nc                     s@   z | |W S  t jk
r:   d k	r,s, tdY nX d S )Nzraises AccessDenied)r   ZAccessDeniedrs  SkipTestr   r   only_ifru   rv   r     s    z9skip_on_access_denied.<locals>.decorator.<locals>.wrapperr   r   r  r   rv   rL    s    z(skip_on_access_denied.<locals>.decoratorru   r  rL  ru   r  rv   rC     s    c                    s    fdd}|S )z3Decorator to Ignore NotImplementedError exceptions.c                    s   t   fdd}|S )Nc                     sH   z | |W S  t k
rB   d k	r*s* d j }t|Y nX d S )Nz4%r was skipped because it raised NotImplementedError)r2  r   rs  r
  )r   r   r  r  ru   rv   r     s    z;skip_on_not_implemented.<locals>.decorator.<locals>.wrapperr   r   r  r   rv   rL    s    
z*skip_on_not_implemented.<locals>.decoratorru   r  ru   r  rv   rD     s    	127.0.0.1c              
   C   s@   t t (}|| df | d W  5 Q R  S Q R X dS )z6Return an unused TCP port. Subject to race conditions.r   r1  N)rt  closingsocketbindgetsockname)hostr   ru   ru   rv   rU     s    c                 C   s   |dkr| t tfkrd}t| |}z@tjdkrB|tjtjd || |tj	kr`|
d |W S  tk
r   |   Y nX dS )zBinds a generic socket.Nr0  r   )ntcygwinr1  rz   )r   r   r  r   r   
setsockopt
SOL_SOCKETSO_REUSEADDRr  r   listenr   r   )familytypeaddrr   ru   ru   rv   rV     s    



c                 C   sr   t js
ttj| rt| ttj|}z"||  |tj	krL|
d W n tk
rl   |   Y nX |S )zBind a UNIX socket.rz   )r   r
   r   r   r   r   r  r   r  r   r  r   r   )r   r  r   ru   ru   rv   rW     s    


r  c              
   C   s   t t| t}|| |d | }t| t}zJ|| | }| \}}||krz||fW W  5 Q R  S |	  qPW n t
k
r   |	   Y nX W 5 Q R X dS )z^Build a pair of TCP sockets connected to each other.
    Return a (server, client) tuple.
    rz   N)rt  r  r  r   r  r  r  connectr   r   r  )r  r  Zllr6  Zcaddraru   ru   rv   rX     s    


c                 C   s   t js
td }}z@t| tjd}|d ttjtj}|d ||  W n6 t	k
r   |dk	rr|
  |dk	r|
   Y nX ||fS )zBuild a pair of UNIX sockets connected to each other through
    the same UNIX file name.
    Return a (server, client) tuple.
    Nr  r   )r   r
   r   rW   r  r   setblockingr   r  r   r   )r   serverclientru   ru   rv   rY     s    


c               	   c   s   g } d }}z| ttjtj | ttjtj t rd| ttj	tj | ttj	tj t
rtrt }t }t|\}}t|tjd}|||fD ]}| | q| V  W 5 | D ]}|   q||fD ]}|dk	rt| qX dS )z1Open as many socket families / types as possible.Nr!  )r   rL   r  rV   r  r   r   
SOCK_DGRAMr   r   r
   HAS_CONNECTIONS_UNIXrN   rY   rW   )socksZfname1Zfname2r   rQ  s1s2Zs3ru   ru   rv   rZ     s*    

c                 C   s   ddl }tr(tr(ts(t|tjs(t||tjkrdd | 	dD }t
|dksZt| |D ]"}d|  krvdks^n t| q^tst| } ||  nb|tjkrt| tst| tst| } ||  n.|tjkrtd| dk	st| n
td	|dS )
z[Check a net address validity. Supported families are IPv4,
    IPv6 and MAC addresses.
    r   Nc                 S   s   g | ]}t |qS ru   )rm   r   ru   ru   rv   r   9  s     z%check_net_address.<locals>.<listcomp>ra   r      z([a-fA-F0-9]{2}[:|\-]?){6}zunknown family %r)	ipaddressenumr   r$   r	  IntEnumr   r  r   rn   r5  r   IPv4Addressr   r
  IPv6Addressr   ZAF_LINKr>  matchr   )r  r  r+  Zoctsnumru   ru   rv   rT   1  s&    
 

c                 C   sT   dd }dd }dd }dd }d	d
 }||  ||  ||  ||  ||  dS )z*Check validity of a connection namedtuple.c                 S   s   t | dk}t | dks$tt | | d | jks<t| j| d | jksTt| j| d | jkslt| j| d | jkst| j| d | jkst| j| d | jkst| j|r| d	 | jkst| jd S )
N   )r  r2  r   r1  rb   r   r   rz   r  )	r5  r   r  r  r  laddrraddrr   r   )r   Zhas_pidru   ru   rv   check_ntupleM  s    z-check_connection_ntuple.<locals>.check_ntuplec                 S   s   | j tttfkst| j td k	r:t| j tjsNt| nt| j tsNt| | j tkrt		| j | j
}t|R z|| jd df W n2 t	jk
r } z|jtjkr W 5 d }~X Y nX W 5 Q R X n | j tkr| jtjkst| jd S )Nr   )r  r   r   r   r   r,  r	  r-  rm   r  r  rt  r  r  r3  errorr  ZEADDRNOTAVAILr   r   	CONN_NONE)r   r   r   ru   ru   rv   check_familyY  s    
 
z-check_connection_ntuple.<locals>.check_familyc                 S   s   t tdt }| jtjtj|fks,t| jtd k	rLt| jtj	s`t| nt| jt
s`t| | jtjkr| jtjkst| jd S )NSOCK_SEQPACKET)r   r  objectr  r   r%  r   r,  r	  r-  rm   r   r   r7  )r   r9  ru   ru   rv   
check_typen  s    z+check_connection_ntuple.<locals>.check_typec                 S   s   | j | jfD ]}| jttfkrt|ts4tt||s:qt|j	t
sTtt|j	d|j	  krjdksvn t|j	t|j| j q| jtkrt|tstt|qd S )Nr   i  )r3  r4  r  r   r   r	  rk   r   r  portrm   rT   ipr   r
  )r   r  ru   ru   rv   check_addrsz  s    "
z,check_connection_ntuple.<locals>.check_addrsc                 S   s   t | jtst| jdd ttD }| j|ks<t| j| jttfkrl| j	t
krl| jtjkst| jn| jtjkst| jd S )Nc                 S   s    g | ]}| d rtt|qS )ZCONN_r   r   ru   ru   rv   r     s    
zAcheck_connection_ntuple.<locals>.check_status.<locals>.<listcomp>)r	  r   r
  r   r   r   r  r   r   r  r   r7  )r   Zvalidsru   ru   rv   check_status  s    z-check_connection_ntuple.<locals>.check_statusNru   )r   r5  r8  r;  r>  r?  ru   ru   rv   check_connection_ntupleK  s    
r@  c                 C   sP   zddl }t|dstW n& tk
r@   ddl}||  Y S X || S dS )z,Backport of importlib.reload of Python 3.3+.r   Nreload)	importlibr=  r  imprA  )modulerB  rC  ru   ru   rv   r[     s    
c                 C   s   t jt j| d }tjd dkr:dd l}||| S tjd d dkrfddlm	} ||| 
 S dd l}|j|| }|j|}|j| |S d S )Nr   rb   r   )SourceFileLoader)r   r   splitextr   rq   r   rC  Zload_sourceZimportlib.machineryrE  load_moduleimportlib.utilutilspec_from_file_locationmodule_from_specloaderexec_module)r   r   rC  rE  rB  specmodru   ru   rv   r\     s    c                 C   s   t | t dS )zRaise a warning msg.N)warningsr]   UserWarning)r  ru   ru   rv   r]     s    c                 C   sV   t | }|j}t|dks&|d tkr*dS t|dd}t|tsDdS tdd |D S )z-Check if object is an instance of namedtuple.r1  r   F_fieldsNc                 s   s   | ]}t |tkV  qd S r   )r  r
  )r   nru   ru   rv   	<genexpr>  s     z is_namedtuple.<locals>.<genexpr>)r  	__bases__r5  rk   r   r	  r  )r   tbr  ru   ru   rv   r_     s    
c                 #   st   t rdnd dt|  d} fddt  D }t|}t|| zt
| |V  W 5 t	| X dS )zCtx manager which picks up a random shared CO lib used
        by this process, copies it in another location and loads it
        in memory via ctypes. Return the new absolutized path.
        r   r   z.sord  c                    s6   g | ].}t j|jd  kr |j kr|jqS )r1  )r   r   rF  lowerr   r   extru   rv   r     s    'copyload_shared_lib.<locals>.<listcomp>N)r$   rN   r   r   r   r  r  r[  rg  rL   ctypesCDLL)re  dstlibsr   ru   rY  rv   r^     s    


c           	      #   s   ddl m} ddl m} d t|   d} fddt  D }trb|sbdd t  D }t	|}t
|| d	}zt |}|V  W 5 |d	k	rt jjj}|jg|_||j}|dkr|  t| X d	S )
zCtx manager which picks up a random shared DLL lib used
        by this process, copies it in another location and loads it
        in memory via ctypes.
        Return the new absolutized, normcased path.
        r   )WinError)wintypesz.dllrd  c                    sF   g | ]>}|j   rd tj |j  krd|j  kr|j qS )r   Zwow64)r   rX  r  r   r   r   rZ  ru   rv   r     s
    r[  c                 S   s(   g | ] }d t j|j kr|jqS )r   )r   r   r   rX  r   ru   ru   rv   r     s    N)r\  r`  ra  rN   r   r   r   r$   r  r  r[  rg  windllkernel32FreeLibraryZHMODULEargtypes_handlerL   ZWinDLL)	re  r`  ra  r^  r_  r   cfilere  rU  ru   rb  rv   r^     s(    





c                   C   s   t dd d S )NTr)  )r?   ru   ru   ru   rv   cleanup_test_procs  s    ri  c                 C   s
   t | S r   )rq   exit)r  frameru   ru   rv   r     r   r   )N)F)TF)N)r0  N)N)N)r  )r  )r0  )r0  )r   
__future__r   atexitrt  r\  r  r   r  r  r   ri   r  r>  r   r  r[  r  r  rW  ro   rq   rk  r   r   r   rs  rP  r   r   r   r   r   r   r   r	   r
   r   r   Zpsutil._commonr   r   r   r   Zpsutil._compatr   r   r   r   r   r   r   r   r   r  catch_warningssimplefilterr   r,  Zpsutil._psposixr   __all__builtin_module_namesr$   r   r   r`   r+   maxsizer.   rw   r;   r<   r#   r"   r-   r!   r   r  r(   r)   decoder*   r  rX  ZASCII_FSr   r   r   ra  __file__r&   r'   ZHEREr&  r=  r   r/   r0   r  r1   r3   r4   ZHAS_NET_IO_COUNTERSr5   r2   r6   r7   rf  r   r8   r   r9   r:   ZHAS_THREADSgetuidZSKIP_SYSCONSr   r%   r  devnullr    registerr   r   r,   r   r:  r   r   r   r   r   r   r   r@   rB   rA   r=   r  r  r>   r?   rP   rO   rC  r  rR   r   rS   rQ   rL   r`  ru  rK   rM   rN   rm  rG   ZskipIfrF   rJ   r  rH   rI   r	  rE   rC   rD   rU   rV   rW   rX   rY   rZ   rT   r@  r[   r\   r]   r_   r^   ri  ru   ru   ru   rv   <module>   s  


                                              .












 0'
&-

U
%:



 
!



1
 [	 
B





R,
