3
e>                 @   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	m
Z
 ddlmZ ddlmZ ddlmZ ddlmZ ejrddlmZ G d	d
 d
Ze jeje ejd dddZG dd dejZejejeeejf  eejdddZ G dd dZ!G dd dZ"dS )    N)TracebackType   )
formatting)termui)utils)_find_binary_reader)BaseCommandc               @   s   e Zd ZejejddddZeejdddZe	e	dd	d
Z
dee	dddZdee	dddZdee	dddZeje	 dddZeje	 dddZedddZdS ) EchoingStdinN)inputoutputreturnc             C   s   || _ || _d| _d S )NF)_input_output_paused)selfr
   r    r   ./tmp/pip-build-3irwxpxt/click/click/testing.py__init__   s    zEchoingStdin.__init__)xr   c             C   s   t | j|S )N)getattrr   )r   r   r   r   r   __getattr__   s    zEchoingStdin.__getattr__)rvr   c             C   s   | j s| jj| |S )N)r   r   write)r   r   r   r   r   _echo   s    zEchoingStdin._echor   )nr   c             C   s   | j | jj|S )N)r   r   read)r   r   r   r   r   r   #   s    zEchoingStdin.readc             C   s   | j | jj|S )N)r   r   read1)r   r   r   r   r   r   &   s    zEchoingStdin.read1c             C   s   | j | jj|S )N)r   r   readline)r   r   r   r   r   r   )   s    zEchoingStdin.readline)r   c                s    fdd j j D S )Nc                s   g | ]} j |qS r   )r   ).0r   )r   r   r   
<listcomp>-   s    z*EchoingStdin.readlines.<locals>.<listcomp>)r   	readlines)r   r   )r   r   r    ,   s    zEchoingStdin.readlinesc                s   t  fdd jD S )Nc             3   s   | ]} j |V  qd S )N)r   )r   r   )r   r   r   	<genexpr>0   s    z(EchoingStdin.__iter__.<locals>.<genexpr>)iterr   )r   r   )r   r   __iter__/   s    zEchoingStdin.__iter__c             C   s
   t | jS )N)reprr   )r   r   r   r   __repr__2   s    zEchoingStdin.__repr__)r&   r&   )r&   r&   )r&   )__name__
__module____qualname__tBinaryIOr   strAnyr   bytesr   intr   r   r   Listr    Iteratorr#   r%   r   r   r   r   r	      s   r	   )streamr   c             c   s&   | d krd V  nd| _ d V  d| _ d S )NTF)r   )r2   r   r   r   _pause_echo6   s
    r3   c                   sR   e Zd Zejeeejdd fddZeedddZ	eeddd	Z
  ZS )
_NamedTextIOWrapperN)buffernamemodekwargsr   c                s    t  j|f| || _|| _d S )N)superr   _name_mode)r   r5   r6   r7   r8   )	__class__r   r   r   A   s    z_NamedTextIOWrapper.__init__)r   c             C   s   | j S )N)r:   )r   r   r   r   r6   H   s    z_NamedTextIOWrapper.namec             C   s   | j S )N)r;   )r   r   r   r   r7   L   s    z_NamedTextIOWrapper.mode)r'   r(   r)   r*   r+   r,   r-   r   propertyr6   r7   __classcell__r   r   )r<   r   r4   @   s   r4   )r
   charsetr   c             C   sd   t | dr0ttjtj| }|d k	r(|S td| d kr>d} nt| trR| j|} t	j
tjt| S )Nr   z.Could not find binary reader for input stream.    )hasattrr   r*   castIO	TypeError
isinstancer,   encodeioBytesIOr.   )r
   r?   r   r   r   r   make_input_streamQ   s    


rI   c               @   s   e Zd ZdZddeeje ejeeje	 ejej
eje	 e	ef  dddZeeddd	Zeedd
dZeedddZedddZdS )Resultz3Holds the captured result of an invoked CLI script.N	CliRunner)runnerstdout_bytesstderr_bytesreturn_value	exit_code	exceptionexc_infoc             C   s.   || _ || _|| _|| _|| _|| _|| _d S )N)rL   rM   rN   rO   rP   rQ   rR   )r   rL   rM   rN   rO   rP   rQ   rR   r   r   r   r   h   s    zResult.__init__)r   c             C   s   | j S )z(The (standard) output as unicode string.)stdout)r   r   r   r   r      s    zResult.outputc             C   s   | j j| jjdjddS )z&The standard output as unicode string.replacez

)rM   decoderL   r?   rT   )r   r   r   r   rS      s    zResult.stdoutc             C   s,   | j dkrtd| j j| jjdjddS )z%The standard error as unicode string.Nzstderr not separately capturedrT   z
rU   )rN   
ValueErrorrV   rL   r?   rT   )r   r   r   r   stderr   s    
zResult.stderrc             C   s,   | j rt| j nd}dt| j d| dS )Nokay< >)rQ   r$   typer'   )r   Zexc_strr   r   r   r%      s    zResult.__repr__)N)r'   r(   r)   __doc__r.   r*   Optionalr-   r/   BaseExceptionTupleTyper   r   r=   r,   r   rS   rX   r%   r   r   r   r   rJ   e   s   BrJ   c            
   @   sv  e Zd ZdZdeejejeeje f  eeddddZ	d	ed
