a
    ze	D                     @   s  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mZ zd dlZW n ey   dZY n0 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 Z!e!dZ"e!dZ#e!dZ$e!dZ%ddddddddddd
Z&dd Z'dd d!d"Z(d#d$ Z)d%d& Z*e j+fd'd(Z,d)d* Z-G d+d, d,eZ.G d-d. d.eZ/G d/d0 d0Z0G d1d2 d2e0e/Z1d3d4d5d6Z2e3ed7rjG d8d9 d9e	j4eZ5G d:d; d;e5eZ6G d<d= d=e6Z7G d>d? d?e0e7Z8d@dA Z9ej:dBdC Z;ej:d3d4dDdEZ<ej:dFd d3dGdHdIZ=dJdK Z>G dLdM dMej?Z@G dNdO dOejAZBdPdQ ZCG dRdS dSeDZEG dTdU dUZFdVdW ZGG dXdY dYejHZHej:dZd[ ZIejJejKejLfd\d]ZMdS )^    N)mock)
HTTPServer)WSGIRequestHandler
WSGIServer)base_events)events)format_helpers)futures)tasks)logger)supportc                 C   s^   t tdr*tjtj| }tj|r*|S tjtjtd| }tj|rR|S t	| d S )NTEST_HOME_DIRz..)
hasattrr   ospathjoinr   isfiledirname__file__FileNotFoundError)filenamefullname r   -/usr/lib/python3.9/test/test_asyncio/utils.py	data_file'   s    
r   zssl_cert.pemzssl_key.pemzkeycert3.pemzpycacert.pem)z)http://testca.pythontest.net/testca/ocsp/)z0http://testca.pythontest.net/testca/pycacert.cer)z2http://testca.pythontest.net/testca/revocation.crl))ZcountryNameZXY))organizationNamezPython Software Foundation CA))
commonNamezour-ca-serverzOct 28 14:23:16 2037 GMTzAug 29 14:23:16 2018 GMTZCB2D80995A69525C)r   ))ZlocalityNamezCastle Anthrax))r   zPython Software Foundation))r   	localhost))ZDNSr      )
ZOCSPZ	caIssuersZcrlDistributionPointsZissuerZnotAfterZ	notBeforeZserialNumberZsubjectZsubjectAltNameversionc                  C   s*   t t j} | tt d| _t j| _| S NF)	ssl
SSLContextZPROTOCOL_TLS_SERVERload_cert_chainONLYCERTONLYKEYcheck_hostname	CERT_NONEverify_mode)Zserver_contextr   r   r   simple_server_sslcontextI   s
    r*   T)disable_verifyc                 C   s"   t t j}d|_| rt j|_|S r!   )r"   r#   ZPROTOCOL_TLS_CLIENTr'   r(   r)   )r+   Zclient_contextr   r   r   simple_client_sslcontextQ   s
    r,   c                   C   s   t d u rd S t t jS d S N)r"   r#   ZPROTOCOL_TLSr   r   r   r   dummy_ssl_contextY   s    r.   c                 C   sD   dd }| }|  |}d|_z| | W |  n
