U
    d!'                     @  s  d dl m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 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 ddlmZ G dd dejjZda ddddZ!G dd deZ"G dd deZ#dS )    )annotationsN)contextmanager)	ExitStack)copy)TracebackType)urlsplit)	CliRunner)Client)Request   )
ScriptInfo)SessionMixin)TestResponse)Flaskc                
      sH   e Zd ZdZdddddddddd	 fd
dZddddddZ  ZS )EnvironBuildera  An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the
    application.

    :param app: The Flask application to configure the environment from.
    :param path: URL path being requested.
    :param base_url: Base URL where the app is being served, which
        ``path`` is relative to. If not given, built from
        :data:`PREFERRED_URL_SCHEME`, ``subdomain``,
        :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.
    :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.
    :param url_scheme: Scheme to use instead of
        :data:`PREFERRED_URL_SCHEME`.
    :param json: If given, this is serialized as JSON and passed as
        ``data``. Also defaults ``content_type`` to
        ``application/json``.
    :param args: other positional arguments passed to
        :class:`~werkzeug.test.EnvironBuilder`.
    :param kwargs: other keyword arguments passed to
        :class:`~werkzeug.test.EnvironBuilder`.
    /Nr   strz
str | Nonet.AnyNone)apppathbase_url	subdomain
url_schemeargskwargsreturnc                   s   |s|s|r(|d k	t |p|ks(td|d kr|jdp>d}|jd }	|r\| d| }|d krn|jd }t|}
|
jp~| d|
jp| d|	d }|
j}|
j	rt
|
j	trd	nd
}|||
j	 7 }|| _t j||f|| d S )Nz8Cannot pass "subdomain" or "url_scheme" with "base_url".ZSERVER_NAME	localhostZAPPLICATION_ROOT.ZPREFERRED_URL_SCHEMEz://r      ??)boolAssertionErrorconfiggetr   schemenetloclstripr   query
isinstancebytesr   super__init__)selfr   r   r   r   r   r   r   Z	http_hostZapp_rooturlsep	__class__ 1/tmp/pip-unpacked-wheel-uq31yewi/flask/testing.pyr,   /   s0    


$zEnvironBuilder.__init__)objr   r   c                 K  s   | j jj|f|S )zSerialize ``obj`` to a JSON-formatted string.

        The serialization will be configured according to the config associated
        with this EnvironBuilder's ``app``.
        )r   jsondumps)r-   r4   r   r2   r2   r3   
json_dumpsW   s    zEnvironBuilder.json_dumps)r   NNN)__name__
__module____qualname____doc__r,   r7   __classcell__r2   r2   r0   r3   r      s       "(r    r   r   c                   C  s   t stjda t S )Nwerkzeug)_werkzeug_version	importlibmetadataversionr2   r2   r2   r3   _get_werkzeug_versionc   s    rD   c                      s   e Zd ZU dZded< dddd fddZeddd	dd
dZdd Zdd Z	ddddddddd fddZ
d dddZdddddddZ  ZS ) FlaskClienta  Works like a regular Werkzeug test client but has knowledge about
    Flask's contexts to defer the cleanup of the request context until
    the end of a ``with`` block. For general information about how to
    use this class refer to :class:`werkzeug.test.Client`.

    .. versionchanged:: 0.12
       `app.test_client()` includes preset default environment, which can be
       set after instantiation of the `app.test_client()` object in
       `client.environ_base`.

    Basic usage is outlined in the :doc:`/testing` chapter.
    r   applicationr   r   )r   r   r   c                   s:   t  j|| d| _g | _t | _ddt  d| _d S )NFz	127.0.0.1z	Werkzeug/)ZREMOTE_ADDRZHTTP_USER_AGENT)r+   r,   preserve_context_new_contextsr   _context_stackrD   environ_base)r-   r   r   r0   r2   r3   r,   |   s    
zFlaskClient.__init__z%t.Generator[SessionMixin, None, None]c              	   o  s   | j dkrtd| j}|j||}| |jj | |j||j}W 5 Q R X |dkrbt	d|V  |
 }|j|rdS | |j||| W 5 Q R X | |jjdd |jj|jd dS )a  When used in combination with a ``with`` statement this opens a
        session transaction.  This can be used to modify the session that
        the test client uses.  Once the ``with`` block is left the session is
        stored back.

        ::

            with client.session_transaction() as session:
                session['value'] = 42

        Internally this is implemented by going through a temporary test
        request context and since session handling could depend on
        request variables this function accepts the same arguments as
        :meth:`~flask.Flask.test_request_context` which are directly
        passed through.
        Nz>Cookies are disabled. Create a client with 'use_cookies=True'.z'Session backend did not open a session.:r   z
