
    d.0                    B   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 Z!d Z"e"dddde efd(d            Z#d)d*dZ$	 d)d+dZ%d)d,d!Z&d)d,d"Z'd-d.d%Z(d)d/d'Z)dS )0    )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                 p    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urllibs     O/var/www/html/t/fyr/venv311/lib/python3.11/site-packages/pandas/_testing/_io.py_get_default_network_errorsr&   I   sC      	!     c                <     t                      f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                       fd} o't                     dk    ot           d                   }|r d         }d  ||          S |S )Nc                     | gR i S N )fargs	decoratorkwargss    r%   decz+optional_args.<locals>.wrapper.<locals>.decf   s#    9Q0000000r'      r   r,   )lencallable)r.   r0   r1   is_decoratingr-   r/   s   ``   r%   wrapperzoptional_args.<locals>.wrapperd   sy    	1 	1 	1 	1 	1 	1 	1 #
Ks4yyA~K(47:K:K 	QAD3q66MJr'   r   )r/   r6   s   ` r%   optional_argsr7   X   s8     9
 
 
 
 
 Nr'   zhttps://www.google.comFurlstrraise_on_errorboolcheck_before_testc           	          ddl t                      d _        t                      f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                 $   r*	s(t                    s                    d            	  | i |S # t          $ r}t          |dd           }|s&t	          |d          rt          |j        dd           }|
v r                    d|            t          |          t          fdD                       r                    d|            t          |          r	r                     d|            Y d }~d S d }~ww xY w)Nz<May not have network connectivity because cannot connect to errnoreasonz+Skipping test due to known errno and error c              3  h   K   | ],}|                                                                  v V  -d S r+   )lower).0me_strs     r%   	<genexpr>z+network.<locals>.wrapper.<locals>.<genexpr>   s8      II!17799-IIIIIIr'   z;Skipping test because exception message is known and error z4Skipping test due to lack of connectivity and error )	can_connectskip	Exceptiongetattrhasattrr@   r9   any
isinstance)r.   r0   errr?   rE   _skip_on_messagesr<   error_classespytestr:   skip_errnostr8   s       @r%   r6   znetwork.<locals>.wrapper   s    	"	  ]33	
 KKTsTT  	V1d%f%%% 	V 	V 	VC$//E ;WUH55 ;
GT::##O#OOPPPHHEIIII7HIIIII WRUWW   c=11 ^ KKTsTTUUUUUUUUU%	Vs   8 
DCD

D)rQ   r&   networkr   )	rS   r8   r:   r<   rP   rR   rO   r6   rQ   s	   ``````` @r%   rT   rT   u   s    x MMM355AI
1XXV V V V V V V V V V V XV> Nr'   returnc                    |t                      }	 t          | d          5 }|j        dk    r	 ddd           dS 	 ddd           n# 1 swxY w Y   dS # |$ r Y dS w xY w)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)r8   rP   responses      r%   rG   rG      s      355S"%%% 	#%%	 	 	 	 	 	 	 	%	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 t    uus8   A A
A A 
AA AA A A objr   path"FilePath | ReadPickleBuffer | NoneDataFrame | Seriesc                    |}|dt          d           d}t          |          5 }t          j        | |           t          j        |          cddd           S # 1 swxY w Y   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   pd	to_pickleread_pickle)r[   r\   _path	temp_paths       r%   round_trip_picklerg     s    $ E})U2YY)))	e		 )	
S)$$$~i(() ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )s   )AA!$A!
str | Nonec                    ddl }|                    d          j        }|d}t          |          5 } |  ||                      | ||                    }ddd           n# 1 swxY w Y   |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pathlib___pathlib___)rQ   importorskipPathr   )writerreaderr\   rQ   rm   r[   s         r%   round_trip_pathlibrp   7  s    $ MMMy)).D|	d		 !tttDzzfTT$ZZ  ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! J   )A''A+.A+c                    ddl }|                    d          j        }|d}t          |          5 } |  ||                      | ||                    }ddd           n# 1 swxY w Y   |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.path___localpath___)rQ   rl   localr   )rn   ro   r\   rQ   	LocalPathr[   s         r%   round_trip_localpathrv   T  s    $ MMM##I..4I| 	d		 &tyyfYYt__%%& & & & & & & & & & & & & & & Jrq   testdestc                <   |f}d}d}| dk    rt           j        }d}||f}d}n| dk    rRt          j        }d}t          j        |          }t          j        |          }	t          |          |_        ||	f}d}nh| d	k    rt          j
        }nU| d
k    rt          j        }nB| dk    rt          d          j        }n'| dk    rt                      }nt!          d|             |||          5 }
 t#          |
|          |  ddd           dS # 1 swxY w Y   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bz2zstd	zstandardxzzUnrecognized compression type: )modeN)zipfileZipFiletarfileTarFileTarInfoioBytesIOr3   sizer   GzipFiler   BZ2Filer   openr   
ValueErrorrJ   )compressionr\   datarx   r.   r   methodcompress_methodfilebytesr-   s              r%   write_to_compressedr   q  s   & "GDDF e!/d|			!/D)))
4  II	e}			-			+			4[AAF			'//H;HHIII	D	)	)	) "Q6D!!" " " " " " " " " " " " " " " " " "s   0DDDNonec                d    ddl m}m} |  |            D ]}  ||            d S  ||            d S )Nr   )closeget_fignums)matplotlib.pyplotr   r   )fignum_closer   s      r%   r   r     sr           
 ~!kmm 	 	FF6NNNN	 	 	vr'   )r8   r9   r:   r;   r<   r;   r+   )rU   r;   )r[   r   r\   r]   rU   r^   )r\   rh   )rw   )rx   r9   )rU   r   )*
__future__r   r   	functoolsr   r   r   r!   r   typingr   r   r   r   pandas._typingr	   r
   pandas.compatr   pandas.compat._optionalr   pandasrb   pandas._testing._randomr   pandas._testing.contextsr   pandas.io.commonr   r   r   _network_error_messages_network_errno_valsr&   r7   rT   rG   rg   rp   rv   r   r   r,   r'   r%   <module>r      sg   " " " " " " 



        				           
         ( ' ' ' ' ' > > > > > >     ) ) ) ) ) ) 1 1 1 1 1 1 $ $ $ $ $ $         ( "    :  ( ##-B B B B BJ    F :>) ) ) ) )4    :    :1" 1" 1" 1" 1"p
 
 
 
 
 
 
r'   