|  0 d S )Nc                      s   d S r-   r   r   r   r   r   oncea   s    zrun_briefly.<locals>.onceF)Zcreate_taskZ_log_destroy_pendingrun_until_completeclose)loopr/   gentr   r   r   run_briefly`   s    
r5   c                 C   sL   t  | }| sH|d ur6|t   }|dkr6t | td qd S )Nr   gMbP?)time	monotonicr	   TimeoutErrorr0   r
   sleep)r2   Zpredtimeoutdeadliner   r   r   	run_untiln   s    r<   c                 C   s   |  | j |   d S r-   )Z	call_soonstopZrun_foreverr2   r   r   r   run_oncex   s    r?   c                   @   s   e Zd Zdd Zdd ZdS )SilentWSGIRequestHandlerc                 C   s   t  S r-   )ioStringIOselfr   r   r   
get_stderr   s    z#SilentWSGIRequestHandler.get_stderrc                 G   s   d S r-   r   )rD   formatargsr   r   r   log_message   s    z$SilentWSGIRequestHandler.log_messageN)__name__
__module____qualname__rE   rH   r   r   r   r   r@      s   r@   c                       s*   e Zd ZejZ fddZdd Z  ZS )SilentWSGIServerc                    s"   t   \}}|| j ||fS r-   superget_request
settimeoutrequest_timeoutrD   requestZclient_addr	__class__r   r   rO      s    zSilentWSGIServer.get_requestc                 C   s   d S r-   r   rD   rS   client_addressr   r   r   handle_error   s    zSilentWSGIServer.handle_error)	rI   rJ   rK   r   LOOPBACK_TIMEOUTrQ   rO   rX   __classcell__r   r   rT   r   rL      s   rL   c                   @   s   e Zd Zdd ZdS )SSLWSGIServerMixinc                 C   sT   t  }|tt |j|dd}z| |||  |  W n tyN   Y n0 d S )NT)Zserver_side)	r"   r#   r$   r%   r&   Zwrap_socketZRequestHandlerClassr1   OSError)rD   rS   rW   contextZssockr   r   r   finish_request   s    z!SSLWSGIServerMixin.finish_requestN)rI   rJ   rK   r^   r   r   r   r   r[      s   r[   c                   @   s   e Zd ZdS )SSLWSGIServerNrI   rJ   rK   r   r   r   r   r_      s   r_   F)use_sslc                 #   s   dd fdd}|r|n|}|| t   |  j _tj fddd}|  z" V  W       |	  n      |	  0 d S )Nc                 s   s<   t | d }|r8| d t|d}|V  |t|8 }qd S )NZCONTENT_LENGTHz
wsgi.inputi   )intreadminlen)environsizedatar   r   r   r2      s
    z_run_test_server.<locals>.loopc                    s2   d}dg}||| | d dkr( | S dgS d S )Nz200 OK)zContent-typez
text/plainZ	PATH_INFOz/loops   Test messager   )rf   Zstart_responsestatusZheadersr>   r   r   app   s    
z_run_test_server.<locals>.appc                      s    j ddS )Ng?)Zpoll_interval)Zserve_foreverr   )httpdr   r   <lambda>       z"_run_test_server.<locals>.<lambda>)target)
r@   Zset_appZserver_addressaddress	threadingThreadstartshutdownZserver_closer   )ro   ra   
server_clsserver_ssl_clsrj   Zserver_classZserver_threadr   )rk   r2   r   _run_test_server   s$    



rv   AF_UNIXc                   @   s   e Zd Zdd ZdS )UnixHTTPServerc                 C   s   t j|  d| _d| _d S )N	127.0.0.1P   )socketserverUnixStreamServerserver_bindZserver_nameZserver_portrC   r   r   r   r}      s    zUnixHTTPServer.server_bindN)rI   rJ   rK   r}   r   r   r   r   rx      s   rx   c                       s*   e Zd ZejZdd Z fddZ  ZS )UnixWSGIServerc                 C   s   t |  |   d S r-   )rx   r}   Zsetup_environrC   r   r   r   r}      s    
zUnixWSGIServer.server_bindc                    s"   t   \}}|| j |dfS )N)ry    rM   rR   rT   r   r   rO      s    zUnixWSGIServer.get_request)	rI   rJ   rK   r   rY   rQ   r}   rO   rZ   r   r   rT   r   r~      s   r~   c                   @   s   e Zd Zdd ZdS )SilentUnixWSGIServerc                 C   s   d S r-   r   rV   r   r   r   rX      s    z!SilentUnixWSGIServer.handle_errorN)rI   rJ   rK   rX   r   r   r   r   r      s   r   c                   @   s   e Zd ZdS )UnixSSLWSGIServerNr`   r   r   r   r   r      s   r   c                  C   s2   t  } | jW  d    S 1 s$0    Y  d S r-   )tempfileNamedTemporaryFilename)filer   r   r   gen_unix_socket_path   s    
r   c                  c   s\   t  } z,| V  W zt|  W qX ty0   Y qX0 n$zt|  W n tyT   Y n0 0 d S r-   )r   r   unlinkr\   )r   r   r   r   unix_socket_path   s    r   c                 c   s@   t  &}t|| ttdE d H  W d    n1 s20    Y  d S N)ro   ra   rt   ru   )r   rv   r   r   )ra   r   r   r   r   run_test_unix_server  s
    r   ry   hostportra   c                 c   s   t | |f|ttdE d H  d S r   )rv   rL   r_   r   r   r   r   run_test_server  s    
r   c                 C   sL   i }t | D ](}|dr&|dr&qtd d||< qtd| f| j | S )N__)return_valueZTestProtocol)dir
startswithendswithMockCallbacktype	__bases__)baseZdctr   r   r   r   make_test_protocol  s    r   c                   @   s6   e Zd Zdd ZdddZdd Zdd	 Zd
d ZdS )TestSelectorc                 C   s
   i | _ d S r-   keysrC   r   r   r   __init__'  s    zTestSelector.__init__Nc                 C   s   t |d||}|| j|< |S )Nr   )	selectorsSelectorKeyr   )rD   fileobjr   rh   keyr   r   r   register*  s    