Set-Cookie)_cookies	TypeErrorrF   Ztest_request_contextZ_add_cookies_to_wsgirequestenvironZsession_interfaceZopen_sessionRuntimeErrorresponse_classZis_null_sessionZsave_sessionZ_update_cookies_from_responsehost	partitionr   headersgetlist)r-   r   r   r   ctxsessrespr2   r2   r3   session_transaction   s,    

zFlaskClient.session_transactionc                 C  s    | j |}| jr| jj|d< |S )Nzwerkzeug.debug.preserve_context)rJ   rG   rH   append)r-   otheroutr2   r2   r3   _copy_environ   s    
zFlaskClient._copy_environc                 C  sD   |  |di |d< t| jf||}z| W S |  X d S )NrJ   )r]   r$   r   rF   closeget_request)r-   r   r   builderr2   r2   r3   _request_from_builder_args   s
    z&FlaskClient._request_from_builder_argsFbufferedfollow_redirectsr!   r   )r   rc   rd   r   r   c          	        s   |rt |d tjjttfrt |d tjjrVt|d }| |jpFi |_|	 }qt |d trtj
|d | j| i d	 }qt|d }| |j|_n| ||}| j  t j|||d}| jj|_| jr| j }| j| q|S )Nr   )r   rJ   rb   )r)   r?   testr   dictBaseRequestr   r]   rJ   r_   Zfrom_environrF   rO   ra   rI   r^   r+   openr5   Zjson_modulerH   popenter_context)	r-   rc   rd   r   r   r`   rN   responsecmr0   r2   r3   rh      s8     
  


zFlaskClient.openr>   c                 C  s   | j rtdd| _ | S )NzCannot nest client invocationsT)rG   rP   r-   r2   r2   r3   	__enter__   s    zFlaskClient.__enter__ztype | NonezBaseException | NonezTracebackType | None)exc_type	exc_valuetbr   c                 C  s   d| _ | j  d S )NF)rG   rI   r^   )r-   ro   rp   rq   r2   r2   r3   __exit__   s    zFlaskClient.__exit__)r8   r9   r:   r;   __annotations__r,   r   rY   r]   ra   rh   rn   rr   r<   r2   r2   r0   r3   rE   l   s   

1-rE   c                      sD   e Zd ZdZdddd fddZdddddd	 fd
dZ  ZS )FlaskCliRunnerzA :class:`~click.testing.CliRunner` for testing a Flask app's
    CLI commands. Typically created using
    :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.
    r   r   r   )r   r   r   c                   s   || _ t jf | d S N)r   r+   r,   )r-   r   r   r0   r2   r3   r,     s    zFlaskCliRunner.__init__N)clir   r   r   c                   s@   |dkr j j}d|kr.t fddd|d< t j||f|S )ac  Invokes a CLI command in an isolated environment. See
        :meth:`CliRunner.invoke <click.testing.CliRunner.invoke>` for
        full method documentation. See :ref:`testing-cli` for examples.

        If the ``obj`` argument is not given, passes an instance of
        :class:`~flask.cli.ScriptInfo` that knows how to load the Flask
        app being tested.

        :param cli: Command object to invoke. Default is the app's
            :attr:`~flask.app.Flask.cli` group.
        :param args: List of strings to invoke the command with.

        :return: a :class:`~click.testing.Result` object.
        Nr4   c                     s    j S ru   )r   r2   rm   r2   r3   <lambda>%      z'FlaskCliRunner.invoke.<locals>.<lambda>)Z
create_app)r   rv   r   r+   invoke)r-   rv   r   r   r0   rm   r3   ry     s
    zFlaskCliRunner.invoke)NN)r8   r9   r:   r;   r,   ry   r<   r2   r2   r0   r3   rt     s
      rt   )$
__future__r   importlib.metadatarA   typingt
contextlibr   r   r   typesr   urllib.parser   Zwerkzeug.testr?   Zclick.testingr   r	   Zwerkzeug.wrappersr
   rg   rv   r   sessionsr   TYPE_CHECKINGr   r   r   re   r   r@   rD   rE   rt   r2   r2   r2   r3   <module>   s,   G	 