ddZ
dejejeeje f  ejeeje f dddZejdejejeeejf  ejejeeje f  eejejejejej f  dddZdd	ejejeeje f  ejejeeejf  ejejeeje f  eeejedddZejdejejeejf  eje dddZdS )rK   a  The CLI runner provides functionality to invoke a Click command line
    script for unittesting purposes in a isolated environment.  This only
    works in single-threaded systems without any concurrency as it changes the
    global interpreter state.

    :param charset: the character set for the input and output data.
    :param env: a dictionary with environment variables for overriding.
    :param echo_stdin: if this is set to `True`, then reading from stdin writes
                       to stdout.  This is useful for showing examples in
                       some circumstances.  Note that regular prompts
                       will automatically echo the input.
    :param mix_stderr: if this is set to `False`, then stdout and stderr are
                       preserved as independent streams.  This is useful for
                       Unix-philosophy apps that have predictable stdout and
                       noisy stderr, such that each may be measured
                       independently
    utf-8NFT)r?   env
echo_stdin
mix_stderrr   c             C   s    || _ |pi | _|| _|| _d S )N)r?   rd   re   rf   )r   r?   rd   re   rf   r   r   r   r      s    
zCliRunner.__init__r   )clir   c             C   s
   |j pdS )zGiven a command object it will return the default program name
        for it.  The default is the `name` attribute or ``"root"`` if not
        set.
        root)r6   )r   rg   r   r   r   get_default_prog_name   s    zCliRunner.get_default_prog_name)	overridesr   c             C   s   t | j}|r|j| |S )z8Returns the environment overrides for invoking a script.)dictrd   update)r   rj   r   r   r   r   make_env   s    

zCliRunner.make_env)r
   rd   colorr   c             #   s  t || j}d}tj}tj}tj}tj}	dt_| j|}t	j
 }
| jr^tjtjt||
 }}t|| jddd t_| jrd_t|
| jdddt_d}| jrtjt_nt	j
 }t|| jd	dd