zTestSelector.registerc                 C   s   | j |S r-   )r   pop)rD   r   r   r   r   
unregister/  s    zTestSelector.unregisterc                 C   s   g S r-   r   )rD   r:   r   r   r   select2  s    zTestSelector.selectc                 C   s   | j S r-   r   rC   r   r   r   get_map5  s    zTestSelector.get_map)N)rI   rJ   rK   r   r   r   r   r   r   r   r   r   r   %  s
   
r   c                       s   e Zd Zd- fdd	Zdd Zdd Z f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 Zdd Zdd Zdd Zd d! Zd"d# Z fd$d%Zdd& fd'd(
Zd)d* Zd+d, Z  ZS ).TestLoopNc                    sv   t    |d u r"dd }d| _nd| _| | _t| j d| _d| _g | _t | _	i | _
i | _|   t | _d S )Nc                   s   s
   d V  d S r-   r   r   r   r   r   r3   P  s    zTestLoop.__init__.<locals>.genFTr   g&.>)rN   r   _check_on_close_gennext_timeZ_clock_resolution_timersr   	_selectorreaderswritersreset_countersweakrefWeakValueDictionary_transports)rD   r3   rT   r   r   r   L  s    

zTestLoop.__init__c                 C   s   | j S r-   r   rC   r   r   r   r6   c  s    zTestLoop.timec                 C   s   |r|  j |7  _ d S r-   r   )rD   advancer   r   r   advance_timef  s    zTestLoop.advance_timec                    s@   t    | jr<z| jd W n ty2   Y n
0 tdd S )Nr   zTime generator is not finished)rN   r1   r   r   sendStopIterationAssertionErrorrC   rT   r   r   r1   k  s    
zTestLoop.closec                 G   s   t ||| d | j|< d S r-   )r   Handler   rD   fdcallbackrG   r   r   r   _add_readeru  s    zTestLoop._add_readerc                 C   s0   | j |  d7  < || jv r(| j|= dS dS d S N   TF)remove_reader_countr   rD   r   r   r   r   _remove_readerx  s
    
zTestLoop._remove_readerc                 G   sh   || j vrtd| d| j | }|j|krDtd|j d| |j|krdtd|j d| d S )Nfd z is not registeredzunexpected callback: z != zunexpected callback args: )r   r   	_callback_argsrD   r   r   rG   handler   r   r   assert_reader  s    



zTestLoop.assert_readerc                 C   s   || j v rtd| dd S )Nr   z is registered)r   r   r   r   r   r   assert_no_reader  s    
zTestLoop.assert_no_readerc                 G   s   t ||| d | j|< d S r-   )r   r   r   r   r   r   r   _add_writer  s    zTestLoop._add_writerc                 C   s0   | j |  d7  < || jv r(| j|= dS dS d S r   )remove_writer_countr   r   r   r   r   _remove_writer  s
    
zTestLoop._remove_writerc                 G   s   | j | }d S r-   )r   r   r   r   r   assert_writer  s    
zTestLoop.assert_writerc              
   C   sz   t |tsDzt| }W n( tttfyB   td|d Y n0 z| j| }W n tyd   Y n0 t	d||d S )NzInvalid file object: {!r}z.File descriptor {!r} is used by transport {!r})

isinstancerb   filenoAttributeError	TypeError
ValueErrorrF   r   KeyErrorRuntimeError)rD   r   Z	transportr   r   r   _ensure_fd_no_transport  s$    
z TestLoop._ensure_fd_no_transportc                 G   s   |  | | j||g|R  S r-   )r   r   r   r   r   r   
add_reader  s    
zTestLoop.add_readerc                 C   s   |  | | |S r-   )r   r   r   r   r   r   remove_reader  s    
zTestLoop.remove_readerc                 G   s   |  | | j||g|R  S r-   )r   r   r   r   r   r   
add_writer  s    
zTestLoop.add_writerc                 C   s   |  | | |S r-   )r   r   r   r   r   r   remove_writer  s    
zTestLoop.remove_writerc                 C   s   t t| _t t| _d S r-   )collectionsdefaultdictrb   r   r   rC   r   r   r   r     s    zTestLoop.reset_countersc                    s6   t    | jD ]}| j|}| | qg | _d S r-   )rN   	_run_oncer   r   r   r   )rD   whenr   rT   r   r   r     s
    

