3
W­E^/  ã               @   s:   d dl Z d dlZddlmZ ddlmZ G dd„ dƒZdS )é    Né   )Úguarantee_single_callable)Útimeoutc               @   sP   e Zd ZdZdd„ Zddd„Zddd	„Zd
d„ Zdd„ Zddd„Z	ddd„Z
dS )ÚApplicationCommunicatorz}
    Runs an ASGI application in a test mode, allowing sending of
    messages to it and retrieval of messages it sends.
    c             C   sF   t |ƒ| _|| _tjƒ | _tjƒ | _tj| j|| jj| jj	ƒƒ| _
d S )N)r   ÚapplicationÚscopeÚasyncioÚQueueÚinput_queueÚoutput_queueZensure_futureÚgetÚputÚfuture)Úselfr   r   © r   ú2/tmp/pip-build-78s3knkw/asgiref/asgiref/testing.pyÚ__init__   s    


z ApplicationCommunicator.__init__r   c          !   Ã   sœ   zXt |ƒ4 I dH š8 y| jI dH  | jjƒ  W n tjk
rD   Y nX W dQ I dH R X W d| jjƒ s–| jjƒ  y| jI dH  W n tjk
r”   Y nX X dS )zV
        Waits for the application to stop itself and returns any exceptions.
        N)Úasync_timeoutr   Úresultr   ÚCancelledErrorÚdoneÚcancel)r   r   r   r   r   Úwait   s    

zApplicationCommunicator.waitTc             C   s(   | j jƒ s| j jƒ  n|r$| j jƒ  d S )N)r   r   r   r   )r   Ú
exceptionsr   r   r   Ústop*   s    
zApplicationCommunicator.stopc             C   s*   y| j dd� W n tk
r$   Y nX d S )NF)r   )r   ÚRuntimeError)r   r   r   r   Ú__del__1   s    zApplicationCommunicator.__del__c             Ã   s   | j j|ƒI dH  dS )z;
        Sends a single message to the application
        N)r
   r   )r   Úmessager   r   r   Ú
send_input9   s    z"ApplicationCommunicator.send_inputc             Ã   s¼   | j jƒ r| j jƒ  y2t|ƒ4 I dH š | jjƒ I dH S Q I dH R X W np tjk
r¶ } zR| j jƒ rp| j jƒ  n2| j jƒ  y| j I dH  W n tj	k
r    Y nX |‚W Y dd}~X nX dS )zX
        Receives a single message from the application, with optional timeout.
        N)
r   r   r   r   r   r   r   ÚTimeoutErrorr   r   )r   r   Úer   r   r   Úreceive_output@   s    

 

z&ApplicationCommunicator.receive_outputçš™™™™™¹?ç{®Gáz„?c             Ã   sF   t jƒ }x2t jƒ | |k r:| jjƒ s(dS tj|ƒI dH  q
W | jjƒ S )zO
        Checks that there is no message to receive in the given time.
        FN)ÚtimeÚ	monotonicr   Úemptyr   Úsleep)r   r   ÚintervalÚstartr   r   r   Úreceive_nothingW   s    
z'ApplicationCommunicator.receive_nothingN)r   )T)r   )r"   r#   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r   r!   r*   r   r   r   r   r      s   	


r   )r   r$   Zcompatibilityr   r   r   r   r   r   r   r   Ú<module>   s   