dt_t|dtjt tdfdd}t|dtjt tdfdd}t|ttddd}| dtjtj tjt td fdd}tj}tj}tj}tj}|t_|t_|t_|t_i }zpx`|j D ]T\}}tj j!|||< |dkrytj |= W n t"k
r   Y nX n
|tj |< qW |
|fV  W dxP|j D ]D\}}|dkr:ytj |= W n t"k
r6   Y nX n
|tj |< qW |t_|t_|t_|t_|t_|t_|t_|	t_X dS )an  A context manager that sets up the isolation for invoking of a
        command line tool.  This sets up stdin with the given input data
        and `os.environ` with the overrides from the given dictionary.
        This also rebinds some internals in Click to be mocked (like the
        prompt functionality).

        This is automatically done in the :meth:`invoke` method.

        :param input: the input stream to put into sys.stdin.
        :param env: the environment overrides as dictionary.
        :param color: whether the output should contain color codes. The
                      application can still override this explicitly.

        .. versionchanged:: 8.0
            ``stderr`` is opened with ``errors="backslashreplace"``
            instead of the default ``"strict"``.

        .. versionchanged:: 4.0
            Added the ``color`` parameter.
        NP   z<stdin>r)encodingr6   r7   r   z<stdout>wz<stderr>backslashreplace)rq   r6   r7   errors)promptr   c                s>   t jj| pd  j jd}t jj| d t jj  |S )N z
rU   )sysrS   r   r   rstripflush)ru   val)
text_inputr   r   visible_input  s
    
z*CliRunner.isolation.<locals>.visible_inputc                s.   t jj| pd d t jj   j jdS )Nrv   rU   z
)rw   rS   r   ry   r   rx   )ru   )r{   r   r   hidden_input  s    
z)CliRunner.isolation.<locals>.hidden_input)echor   c             S   s*   t jjd}| rt jj| t jj  |S )Nr   )rw   stdinr   rS   r   ry   )r~   charr   r   r   _getchar#  s
    
z%CliRunner.isolation.<locals>._getchar)r2   rn   r   c                s   |d kr  S | S )Nr   )r2   rn   )default_colorr   r   should_strip_ansi/  s    z.CliRunner.isolation.<locals>.should_strip_ansi)N)N)NN)#rI   r?   rw   r   rS   rX   r   ZFORCED_WIDTHrm   rG   rH   re   r*   rB   r+   r	   r4   _CHUNK_SIZErf   r3   r_   r,   boolrC   r   Zvisible_prompt_funcZhidden_prompt_funcr   r   r   itemsosenvironget	Exception)r   r
   rd   rn   Zbytes_inputZ
echo_inputZ	old_stdinZ
old_stdoutZ
old_stderrZold_forced_widthZbytes_outputZbytes_errorr|   r}   r   r   Zold_visible_prompt_funcZold_hidden_prompt_funcZold__getchar_funcZold_should_strip_ansiZold_envkeyvaluer   )r   r{   r   	isolation   s    


	

zCliRunner.isolation)rg   argsr
   rd   catch_exceptionsrn   extrar   c          ,   K   s  d}| j |||dz}	d}
d}d}t|tr8tj|}y|jd}W n tk
rd   | j|}Y nX zy|jf |pvf |d|}
W n t	k
r } zvt
j }tjtjtjttjf  |j}|dkrd}|dkr|}t|tst
jjt| t
jjd d}|}W Y dd}~X n< tk
rT } z|s4 |}d}t
j }W Y dd}~X nX W dt
jj  |	d j }| jr~d}n|	d j }X W dQ R X t| |||
|||dS )	a  Invokes a command in an isolated environment.  The arguments are
        forwarded directly to the command line script, the `extra` keyword
        arguments are passed to the :meth:`~clickpkg.Command.main` function of
        the command.

        This returns a :class:`Result` object.

        :param cli: the command to invoke
        :param args: the arguments to invoke. It may be given as an iterable
                     or a string. When given as string it will be interpreted
                     as a Unix shell command. More details at
                     :func:`shlex.split`.
        :param input: the input data for `sys.stdin`.
        :param env: the environment overrides.
        :param catch_exceptions: Whether to catch any other exceptions than
                                 ``SystemExit``.
        :param extra: the keyword arguments to pass to :meth:`main`.
        :param color: whether the output should contain color codes. The
                      application can still override this explicitly.

        .. versionchanged:: 8.0
            The result object has the ``return_value`` attribute with
            the value returned from the invoked command.

        .. versionchanged:: 4.0
            Added the ``color`` parameter.

        .. versionchanged:: 3.0
            Added the ``catch_exceptions`` parameter.

        .. versionchanged:: 3.0
            The result object has the ``exc_info`` attribute with the
            traceback if available.
        N)r
   rd   rn   r   	prog_name)r   r   rU   r   )rL   rM   rN   rO   rP   rQ   rR   )r   rE   r,   shlexsplitpopKeyErrorri   main
SystemExitrw   rR   r*   rB   r_   Unionr/   r-   coderS   r   r   ry   getvaluerf   rJ   )r   rg   r   r
   rd   r   rn   r   rR   Z
outstreamsrO   rQ   rP   r   eZe_coderS   rX   r   r   r   invoke]  sX    ,

 
zCliRunner.invoke)temp_dirr   c             c   sn   t j }tj|d}t j| ztjt|V  W dt j| |dkrhytj	| W n t
k
rf   Y nX X dS )a  A context manager that creates a temporary directory and
        changes the current working directory to it. This isolates tests
        that affect the contents of the CWD to prevent them from
        interfering with each other.

        :param temp_dir: Create the temporary directory under this
            directory. If given, the created directory is not removed
            when exiting.

        .. versionchanged:: 8.0
            Added the ``temp_dir`` parameter.
        )dirN)r   getcwdtempfilemkdtempchdirr*   rB   r,   shutilrmtreeOSError)r   r   cwddtr   r   r   isolated_filesystem  s    

zCliRunner.isolated_filesystem)rc   NFT)N)NNF)NNNTF)N)r'   r(   r)   r^   r,   r*   r_   Mappingr   r   ri   rm   
contextlibcontextmanagerr   r.   rC   r1   ra   rG   rH   r   Sequencer-   rJ   r   r   PathLiker   r   r   r   r   rK      s2         2*     N\rK   )#r   rG   r   r   r   rw   r   typingr*   typesr   rv   r   r   r   _compatr   ZTYPE_CHECKINGcorer   r	   r   r_   r1   r3   TextIOWrapperr4   r   r,   r.   rC   r+   rI   rJ   rK   r   r   r   r   <module>   s,   "	: