U
    ÎZjú/  ã                   @  sX  d dl mZ d dl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	m
Z
mZmZ d dlZd dlmZ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 e
rÄd dlmZmZ dZdZ dd„ Z!dd„ Z"e"dddde efdd„ƒZ#d,ddœdd„Z$d-ddddœdd„Z%d.d d!œd"d#„Z&d/d d!œd$d%„Z'd0d'd(„Z(d1d)dœd*d+„Z)dS )2é    )ÚannotationsN©Úwraps)ÚTYPE_CHECKINGÚAnyÚCallable)ÚFilePathÚReadPickleBuffer)Úget_lzma_file)Úimport_optional_dependency)Úrands)Úensure_clean)Úurlopen)Ú	DataFrameÚSeries)z	timed outzServer Hangupz#HTTP Error 503: Service Unavailablez502: Proxy ErrorzHTTP Error 502: internal errorzHTTP Error 502zHTTP Error 503zHTTP Error 403zHTTP Error 400z$Temporary failure in name resolutionzName or service not knownzConnection refusedzcertificate verify)ée   éo   én   éh   é6   é<   c                  C  s(   dd l } dd l}t| jjt|jjtj	fS )Nr   )
Úhttp.clientÚurllib.errorÚOSErrorÚclientÚHTTPExceptionÚTimeoutErrorÚerrorÚURLErrorÚsocketÚtimeout)ÚhttpÚurllib© r#   úV/var/www/html/TRUCKING_PROJECT/venv/lib/python3.8/site-packages/pandas/_testing/_io.pyÚ_get_default_network_errorsI   s    ûr%   c                   s   t ˆ ƒ‡ fdd„ƒ}|S )aB  
    allows a decorator to take optional positional and keyword arguments.
    Assumes that taking a single, callable, positional argument means that
    it is decorating a function, i.e. something like this::

        @my_decorator
        def function(): pass

    Calls decorator with decorator(f, *args, **kwargs)
    c                    sN   ‡ ‡‡fdd„}ˆ o,t ˆ ƒdko,tˆ d ƒ}|rFˆ d }d‰ ||ƒS |S d S )Nc                   s   ˆ| fˆ žˆŽS ©Nr#   )Úf)ÚargsÚ	decoratorÚkwargsr#   r$   Údecf   s    z+optional_args.<locals>.wrapper.<locals>.decé   r   r#   )ÚlenÚcallable)r(   r*   r+   Zis_decoratingr'   ©r)   )r(   r*   r$   Úwrapperd   s    zoptional_args.<locals>.wrapperr   )r)   r0   r#   r/   r$   Úoptional_argsX   s    r1   zhttps://www.google.comFc              	     sB   ddl ‰ˆdkrtƒ ‰dˆ_tˆƒ‡ ‡‡‡‡‡‡‡fdd„ƒ}|S )a‘  
    Label a test as requiring network connection and, if an error is
    encountered, only raise if it does not find a network connection.

    In comparison to ``network``, this assumes an added contract to your test:
    you must assert that, under normal conditions, your test will ONLY fail if
    it does not have network connectivity.

    You can call this in 3 ways: as a standard decorator, with keyword
    arguments, or with a positional argument that is the url to check.

    Parameters
    ----------
    t : callable
        The test requiring network connectivity.
    url : path
        The url to test via ``pandas.io.common.urlopen`` to check
        for connectivity. Defaults to 'https://www.google.com'.
    raise_on_error : bool
        If True, never catches errors.
    check_before_test : bool
        If True, checks connectivity before running the test case.
    error_classes : tuple or Exception
        error classes to ignore. If not in ``error_classes``, raises the error.
        defaults to OSError. Be careful about changing the error classes here.
    skip_errnos : iterable of int
        Any exception that has .errno or .reason.erno set to one
        of these values will be skipped with an appropriate
        message.
    _skip_on_messages: iterable of string
        any exception e for which one of the strings is
        a substring of str(e) will be skipped with an appropriate
        message. Intended to suppress errors where an errno isn't available.

    Notes
    -----
    * ``raise_on_error`` supersedes ``check_before_test``

    Returns
    -------
    t : callable
        The decorated test ``t``, with checks for connectivity errors.

    Example
    -------

    Tests decorated with @network will fail if it's possible to make a network
    connection to another URL (defaults to google.com)::

      >>> from pandas import _testing as tm
      >>> @tm.network
      ... def test_network():
      ...     with pd.io.common.urlopen("rabbit://bonanza.com"):
      ...         pass
      >>> test_network()  # doctest: +SKIP
      Traceback
         ...
      URLError: <urlopen error unknown url type: rabbit>

      You can specify alternative URLs::

        >>> @tm.network("https://www.yahoo.com")
        ... def test_something_with_yahoo():
        ...    raise OSError("Failure Message")
        >>> test_something_with_yahoo()  # doctest: +SKIP
        Traceback (most recent call last):
            ...
        OSError: Failure Message

    If you set check_before_test, it will check the url first and not run the
    test on failure::

        >>> @tm.network("failing://url.blaher", check_before_test=True)
        ... def test_something():
        ...     print("I ran!")
        ...     raise ValueError("Failure")
        >>> test_something()  # doctest: +SKIP
        Traceback (most recent call last):
            ...

    Errors not related to networking will always be raised.
    r   NTc               
     sæ   ˆr"ˆs"t ˆˆƒs"ˆ dˆ› �¡ zˆ| |ŽW S  tk
rà } z”t|dd ƒ}|sht|dƒrht|jdd ƒ}|ˆkr€ˆ d|› �¡ t|ƒ‰ t‡ fdd„ˆD ƒƒr®ˆ d|› �¡ t|ˆƒr¼ˆrÀ‚ nˆ d|› �¡ W 5 d }~X Y nX d S )	Nz<May not have network connectivity because cannot connect to ÚerrnoÚreasonz+Skipping test due to known errno and error c                 3  s   | ]}|  ¡ ˆ   ¡ kV  qd S r&   )Úlower)Ú.0Úm©Ze_strr#   r$   Ú	<genexpr>î   s     z+network.<locals>.wrapper.<locals>.<genexpr>z;Skipping test because exception message is known and error z4Skipping test due to lack of connectivity and error )	Úcan_connectÚskipÚ	ExceptionÚgetattrÚhasattrr3   ÚstrÚanyÚ
isinstance)r(   r*   Úerrr2   ©Ú_skip_on_messagesÚcheck_before_testÚerror_classesÚpytestÚraise_on_errorÚskip_errnosÚtÚurlr7   r$   r0   ×   s6    ÿþýÿÿÿznetwork.<locals>.wrapper)rF   r%   Únetworkr   )rI   rJ   rG   rD   rE   rH   rC   r0   r#   rB   r$   rK   t   s    \"rK   Úbool)Úreturnc              	   C  sd   |dkrt ƒ }z6t| dd�� }|jdkr8W 5 Q R £ W dS W 5 Q R X W n |k
rZ   Y dS X dS dS )a@  
    Try to connect to the given url. True if succeeds, False if OSError
    raised

    Parameters
    ----------
    url : basestring
        The URL to try to connect to

    Returns
    -------
    connectable : bool
        Return True if no OSError (unable to connect) or URLError (bad url) was
        raised
    Né   )r    éÈ   FT)r%   r   Ústatus)rJ   rE   Úresponser#   r#   r$   r9   ý   s    
r9   r   z"FilePath | ReadPickleBuffer | NonezDataFrame | Series)ÚobjÚpathrM   c              
   C  sR   |}|dkrdt dƒ› d�}t|ƒ�$}t | |¡ t |¡W  5 Q R £ S Q R X dS )a�  
    Pickle an object and then read it again.

    Parameters
    ----------
    obj : any object
        The object to pickle and then re-read.
    path : str, path object or file-like object, default None
        The path where the pickled object is written and then read.

    Returns
    -------
    pandas object
        The original object that was pickled and then re-read.
    NÚ__é
   z	__.pickle)r   r   ÚpdZ	to_pickleZread_pickle)rR   rS   Ú_pathZ	temp_pathr#   r#   r$   Úround_trip_pickle  s    