zTestLoop._run_once)r]   c                   s(   | j | t j||g|R d|iS )Nr]   )r   appendrN   call_at)rD   r   r   r]   rG   rT   r   r   r     s    zTestLoop.call_atc                 C   s   d S r-   r   )rD   Z
event_listr   r   r   _process_events  s    zTestLoop._process_eventsc                 C   s   d S r-   r   rC   r   r   r   _write_to_self  s    zTestLoop._write_to_self)N)rI   rJ   rK   r   r6   r   r1   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rZ   r   r   rT   r   r   9  s*   
r   c                  K   s   t jf ddgi| S )Nspec__call__)r   ZMock)kwargsr   r   r   r     s    r   c                   @   s   e Zd Zdd ZdS )MockPatternc                 C   s   t tt| |tjS r-   )boolresearchstrSrD   otherr   r   r   __eq__  s    zMockPattern.__eq__N)rI   rJ   rK   r   r   r   r   r   r     s   	r   c                   @   s   e Zd Zdd Zdd ZdS )MockInstanceOfc                 C   s
   || _ d S r-   )_type)rD   r   r   r   r   r     s    zMockInstanceOf.__init__c                 C   s   t || jS r-   )r   r   r   r   r   r   r     s    zMockInstanceOf.__eq__N)rI   rJ   rK   r   r   r   r   r   r   r     s   r   c                 C   s$   t | }|d u r td| f |S )Nzunable to get the source of %r)r   Z_get_function_sourcer   )funcsourcer   r   r   get_function_source  s    
r   c                   @   sH   e Zd Zedd ZddddZddd	Zd
d Zdd Zdd Z	dS )TestCasec                 C   s   | j d ur0|  s"| |   n| j jdd |   t }|d urz| }W n t	yf   Y n.0 t
|tjrt|j }|D ]}|  qd S )NT)wait)Z_default_executorZ	is_closedr0   Zshutdown_default_executorrs   r1   r   Zmaybe_get_event_loop_policyZget_child_watcherNotImplementedErrorr   asyncioZThreadedChildWatcherlistZ_threadsvaluesr   )r2   ZpolicyZwatcherthreadsthreadr   r   r   
close_loop  s    
zTestCase.close_loopT)cleanupc                C   s    t d  |r| | j| d S r-   )r   set_event_loopZ
addCleanupr   )rD   r2   r   r   r   r   r     s    
zTestCase.set_event_loopNc                 C   s   t |}| | |S r-   )r   r   )rD   r3   r2   r   r   r   new_test_loop  s    
zTestCase.new_test_loopc                 C   s   | j t_ d S r-   )_get_running_loopr   rC   r   r   r   unpatch_get_running_loop  s    z!TestCase.unpatch_get_running_loopc                 C   s    t j| _dd t _t | _d S )Nc                   S   s   d S r-   r   r   r   r   r   rl   $  rm   z TestCase.setUp.<locals>.<lambda>)r   r   r   Zthreading_setup_thread_cleanuprC   r   r   r   setUp"  s    
zTestCase.setUpc                 C   sB   |    td  | t d |   tj| j	  t
  d S )N)NNN)r   r   r   ZassertEqualsysexc_infoZ
doCleanupsr   Zthreading_cleanupr  reap_childrenrC   r   r   r   tearDown'  s    
zTestCase.tearDown)N)
rI   rJ   rK   staticmethodr   r   r   r   r  r  r   r   r   r   r     s   

r   c               	   c   s<   t j} z$t tjd  d V  W t |  nt |  0 d S )Nr   )r   levelsetLevelloggingCRITICAL)Z	old_levelr   r   r   disable_logger5  s
    r  c                 C   s*   t tj}| |_||_||_d|j_|S )Ng        )r   Z	MagicMocksocketprotor   family
gettimeoutr   )r  r   r  sockr   r   r   mock_nonblocking_socketC  s    r  )Nr   r   
contextlibrA   r
  r   r   r   r  r{   r  r   rp   r6   Zunittestr   r   Zhttp.serverr   Zwsgiref.simple_serverr   r   r"   ImportErrorr   r   r   r	   r
   Zasyncio.logr   testr   r   r%   r&   ZSIGNED_CERTFILEZ
SIGNING_CAZPEERCERTr*   r,   r.   r5   ZSHORT_TIMEOUTr<   r?   r@   rL   r[   r_   rv   r   r|   rx   r~   r   r   r   contextmanagerr   r   r   r   BaseSelectorr   ZBaseEventLoopr   r   r   r   r   r   r   r  IPPROTO_TCPSOCK_STREAMAF_INETr  r   r   r   r   <module>   s   

	#

 %8