rX   z
str | None)rS   c              	   C  sP   ddl }| d¡j}|dkr d}t|ƒ�}| ||ƒƒ |||ƒƒ}W 5 Q R X |S )aÛ  
    Write an object to file specified by a pathlib.Path and read it back

    Parameters
    ----------
    writer : callable bound to pandas object
        IO writing function (e.g. DataFrame.to_csv )
    reader : callable
        IO reading function (e.g. pd.read_csv )
    path : str, default None
        The path where the object is written and then read.

    Returns
    -------
    pandas object
        The original object that was serialized and then re-read.
    r   NÚpathlibZ___pathlib___)rF   ÚimportorskipÚPathr   )ÚwriterÚreaderrS   rF   r[   rR   r#   r#   r$   Úround_trip_pathlib9  s    
r^   c              	   C  sP   ddl }| d¡j}|dkr d}t|ƒ�}| ||ƒƒ |||ƒƒ}W 5 Q R X |S )aá  
    Write an object to file specified by a py.path LocalPath and read it back.

    Parameters
    ----------
    writer : callable bound to pandas object
        IO writing function (e.g. DataFrame.to_csv )
    reader : callable
        IO reading function (e.g. pd.read_csv )
    path : str, default None
        The path where the object is written and then read.

    Returns
    -------
    pandas object
        The original object that was serialized and then re-read.
    r   Nzpy.pathZ___localpath___)rF   rZ   Úlocalr   )r\   r]   rS   rF   Z	LocalPathrR   r#   r#   r$   Úround_trip_localpathV  s    
r`   Útestc              	   C  sê   |f}d}d}| dkr.t j}d}||f}d}n’| dkrntj}d}tj|d�}t |¡}	t|ƒ|_||	f}d}nR| d	kr~t	j
}nB| d
krŽtj}n2| dkr¢tdƒj}n| dkr²tƒ }ntd| › �ƒ‚|||d��}
t|
|ƒ|Ž  W 5 Q R X dS )a¦  
    Write data to a compressed file.

    Parameters
    ----------
    compression : {'gzip', 'bz2', 'zip', 'xz', 'zstd'}
        The compression type to use.
    path : str
        The file path to write the data.
    data : str
        The data to write.
    dest : str, default "test"
        The destination file (for ZIP only)

    Raises
    ------
    ValueError : An invalid compression value was passed in.
    ÚwbÚwriteÚzipÚwÚwritestrÚtar)ÚnameÚaddfileÚgzipÚbz2ZzstdZ	zstandardÚxzzUnrecognized compression type: )ÚmodeN)ÚzipfileÚZipFileÚtarfileÚTarFileÚTarInfoÚioÚBytesIOr-   Úsizerj   ÚGzipFilerk   ÚBZ2Filer   Úopenr
   Ú
ValueErrorr<   )ÚcompressionrS   ÚdataÚdestr(   rm   ÚmethodZcompress_methodÚfileÚbytesr'   r#   r#   r$   Úwrite_to_compresseds  s6    

r€   ÚNonec                 C  s:   ddl m}m} | d kr.|ƒ D ]} || ƒ qn|| ƒ d S )Nr   )ÚcloseÚget_fignums)Zmatplotlib.pyplotr‚   rƒ   )ZfignumÚ_closerƒ   r#   r#   r$   r‚   «  s
    
r‚   )N)N)N)N)ra   )N)*Ú
__future__r   rk   Ú	functoolsr   rj   rs   r   rp   Útypingr   r   r   rn   Zpandas._typingr   r	   Zpandas.compatr
   Zpandas.compat._optionalr   ZpandasrV   Zpandas._testing._randomr   Zpandas._testing.contextsr   Zpandas.io.commonr   r   r   Z_network_error_messagesZ_network_errno_valsr%   r1   rK   r9   rX   r^   r`   r€   r‚   r#   r#   r#   r$   Ú<module>   sJ   ù 	# ÿ
8