B []0j @sddlZddlmZddlmZddlmZddlmZddlZddl Z ddl Z ddl Z ddl mZddlZddlZddlZddlmZmZddlZddlZddlZddlmZmZdd lmZmZmZddl m!m"Z#dd l$m%Z%m&Z&m'Z'dd l(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4dd l5m6Z6ddl7Z8dd l7m9Z9m:Z:m;Z;mZ>m?Z?m@Z@mAZAmBZBddlCmDZDddlEmFZFmGZGmHZHmIZImJZJmKZKddlLmMZMddlNmOZOe&ZPdZQdZRdZSeTeUfZVddZWddZXeWddZYdddZZdddZ[ddd Z\ed!d"Z]dd$d%Z^dd'd(Z_d)d*Z`dd,d-Zadd0d1Zbejcedejeejfejgd2fd3Zhejcedd4iejekeld5d6ejfejmd2fd3Zndd8d9Zodd:d;Zpdd?Zrdd@dAZsed dBdCZtedDdEZuedFdGZvdHdIZwd e=e=eexeyfexeexezfexexeyddK dLdMZ{d dOdPZ|d dRdSZ}dTdUZ~dVdWZdXdYZd d[d\Zdd^d_ZddadbZddddeZddgdhZddidjZddldmZddndoZddqdrZddtduZdvdwZddxdyZdzd{Zdd|d}ZdddZdddZddZddZddZdddZdddZdddZdddZdddZd ddZd!ddZd"ddZd#ddZd$ddZd%ddZd&ddZd'ddZd(ddZddZd)ddZd*ddZd+ddZd,ddZddZd-ddZd.ddZd/ddZd0ddZd1ddZddZddÄZddńZd2ddDŽZd3ddʄZd4dd̄Zd5dd΄Zd6ddфZd7ddӄZGddՄdeZddׄZdZdZee jjefZefddۄZedeSdeeefddބZeZd8ddZGdddZeeddd+d+fddZGdddZeddZed9ddZɐd:ddZGdddeAZGddde;ZGddde8j̓ZGddde8jσZGddde9ZeddZҐd;ddZddZdS(<N)Counter)contextmanager)datetime)wraps)rmtree)Unioncast)randrandn)can_set_locale get_locales set_locale)_get_lzma_file _import_lzmaraise_with_traceback) is_boolis_categorical_dtypeis_datetime64_dtypeis_datetime64tz_dtypeis_extension_array_dtypeis_interval_dtype is_list_like is_numberis_period_dtype is_sequenceis_timedelta64_dtypeneeds_i8_conversion)array_equivalent) CategoricalCategoricalIndex DataFrame DatetimeIndexIndex IntervalIndex MultiIndex RangeIndexSeries bdate_range)take_1d) DatetimeArrayExtensionArray IntervalArray PeriodArrayTimedeltaArray period_array)urlopen) pprint_thingFcCs&tjdd}d|kr"tdtdS)NPANDAS_TESTING_MODENone deprecatealways)osenvirongetwarnings simplefilter_testing_mode_warnings) testing_moder>7/tmp/pip-install-svzetoqp/pandas/pandas/util/testing.pyset_testing_modeRsr@cCs&tjdd}d|kr"tdtdS)Nr3r4r5ignore)r7r8r9r:r;r<)r=r>r>r?reset_testing_modeYsrBcCstjddddS)zJ Reset the display options for printing and representing objects. z ^display.T)ZsilentN)pdZ reset_optionr>r>r>r?reset_display_optionscsrDc CsB|dkrdjtdd}t|}t||t|SQRXdS)a Pickle an object and then read it again. Parameters ---------- obj : pandas object The object to pickle and then re-read. path : str, default None The path where the pickled object is written and then read. Returns ------- round_trip_pickled_object : pandas object The original object that was pickled and then re-read. Nz__{random_bytes}__.pickle )Z random_bytes)formatrands ensure_cleanrCZ to_pickleZ read_pickle)objpathr>r>r?round_trip_pickleks   rKc CsPddl}|dj}|dkr d}t|}||||||}WdQRX|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 ------- round_trip_object : pandas object The original object that was serialized and then re-read. rNZpathlibZ ___pathlib___)pytest importorskipPathrH)writerreaderrJrLrNrIr>r>r?round_trip_pathlibs   rQc CsPddl}|dj}|dkr d}t|}||||||}WdQRX|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 ------- round_trip_object : pandas object The original object that was serialized and then re-read. rNzpy.pathZ___localpath___)rLrMlocalrH)rOrPrJrLZ LocalPathrIr>r>r?round_trip_localpaths   rSccs|dkrt|d}n|dkr*t|d}n|dkr@t|d}np|dkrXtt|d}nX|dkrt|}|}t |dkr|| }qt d |nd |}t |z |VWd| |dkr| XdS) a  Open a compressed file and return a file object Parameters ---------- path : str The path where the file is read from compression : {'gzip', 'bz2', 'zip', 'xz', None} Name of the decompression to use Returns ------- f : file object Nrbgzipbz2xzzipz)ZIP file {} error. Only one file per ZIP.z!Unrecognized compression type: {})openrUrVBZ2FilerlzmazipfileZipFilenamelistlenpop ValueErrorrFclose)rJ compressionfzip_fileZ zip_namesmsgr>r>r?decompress_files*     rhtestc Cs|dkrddl}|j}nT|dkr0ddl}|j}n<|dkrHddl}|j}n$|dkrZtt}nd|}t ||dkrd} ||f} d } nd } |f} d } ||| d } t | | | WdQRXdS) a Write data to a compressed file. Parameters ---------- compression : {'gzip', 'bz2', 'zip', 'xz'} 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. rXrNrUrVrWz!Unrecognized compression type: {}wwritestrwbwrite)mode) r]r^rUGzipFilerVr[rr\rFrbgetattr) rdrJdatadestr]Zcompress_methodrUrVrgrnargsmethodrer>r>r?write_to_compresseds,  ruequivcKst|tjr(t||fd||d|nt|tjrPt||fd||d|nt|tjrxt||fd||d|nr|rt|rt|rnBt |rt |rn0t|t j st|t j rd}nd}t |||dt j||f||d|dS) aw Check that the left and right objects are approximately equal. By approximately equal, we refer to objects that are numbers or that contain numbers which may be equivalent to specific levels of precision. Parameters ---------- left : object right : object check_dtype : bool / string {'equiv'}, default 'equiv' Check dtype if both a and b are the same type. If 'equiv' is passed in, then `RangeIndex` and `Int64Index` are also considered equivalent when doing type checking. check_less_precise : bool or int, default False Specify comparison precision. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the number of digits to compare. When comparing two numbers, if the first number has magnitude less than 1e-5, we compare the two numbers directly and check whether they are equivalent within the specified precision. Otherwise, we compare the **ratio** of the second number to the first number and check whether it is equivalent to 1 within the specified precision. F) check_exactexactcheck_less_precise)rw check_dtyperyz numpy arrayInput)rI)rzryN) isinstancerCr"assert_index_equalr&assert_series_equalr assert_frame_equalrrnpndarrayassert_class_equal_testingassert_almost_equal)leftrightrzrykwargsrIr>r>r?rsN      rcCsRd}|j}t||s,t|j||t|dt||sNt|j||t|ddS)a Helper method for our assert_* methods that ensures that the two objects being compared have the right type before proceeding with the comparison. Parameters ---------- left : The first object being compared. right : The second object being compared. cls : The class type to check against. Raises ------ AssertionError : Either `left` or `right` is not an instance of `cls`. z9{name} Expected type {exp_type}, found {act_type} instead)nameZexp_typeZact_typeN)__name__r|AssertionErrorrFtype)rrclserr_msgZcls_namer>r>r?_check_isinstanceqs  rTcCs t||ttj|||ddS)N) compare_keys)rdictrassert_dict_equal)rrrr>r>r?rs rr>?cCs t||kS)N)r )sizepr>r>r?randboolsrrY)dtypeiiOcCsFtjjt|t|dtj|f|}|dkr8|S||SdS)z"Generate an array of byte strings.)rN) rrandomchoice RANDS_CHARSprodviewstr_reshapeastype)ncharsrrretvalr>r>r? rands_arrays  rcCsFtjjt|t|dtj|f|}|dkr8|S||SdS)z%Generate an array of unicode strings.)rN) rrr RANDU_CHARSrrunicode_rr)rrrrr>r>r? randu_arrays  rcCsdtjt|S)zt Generate one random byte string. See `rands_array` if you want to create an array of random strings. r)joinrrrr)rr>r>r?rGsrGcCsdtjt|S)z Generate one random unicode string. See `randu_array` if you want to create an array of random unicode strings. r)rrrrr)rr>r>r?randusrcCs>ddlm}m}|dkr2x |D] }||q Wn||dS)Nr) get_fignumsrc)matplotlib.pyplotrrc)Zfignumr_closer>r>r?rcs  rcccs |pd}d}|r4tj|d}z |VWd|Xnttj|rLtdytj|d\}}Wn&t k rddl }| dYnXz |VWdyt|Wn&t k rt dj||dYnXytj|rt|Wn4t k r}zt d j|d Wdd}~XYnXXdS) aGets a temporary path and agrees to remove on close. Parameters ---------- filename : str (optional) if None, creates a temporary file which is then removed when out of scope. if passed, creates temporary file with filename as ending. return_filelike : bool (default False) if True, returns a file-like which is *always* cleaned. Necessary for savefig and other functions which want to append extensions. rN)suffixz-Can't pass a qualified name to ensure_clean()rz$no unicode file names on this systemz7Couldn't close file descriptor: {fdesc} (file: {fname}))Zfdescfnamez#Exception on removing file: {error})error)tempfile TemporaryFilercr`r7rJdirnamerbmkstempUnicodeEncodeErrorrLskip ExceptionprintrFexistsremove)filenameZreturn_filelikefdrerLer>r>r?rHs6      rHccs@tjdd}z |VWdy t|Wntk r8YnXXdS)z{ Get a temporary directory path and agrees to remove on close. Yields ------ Temporary directory path r)rN)rmkdtemprr)Zdirectory_namer>r>r?ensure_clean_dirs   rc cs2ttj}z dVWdtjtj|XdS)z Get a context manager to safely set environment variables All changes will be undone on close, hence environment variables set within this contextmanager will neither persist nor change global state. N)rr7r8clearupdate)Z saved_environr>r>r?!ensure_safe_environment_variables#s    rcCst|t|kS)zJChecks if the set of unique elements of arr1 and arr2 are equivalent. ) frozenset)Zarr1Zarr2r>r>r? equalContents7srr") rrrx check_namesryrwcheck_categoricalrIreturnc spd}dfdd } dd} t||t| |||d|j|jkr|dj|d} d j|j|d } d j|j|d } t|| | | t|t|krd j|d} djt||d} djt||d} t|| | | |jdkrNtt|}tt|}xbt|jD]T}| ||}| ||}dj|d}t ||||||d| |j ||j ||dqW|rr| |st |j|jktdt|}dj|t |dd}t||||ntj|j|j||||d|rtd|||dt|tjst|tjrtd|||dt|tjs*t|tjr8t|j|jrlt|sRt|rlt|j|jdj|dddS) aCheck that left and right Index are equal. Parameters ---------- left : Index right : Index exact : bool / string {'equiv'}, default 'equiv' Whether to check the Index class, dtype and inferred_type are identical. If 'equiv', then RangeIndex can be substituted for Int64Index as well. check_names : bool, default True Whether to check the names attribute. check_less_precise : bool or int, default False Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare check_exact : bool, default True Whether to compare number exactly. check_categorical : bool, default True Whether to compare internal Categorical exactly. obj : str, default 'Index' Specify object name being compared, internally used to show appropriate assertion message Tr"csVrRt|||dr(td|||d|jdkrB|jdksRtntd|||ddS)N)rxrIr)rI)stringunicode inferred_type)rassert_attr_equalrr)lrrI)rrxr>r? _check_typesas z(assert_index_equal.._check_typescSs>|j|}|j|}t|j||jd}|j||j|d}|S)N) fill_value)r)levelscodesr(valuesZ _na_valueZ _shallow_copynames)indexleveluniquelabelsZfilledrr>r>r?_get_ilevel_valuesos   z.assert_index_equal.._get_ilevel_values)rIz{obj} levels are differentz{nlevels}, {left})nlevelsrz{nlevels}, {right})rrz{obj} length are differentz{length}, {left})lengthrz{length}, {right})rrrYzMultiIndex level [{level}])r)rxrryrwrIgY@z${obj} values are different ({pct} %))rIpct)ryrzrIlobjZrobjrfreqz{obj} categoryN)r")rr"rrFraise_assert_detailr`rr$ranger}requalsrsumrrintroundrrrr|rCZ PeriodIndexr#assert_interval_array_equalrassert_categorical_equal)rrrxrryrwrrI__tracebackhide__rrmsg1msg2Zmsg3rZllevelZrlevelrdiffrgr>)rrxr?r}=sn"            $r}r{cCsd}dd}|dkrlt|t|krt|jt|jh}t|ddhrdj|d}t||||||n6|rt|t|krd j|d}t||||||d S) zchecks classes are equal.TcSs8t|tr|Sy|jjStk r2tt|SXdS)N)r|r" __class__rAttributeErrorreprr)xr>r>r? repr_classs  z&assert_class_equal..repr_classrvZ Int64Indexr%z {obj} classes are not equivalent)rIz{obj} classes are differentN)rrr`rFr)rrrxrIrrtypesrgr>r>r?rs   r Attributesc Csd}t||}t||}||kr$dSt|rLt|rLt|rLt|rLdSy ||k}Wntk rpd}YnXt|ts|}|rdSdj|d}t ||||dS)aKchecks attributes are equal. Both objects must have attribute. Parameters ---------- attr : str Attribute name being compared. left : object right : object obj : str, default 'Attributes' Specify object name being compared, internally used to show appropriate assertion message TFz Attribute "{attr}" are different)attrN) rprrisnan TypeErrorr|boolallrFr) rrrrIrZ left_attrZ right_attrresultrgr>r>r?rs(         rcCsddlm}t|tjtjfrZx`|D],}dj|j j d}t||j t fs(t |q(Wn&t||jtt fst dj|j j ddS)NrzJone of 'objs' is not a matplotlib Axes instance, type encountered {name!r})rzqobjs is neither an ndarray of Artist instances nor a single Artist instance, tuple, or dict, "objs" is a {name!r})rZpyplotr|rCr&rrZravelrFrrZAxesrrZArtisttuple)objsZpltelrgr>r>r?"assert_is_valid_plot_return_object s  rcCs t|dS)N__iter__)hasattr)rIr>r>r? isiterablesrcCs.t|ttfr|j}t|tt|dS)z#Assert that the sequence is sorted.N)r|r"r&rassert_numpy_array_equalrsortarray)seqr>r>r?assert_is_sorted"srrcCst||t|rHt|j|jdj|ddt|j|j|dj|ddnLt|j|jdj|ddt|j|j|j|jdj|ddt d|||ddS)avTest that Categoricals are equivalent. Parameters ---------- left : Categorical right : Categorical check_dtype : bool, default True Check that integer dtype of the codes are the same check_category_order : bool, default True Whether the order of the categories should be compared, which implies identical integer codes. If False, only the resulting values are compared. The ordered attribute is checked regardless. obj : str, default 'Categorical' Specify object name being compared, internally used to show appropriate assertion message z{obj}.categories)rIz {obj}.codes)rzrIz {obj}.valuesorderedN) rrr} categoriesrFrrZ sort_valuesZtaker)rrrzZcheck_category_orderrIr>r>r?r*s$   rr+cCsXt||tt|j|j|dj|ddt|j|j|dj|ddtd|||ddS)aTest that two IntervalArrays are equivalent. Parameters ---------- left, right : IntervalArray The IntervalArrays to compare. exact : bool / string {'equiv'}, default 'equiv' Whether to check the Index class, dtype and inferred_type are identical. If 'equiv', then RangeIndex can be substituted for Int64Index as well. obj : str, default 'IntervalArray' Specify object name being compared, internally used to show appropriate assertion message z {obj}.left)rI)rxrIclosedN)rr+r}rrFrr)rrrxrIr>r>r?rYs  rr,cCs:t||tt|j|jdj|ddtd|||ddS)Nz {obj}.values)rIr)rr,r_datarFr)rrrIr>r>r?assert_period_array_equalss rr)cCsNd}t||tt|j|jdj|ddtd|||dtd|||ddS)NTz {obj}._data)rIrtz)rr)rrrFr)rrrIrr>r>r?assert_datetime_array_equal|s  rr-cCs>d}t||tt|j|jdj|ddtd|||ddS)NTz {obj}._data)rIr)rr-rrrFr)rrrIrr>r>r?assert_timedelta_array_equals r cCsd}t|tjrt|}nt|r*t|}t|tjr@t|}nt|rPt|}dj||||d}|dk rz|dj|d7}t|dS)NTz?{obj} are different {message} [left]: {left} [right]: {right})rImessagerrz [diff]: {diff})r)r|rrr0rrrFr)rIr rrrrrgr>r>r?rs    r numpy arrayc sd}t||dt||tjdd}||} ||} |dkr`| | k rdj| | d} t| n&|dkr| | krd j| | d} t| fd d } t||d s| ||||rt|tjrt|tjrtd ||ddS)a Checks that 'np.ndarray' is equivalent Parameters ---------- left : np.ndarray or iterable right : np.ndarray or iterable strict_nan : bool, default False If True, consider NaN and None to be different. check_dtype: bool, default True check dtype if both a and b are np.ndarray err_msg : str, default None If provided, used as assertion message check_same : None|'copy'|'same', default None Ensure left and right refer/do not refer to the same memory area obj : str, default 'numpy array' Specify object name being compared, internally used to show appropriate assertion message T)rIcSst|dddk r|jS|S)Nbase)rpr )rIr>r>r? _get_basesz+assert_numpy_array_equal.._get_baseZsamez{left!r} is not {right!r})rrcopyz{left!r} is {right!r}cs|dkr|j|jkr.tdjd|j|jd}x,t||D]\}}t||ds>|d7}q>W|d|j}djt|dd }t|||t|dS) Nz{obj} shapes are different)rIr) strict_nanrYgY@z${obj} values are different ({pct} %)r)rIr) shaperrFrXrrrrr)rrrrrrrg)rIrr>r?_raises    z(assert_numpy_array_equal.._raise)rrN) rrrrrFrrr|r) rrrrzrZ check_samerIrr Z left_baseZ right_basergrr>)rIrr?rs(  rc Cst|tstdt|ts$td|r8td||ddt|drdt|t|krdt|j|jdSt | }t | }t||ddt || t }t || t }|rt||ddnt j||||dd dS) a;Check that left and right ExtensionArrays are equal. Parameters ---------- left, right : ExtensionArray The two arrays to compare check_dtype : bool, default True Whether to check if the ExtensionArray dtypes are identical. check_less_precise : bool or int, default False Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare. check_exact : bool, default False Whether to compare number exactly. Notes ----- Missing values are checked separately from valid values. A mask of missing values is computed for each and checked to match. The remaining all-valid values are cast to object dtype and checked. zleft is not an ExtensionArrayzright is not an ExtensionArrayrr*)rIasi8NzExtensionArray NA mask)rzryrI)r|r*rrrrrrrasarrayZisnarobjectrr) rrrzryrwZleft_naZright_naZ left_validZ right_validr>r>r?assert_extension_array_equals(rr&c  CsHd} t||t|r&t|t|s&tt|t|krldjt||jd} djt||jd} t| d| | t |j|j||||| dj| dd |rt |rt |r| sn t d |||rt | | |d j| dd n|rBt|st|r*t|jt|js@d j|j|jd}t|nt | | |dnt|sVt|rft|j|jnt|jrt|jrt|jstt|j|jn\t|rt |st|rt |st|j|jn$tj| | ||d j| dd|rt d||| d| rDt |s*t |rDt|j|jdj| dddS)a_Check that left and right Series are equal. Parameters ---------- left : Series right : Series check_dtype : bool, default True Whether to check the Series dtype is identical. check_index_type : bool / string {'equiv'}, default 'equiv' Whether to check the Index class, dtype and inferred_type are identical. check_series_type : bool, default True Whether to check the Series class is identical. check_less_precise : bool or int, default False Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare. When comparing two numbers, if the first number has magnitude less than 1e-5, we compare the two numbers directly and check whether they are equivalent within the specified precision. Otherwise, we compare the **ratio** of the second number to the first number and check whether it is equivalent to 1 within the specified precision. check_names : bool, default True Whether to check the Series and Index names attribute. check_exact : bool, default False Whether to compare number exactly. check_datetimelike_compat : bool, default False Compare datetime-like which is comparable ignoring dtype. check_categorical : bool, default True Whether to compare internal Categorical exactly. obj : str, default 'Series' Specify object name being compared, internally used to show appropriate assertion message. Tz {len}, {left})r`rz{len}, {right})r`rzSeries length are differentz {obj}.index)rI)rxrryrwrrIrz{obj})rzrIz:[datetimelike_compat=True] {left} is not equal to {right}.)rr)rz)ryrzrIrz{obj} categoryN)rr&r|rrr`rFrrr}rrrZ_internal_get_valuesrr"rrrrrrrrrZ_valuesrrr)rrrzcheck_index_typecheck_series_typeryrrwcheck_datetimelike_compatrrIrrrrgr>r>r?r~/sz0        r~r cCsd}t||t|r&t|t|s&t|j|jkr\t| dj| ddj|jddj|jd| rp|||}}t |j |j |||| | dj| ddt |j |j |||| | dj| dd|r.| }| }xt tt |t |D]8}||kst||kstt|||||| d qWnrxpt|j D]b\}}||ksPt|jd d |f}|jd d |f}t|||||| || | d j| |d d q:Wd S)a5 Check that left and right DataFrame are equal. This function is intended to compare two DataFrames and output any differences. Is is mostly intended for use in unit tests. Additional parameters allow varying the strictness of the equality checks performed. Parameters ---------- left : DataFrame First DataFrame to compare. right : DataFrame Second DataFrame to compare. check_dtype : bool, default True Whether to check the DataFrame dtype is identical. check_index_type : bool / string {'equiv'}, default 'equiv' Whether to check the Index class, dtype and inferred_type are identical. check_column_type : bool / string {'equiv'}, default 'equiv' Whether to check the columns class, dtype and inferred_type are identical. Is passed as the ``exact`` argument of :func:`assert_index_equal`. check_frame_type : bool, default True Whether to check the DataFrame class is identical. check_less_precise : bool or int, default False Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare. When comparing two numbers, if the first number has magnitude less than 1e-5, we compare the two numbers directly and check whether they are equivalent within the specified precision. Otherwise, we compare the **ratio** of the second number to the first number and check whether it is equivalent to 1 within the specified precision. check_names : bool, default True Whether to check that the `names` attribute for both the `index` and `column` attributes of the DataFrame is identical, i.e. * left.index.names == right.index.names * left.columns.names == right.columns.names by_blocks : bool, default False Specify how to compare internal data. If False, compare by columns. If True, compare by blocks. check_exact : bool, default False Whether to compare number exactly. check_datetimelike_compat : bool, default False Compare datetime-like which is comparable ignoring dtype. check_categorical : bool, default True Whether to compare internal Categorical exactly. check_like : bool, default False If True, ignore the order of index & columns. Note: index labels must match their respective rows (same as in columns) - same labels must be with the same data. obj : str, default 'DataFrame' Specify object name being compared, internally used to show appropriate assertion message. See Also -------- assert_series_equal : Equivalent method for asserting Series equality. DataFrame.equals : Check DataFrame equality. Examples -------- This example shows comparing two DataFrames that are equal but with columns of differing dtypes. >>> from pandas.util.testing import assert_frame_equal >>> df1 = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) >>> df2 = pd.DataFrame({'a': [1, 2], 'b': [3.0, 4.0]}) df1 equals itself. >>> assert_frame_equal(df1, df1) df1 differs from df2 as column 'b' is of a different type. >>> assert_frame_equal(df1, df2) Traceback (most recent call last): AssertionError: Attributes are different ... Attribute "dtype" are different [left]: int64 [right]: float64 Ignore differing dtypes in columns with check_dtype. >>> assert_frame_equal(df1, df2, check_dtype=False) Tz{obj} shape mismatch)rIz {shape!r})rz {obj}.index)rxrryrwrrIz {obj}.columns)rzrINz{obj}.iloc[:, {idx}])rIidx)rzrryrwrrrrI)rr r|rrrrrFZ reindex_liker}rcolumnsZ_to_dict_of_blockslistsetkeysr enumerateZilocr~)rrrzrZcheck_column_typecheck_frame_typeryrZ by_blocksrwrrZ check_likerIrZrblocksZlblocksricolZlcolZrcolr>r>r?rsjj    &rcKsd}t|tjr t||f|nt|tjrr>r? assert_equal~s(          r#cCs|tjkrt|}n|tjkr,t|}n|tjkrPt|}|r|j}nf|tkrbt|}nT|tkrtt|}nB|t krt |}n0|t j krt |}n|t krt |}nt||S)z Helper function to wrap the expected output of a test in a given box_class. Parameters ---------- expected : np.ndarray, Index, Series box_cls : {Index, Series, DataFrame} Returns ------- subclass of box_cls )rCr"r&r Zto_frameTr,r.r)r-rrrto_arrayr")expectedZbox_clsZ transposer>r>r? box_expecteds(           r'cCsJt|rt|St|s t|r*t|St|rr>r?r%s  r%cCst||tjt|j|j|dt|jtjjj s6t t|jtjjj sLt |sf|j }|j }n |j}|j}|r|j dkr| }| }||stdd||n|rtd|||rtd||t|||ddS)a#Check that the left and right SparseArray are equal. Parameters ---------- left : SparseArray right : SparseArray check_dtype : bool, default True Whether to check the data dtype is identical. check_kind : bool, default True Whether to just the kind of the sparse index for each column. check_fill_value : bool, default True Whether to check that left.fill_value matches right.fill_value consolidate_block_indices : bool, default False Whether to consolidate contiguous blocks for sparse arrays with a BlockIndex. Some operations, e.g. concat, will end up with block indices that could be consolidated. Setting this to true will create a new BlockIndex for that array, with consolidated block indices. )rzblockzSparseArray.indexzindex are not equalrrN)rrCZ SparseArrayrZ sp_valuesr|Zsp_index_libssparseZ SparseIndexrZto_block_indexkindZ to_int_indexrrrto_dense)rrrz check_kindcheck_fill_valueconsolidate_block_indicesZ left_indexZ right_indexr>r>r?assert_sp_array_equals(       r0 SparseSeriesc Cst||tj|r t||| dt|j|jdj| ddt|j|j|||d|r`t d|||rpt d||t t |jt |jdS)aCheck that the left and right SparseSeries are equal. Parameters ---------- left : SparseSeries right : SparseSeries check_dtype : bool, default True Whether to check the Series dtype is identical. exact_indices : bool, default True check_series_type : bool, default True Whether to check the SparseSeries class is identical. check_names : bool, default True Whether to check the SparseSeries name attribute. check_kind : bool, default True Whether to just the kind of the sparse index for each column. check_fill_value : bool, default True Whether to check that left.fill_value matches right.fill_value consolidate_block_indices : bool, default False Whether to consolidate contiguous blocks for sparse arrays with a BlockIndex. Some operations, e.g. concat, will end up with block indices that could be consolidated. Setting this to true will create a new BlockIndex for that array, with consolidated block indices. obj : str, default 'SparseSeries' Specify the object name being compared, internally used to show the appropriate assertion message. )rIz {obj}.index)r-r.r/rrN) rrCr1rr}rrFr0rrrrr) rrrz exact_indicesrrr-r.r/rIr>r>r?assert_sp_series_equals'  r3SparseDataFramec Cst||tj|r t|||dt|j|jdj|ddt|j|jdj|dd|rhtd|||dxX| D]L\} } | |kst |rt | || ||||dqrt | ||  |dqrWx|D]} | |kst qWdS)aCheck that the left and right SparseDataFrame are equal. Parameters ---------- left : SparseDataFrame right : SparseDataFrame check_dtype : bool, default True Whether to check the Series dtype is identical. exact_indices : bool, default True SparseSeries SparseIndex objects must be exactly the same, otherwise just compare dense representations. check_frame_type : bool, default True Whether to check the SparseDataFrame class is identical. check_kind : bool, default True Whether to just the kind of the sparse index for each column. check_fill_value : bool, default True Whether to check that left.fill_value matches right.fill_value consolidate_block_indices : bool, default False Whether to consolidate contiguous blocks for sparse arrays with a BlockIndex. Some operations, e.g. concat, will end up with block indices that could be consolidated. Setting this to true will create a new BlockIndex for that array, with consolidated block indices. obj : str, default 'SparseDataFrame' Specify the object name being compared, internally used to show the appropriate assertion message. )rIz {obj}.indexz {obj}.columnsZdefault_fill_value)rzr-r.r/)rzN)rrCr4rr}rrFrritemsrr3r~r,) rrrzr2rr-r.r/rIr!Zseriesr>r>r?assert_sp_frame_equalUs*&   r6cCs*x$|D]}||kstdj|dqWdS)NzDid not contain item: '{key!r}')key)rrF)iterableZdickr>r>r?assert_contains_alls r:cKsPxJt||D]<\}}t||f|djt|t|d}||k s t|q WdS)z iter1, iter2: iterables that produce elements comparable with assert_almost_equal Checks that the elements are equal, but not the same object. (Does not check that items in sequences are also not the same object) zdExpected object {obj1!r} and object {obj2!r} to be different objects, but they were the same object.)Zobj1obj2N)rXrrFrr)Ziter1Ziter2Z eql_kwargsZelem1Zelem2rgr>r>r? assert_copys r<cCstjd|S)N)rascii_uppercase)r9r>r>r?getColssr>rEcCsttd|d|dS)NrE)rr)r)r"r)r9rr>r>r?makeStringIndexsr?cCsttd|d|dS)NrE)rr)r)r"r)r9rr>r>r?makeUnicodeIndexsr@cKs*td|d}ttj||fd|i|S)z' make a length k index or n categories r2)rrr)rrrrr)r9nrrrr>r>r?makeCategoricalIndexs rCcKs*tjdd|dd}tj|fd|i|S)z make a length k IntervalIndex rdrY)numr)rZlinspacer#Z from_breaks)r9rrrr>r>r?makeIntervalIndexsrFcCsL|dkrtdg|dS|dkr.tddg|dStddgdg|d|dS)NrYT)rF)r")r9rr>r>r? makeBoolIndexs rHcCsttt||dS)N)r)r"rr)r9rr>r>r? makeIntIndexsrIcCstddt|D|dS)NcSsg|] }d|qS)lr>).0r r>r>r? sz!makeUIntIndex..)r)r"r)r9rr>r>r? makeUIntIndexsrLcKstd|dfd|i|S)NrrYr)r%)r9rrr>r>r?makeRangeIndexsrMcCs:ttj|tjd}t|dtjdd|dS)NrYrEr )r)sortedrrZ random_sampler"randint)r9rrr>r>r?makeFloatIndexsrQBcKs0tddd}t||||d}t|fd|i|S)NirY)periodsrrr)rr'r!)r9rrrdtdrr>r>r? makeDateIndexs rVDcKstjfd|||d|S)Nz1 day)startrSrr)rCZtimedelta_range)r9rrrr>r>r?makeTimedeltaIndexsrYcKs*tddd}tjf||d|d|}|S)NirYrR)rXrSrr)rrCZ period_range)r9rrrTrUr>r>r?makePeriodIndexs rZcKstjdd|i|S)N)Zfoobar)rYrGr)r[)r$Z from_product)r9rrr>r>r?makeMultiIndexsr]c cs8tttttttttt t g }x|D]}||dVq WdS)zGenerator which can be iterated over to get instances of all the various index classes. Parameters ---------- k: length of each of the index instances )r9N) rIrQr?r@rVrZrYrHrMrFrC)r9Zall_make_index_funcsmake_index_funcr>r>r?all_index_generators  r_ccs*tttttttg}x|D] }|VqWdS)N)rVrZrYrMrFrCr])make_index_funcsr^r>r>r?index_subclass_makers_generators raccs(tttg}x|D]}||dVqWdS)zGenerator which can be iterated over to get instances of all the classes which represent time-series. Parameters ---------- k: length of each of the index instances )r9N)rVrZrY)r9r`r^r>r>r?all_timeseries_index_generator's  rbcCstt}ttt||dS)N)rr)r?Nr&r )rrr>r>r?makeFloatSeries5srdcCstt}ttt||dS)N)rr)r?rcr&r )rrr>r>r?makeStringSeries:srecCs*tt}t|td}tt}t|||dS)N)r)rr)rVrcr"rr?r&)rZ dateIndexrr>r>r?makeObjectSeries?s rfcsttfddttDS)Ncsi|]}tttd|qS))r)r&r rc)rJc)rr>r? Hsz!getSeriesData..)r?rcr>Kr>r>)rr? getSeriesDataFsrjcCs&|dkr t}tt|t||d|dS)N)r)rr)rcr&r rV)nperrrr>r>r?makeTimeSeriesKsrlcCs"|dkr t}tt|t||dS)N)rr)rcr&r rZ)rkrr>r>r?makePeriodSeriesQsrmcsfddttDS)Ncsi|]}t|qSr>)rl)rJrg)rrkr>r?rhXsz%getTimeSeriesData..)r>ri)rkrr>)rrkr?getTimeSeriesDataWsrncsfddttDS)Ncsi|]}t|qSr>)rm)rJrg)rkr>r?rh\sz!getPeriodData..)r>ri)rkr>)rkr? getPeriodData[srocCst||}t|S)N)rnr )rkrrqr>r>r?makeTimeDataFrame`s rpcCst}t|S)N)rjr )rqr>r>r? makeDataFrameesrqcCsNtdddddg}dddd d gdddddgd d d ddgtdddd}||fS)Nabrgdrgg?g@g@g@Zfoo1Zfoo2Zfoo3Zfoo4Zfoo5z1/1/2009r)rS)ArRCrW)r"r')rrqr>r>r?getMixedTypeDictjs    rwcCsttdS)NrY)r rwr>r>r>r?makeMixedDataFramewsrxcCst|}t|S)N)ror )rkrqr>r>r?makePeriodFrame{sry#c sV|dkrdg|}t|r&t||ks*t|dksR|dksR|dksRt||ksRt|dksn|dkrj|dksnt|dkrfddt|D}|dkrd}t|tr|dkr|g}tttt t t t t d|}|r||}|r|d |_|S|dk rtd j|d t||kr*|dg|t|t||ks 1 produces multindex) prefix - a string prefix for labels names - (Optional), bool or list of strings. if True will use default names, if false will use no names, if a list is given, the name of each level in the index will be taken from the list. ndupe_l - (Optional), list of ints, the number of rows for which the label will repeated at the corresponding level, you can specify just the first few, the rest will use the default ndupe_l of 1. len(ndupe_l) <= nlevels. idx_type - "i"/"f"/"s"/"u"/"dt"/"p"/"td". If idx_type is not None, `idx_nlevels` must be 1. "i"/"f" creates an integer/float index, "s"/"u" creates a string/unicode index "dt" create a datetime index. "td" create a datetime index. if unspecified, string labels will be generated. NrYFT)r resurTrtdcsg|]}t|qSr>)str)rJr )prefixr>r?rKsz#makeCustomIndex..)r rer{r|rTr}rrzT"{idx_type}" is not a legal value for `idx_type`, use "i"/"f"/"s"/"u"/"dt/"p"/"td".)idx_typecss|]}|dkVqdS)rNr>)rJrr>r>r? sz"makeCustomIndex..cSs*ddl}|dd|d}dd|DS)Nrz[^\d_]_?r_cSsg|] }t|qSr>)r)rJrEr>r>r?rKsz4makeCustomIndex..keyfunc..)resubsplit)rrZ numeric_tupler>r>r?keyfuncsz makeCustomIndex..keyfuncz{prefix}_l{i}_g{j})rr j)r7)rcss|]}|dVqdS)rNr>)rJrr>r>r?rs)r)rr`rrr|r~rrIrQr?r@rVrYrZr9rrbrFextendrrrrOelementsappendrXr"r$ from_tuples)Znentriesrrrndupe_lrZidx_funcrZtuplesr rZ div_factorZcntrlabelrrrr>)rr?makeCustomIndexsh (      rc s|dks t|dkst| dks4| dkr0|dks4t| dksP| dkrL|dksPtt|d||| d} t||d||| d} dkrdd fd d t|D}t|| | | d S) a nrows, ncols - number of data rows/cols c_idx_names, idx_names - False/True/list of strings, yields No names , default names or uses the provided names for the levels of the corresponding index. You can provide a single string when c_idx_nlevels ==1. c_idx_nlevels - number of levels in columns index. > 1 will yield MultiIndex r_idx_nlevels - number of levels in rows index. > 1 will yield MultiIndex data_gen_f - a function f(row,col) which return the data value at that position, the default generator used yields values of the form "RxCy" based on position. c_ndupe_l, r_ndupe_l - list of integers, determines the number of duplicates for each label at a given level of the corresponding index. The default `None` value produces a multiplicity of 1 across all levels, i.e. a unique index. Will accept a partial list of length N < idx_nlevels, for just the first N levels. If ndupe doesn't divide nrows/ncol, the last label might have lower multiplicity. dtype - passed to the DataFrame constructor as is, in case you wish to have more control in conjunction with a custom `data_gen_f` r_idx_type, c_idx_type - "i"/"f"/"s"/"u"/"dt"/"td". If idx_type is not None, `idx_nlevels` must be 1. "i"/"f" creates an integer/float index, "s"/"u" creates a string/unicode index "dt" create a datetime index. "td" create a timedelta index. if unspecified, string labels will be generated. Examples: # 5 row, 3 columns, default names on both, single index on both axis >> makeCustomDataframe(5,3) # make the data a random int between 1 and 100 >> mkdf(5,3,data_gen_f=lambda r,c:randint(1,100)) # 2-level multiindex on rows with each label duplicated # twice on first level, default names on both axis, single # index on both axis >> a=makeCustomDataframe(5,3,r_idx_nlevels=2,r_ndupe_l=[2]) # DatetimeIndex on row, index with unicode labels on columns # no names on either axis >> a=makeCustomDataframe(5,3,c_idx_names=False,r_idx_names=False, r_idx_type="dt",c_idx_type="u") # 4-level multindex on rows with names provided, 2-level multindex # on columns with default labels and default names. >> a=makeCustomDataframe(5,3,r_idx_nlevels=4, r_idx_names=["FEE","FI","FO","FAM"], c_idx_nlevels=2) >> a=mkdf(5,3,r_idx_nlevels=2,c_idx_nlevels=4) rN)r rer{r|rTrr}rYrv)rrrrrRcSsdj||dS)NzR{rows}C{cols})Zrowscols)rF)rrgr>r>r?Jz%makeCustomDataframe..cs$g|]fddtDqS)csg|]}|qSr>r>)rJrg) data_gen_frr>r?rKLsz2makeCustomDataframe...)r)rJ)rncols)rr?rKLsz'makeCustomDataframe..)r)rrrr )nrowsr c_idx_names r_idx_names c_idx_nlevels r_idx_nlevelsr c_ndupe_l r_ndupe_lr c_idx_type r_idx_typerrrqr>)rrr?makeCustomDataframes0E  rc s|dkrtj}n tj|}ttd|d}d}t||}fdd}|||}x |jkr|d9}|||}qlWt|dt} || t} | | fS)NrYrgRQ?cs.|t|}tt|dS)N)r rrrfloor)rngZ _extra_sizeind)rrrr>r?_gen_unique_rand^sz-_create_missing_idx.._gen_unique_randg?g?) rrZ RandomStaterrminrrrtolist) rrdensity random_stateZmin_rowsZfacZ extra_sizerrrr r>)rrrr?_create_missing_idxQs   r?cCsFt|||||||| | | | | d }t||||\}}tj|j||f<|S)a[ Parameters ---------- Density : float, optional Float in (0, 1) that gives the percentage of non-missing numbers in the DataFrame. random_state : {np.random.RandomState, int}, optional Random number generator or random seed. See makeCustomDataframe for descriptions of the rest of the parameters. ) rrrrrrrrrr)rrrnanr)rrrrrrrrrrrrrrdfr rr>r>r?makeMissingCustomDataframels rcCs0t}t|j||d\}}tj|j||f<|S)N)rr)rqrrrrr)rrrr rr>r>r?makeMissingDataframesrc@seZdZddZdS) TestSubDictcOstj|f||dS)N)r__init__)selfrsrr>r>r?rszTestSubDict.__init__N)r __module__ __qualname__rr>r>r>r?rsrcstfdd}|S)a8allows 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)csNfdd} o,tdko,td}|rFd}g||S|SdS)Ncs|fS)Nr>)re)rs decoratorrr>r?decsz+optional_args..wrapper..decrYr)r`callable)rsrrZ is_decoratingre)r)rsrr?wrapperszoptional_args..wrapper)r)rrr>)rr? optional_argss  r) z timed outz Server Hangupz#HTTP Error 503: Service Unavailablez502: Proxy ErrorzHTTP Error 502: internal errorzHTTP Error 502zHTTP Error 503zHTTP Error 403zHTTP Error 400z$Temporary failure in name resolutionzName or service not knownzConnection refusedzcertificate verify)eonh6<c Cs6yt|WdQRXWn|k r,dSXdSdS)a;Try to connect to the given url. True if succeeds, False if IOError raised Parameters ---------- url : basestring The URL to try to connect to Returns ------- connectable : bool Return True if no IOError (unable to connect) or URLError (bad url) was raised NFT)r/)url error_classesr>r>r? can_connects  rzhttp://www.google.comc s8ddlmd_tfdd}|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 'http://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 IOError. 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`` supercedes ``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.util.testing import network >>> from pandas.io.common import urlopen >>> @network ... def test_network(): ... with urlopen("rabbit://bonanza.com"): ... pass Traceback ... URLError: You can specify alternative URLs:: >>> @network("http://www.yahoo.com") ... def test_something_with_yahoo(): ... raise IOError("Failure Message") >>> test_something_with_yahoo() Traceback (most recent call last): ... IOError: Failure Message If you set check_before_test, it will check the url first and not run the test on failure:: >>> @network("failing://url.blaher", check_before_test=True) ... def test_something(): ... print("I ran!") ... raise ValueError("Failure") >>> test_something() Traceback (most recent call last): ... Errors not related to networking will always be raised. r)rTc s rstsy ||Stk r}zt|dd}|s^t|dr^t|jdd}|krvdj|dyt|Wntk rt|YnXt fddDrȈdj|dt |sԂstrndj|dWdd}~XYnXdS) Nerrnoreasonz2Skipping test due to known errno and error {error})rc3s|]}|kVqdS)N)lower)rJm)e_strr>r?rw sz+network..wrapper..zBSkipping test because exception message is known and error {error}z;Skipping test due to lack of connectivity and error {error}) rrrprrrF traceback format_excr~anyr|)rsrrr)_skip_on_messagescheck_before_testrraise_on_errorr skip_errnostr)rr?r` s8      znetwork..wrapper)rLrnetworkr)rrrrrrrrr>)rrrrrrrrr?r s\ "(rc OsHtjdtddt||d}|dk r@||||WdQRXn|SdS)a Check that the specified Exception is raised and that the error message matches a given regular expression pattern. This may be a regular expression object or a string containing a regular expression suitable for use by `re.search()`. This is a port of the `assertRaisesRegexp` function from unittest in Python 2.7. .. deprecated:: 0.24.0 Use `pytest.raises` instead. Examples -------- >>> assert_raises_regex(ValueError, 'invalid literal for.*XYZ', int, 'XYZ') >>> import re >>> assert_raises_regex(ValueError, re.compile('literal'), int, 'XYZ') If an exception of a different type is raised, it bubbles up. >>> assert_raises_regex(TypeError, 'literal', int, 'XYZ') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: 'XYZ' >>> dct = dict() >>> assert_raises_regex(KeyError, 'pear', dct.__getitem__, 'apple') Traceback (most recent call last): ... AssertionError: "pear" does not match "'apple'" You can also use this in a with statement. >>> with assert_raises_regex(TypeError, r'unsupported operand type\(s\)'): ... 1 + {} >>> with assert_raises_regex(TypeError, 'banana'): ... 'apple'[0] = 'b' Traceback (most recent call last): ... AssertionError: "banana" does not match "'str' object does not support \ item assignment" ztassert_raises_regex has been deprecated and will be removed in the next release. Please use `pytest.raises` instead.rG) stacklevel) exceptionregexpN)r:warn FutureWarning_AssertRaisesContextmanager) _exceptionZ_regexpZ _callablersrmanagerr>r>r?assert_raises_regex s( rc@s2eZdZdZd ddZddZddZd d ZdS) rz7 Context manager behind `assert_raises_regex`. NcCs0||_|dk r&t|ds&t|tj}||_dS)a Initialize an _AssertRaisesContextManager instance. Parameters ---------- exception : class The expected Exception class. regexp : str, default None The regex to compare against the Exception message. Nsearch)rrrcompileDOTALLr)rrrr>r>r?r s z$_AssertRaisesContextmanager.__init__cCs|S)Nr>)rr>r>r? __enter__ sz%_AssertRaisesContextmanager.__enter__cCs8|j}|s*t|dt|}tdj|d||||S)Nrz{name} not raised.)r)rrpr~rrFexception_matches)rexc_type exc_value trace_backr&Zexp_namer>r>r?__exit__ s z$_AssertRaisesContextmanager.__exit__cCsZt||jrR|jdk rNt|}|j|sNdj|jj|d}t|}t||dSdSdS)a Check that the Exception raised matches the expected Exception and expected error message regular expression. Parameters ---------- exc_type : class The type of Exception raised. exc_value : Exception The instance of `exc_type` raised. trace_back : stack trace object The traceback object associated with `exc_value`. Returns ------- is_matched : bool Whether or not the Exception raised matches the expected Exception class and expected error message regular expression. Raises ------ AssertionError : The error message provided does not match the expected error message regular expression. Nz"{pat}" does not match "{val}")patvalTF) issubclassrrr~rrFpatternrr)rrrrrrgrr>r>r?r s    z-_AssertRaisesContextmanager.exception_matches)N)rrr__doc__rrrrr>r>r>r?r s   rr6c cs^d}tjddB}|dk r\t|s*|g}x0|D](}y|jWq0tk rVYq0Xq0Wd}t||Vg} x|D]} |rt| j|rd}|rt| jt t frddl m } m } | | dd} dj| j| j| jd }| j| jkst|qz| | jj| j| j| jfqzW|r6d j|jd }|s6t||rP| rPtd | WdQRXdS) a Context manager for running code expected to either raise a specific warning, or not raise any warnings. Verifies that the code raises the expected warning, and that it does not raise any other unexpected warnings. It is basically a wrapper around ``warnings.catch_warnings``. Parameters ---------- expected_warning : {Warning, False, None}, default Warning The type of Exception raised. ``exception.Warning`` is the base class for all warnings. To check that no warning is returned, specify ``False`` or ``None``. filter_level : str or None, default "always" Specifies whether warnings are ignored, displayed, or turned into errors. Valid values are: * "error" - turns matching warnings into exceptions * "ignore" - discard the warning * "always" - always emit a warning * "default" - print the warning the first time it is generated from each location * "module" - print the warning the first time it is generated from each module * "once" - print the warning the first time it is generated clear : str, default None If not ``None`` then remove any previously raised warnings from the ``__warningsregistry__`` to ensure that no warning messages are suppressed by this context manager. If ``None`` is specified, the ``__warningsregistry__`` keeps track of which warnings have been shown, and does not show them again. check_stacklevel : bool, default True If True, displays the line that called the function containing the warning to show were the function is called. Otherwise, the line that implements the function is displayed. raise_on_extra_warnings : bool, default True Whether extra warnings not of the type `expected_warning` should cause the test to fail. Examples -------- >>> import warnings >>> with assert_produces_warning(): ... warnings.warn(UserWarning()) ... >>> with assert_produces_warning(False): ... warnings.warn(RuntimeWarning()) ... Traceback (most recent call last): ... AssertionError: Caused unexpected warning(s): ['RuntimeWarning']. >>> with assert_produces_warning(UserWarning): ... warnings.warn(RuntimeWarning()) Traceback (most recent call last): ... AssertionError: Did not see expected warning of class 'UserWarning'. ..warn:: This is *not* thread-safe. T)recordNFr) getframeinfostackrGzwWarning not set with correct stacklevel. File where warning is raised: {actual} != {caller}. Warning message: {message})actualcallerr z/Did not see expected warning of class {name!r}.)rz#Caused unexpected warning(s): {!r}.)r:catch_warningsr__warningregistry__rrr;rcategoryrDeprecationWarninginspectrrrFrr rrrlineno)Zexpected_warningZ filter_levelrZcheck_stacklevelZraise_on_extra_warningsrrjrZ saw_warningZextra_warningsZactual_warningrrrrgr>r>r?assert_produces_warning sND        rc@s(eZdZdZddZddZddZdS) RNGContexta- Context manager to set the numpy random number generator speed. Returns to the original value upon exiting the context manager. Parameters ---------- seed : int Seed for numpy.random.seed Examples -------- with RNGContext(42): np.random.randn() cCs ||_dS)N)seed)rrr>r>r?r szRNGContext.__init__cCstj|_tj|jdS)N)rrZ get_state start_stater)rr>r>r?r s zRNGContext.__enter__cCstj|jdS)N)rrZ set_stater)rrrrr>r>r?r szRNGContext.__exit__N)rrrrrrrr>r>r>r?r srcksDddl}dddh}||kr"td|j|f|dV||dS)au Context manager to temporarily register a CSV dialect for parsing CSV. Parameters ---------- name : str The name of the dialect. kwargs : mapping The parameters for the dialect. Raises ------ ValueError : the name of the dialect conflicts with a builtin one. See Also -------- csv : Python's CSV library. rNexcelz excel-tabunixz Cannot override builtin dialect.)csvrbregister_dialectunregister_dialect)rrrZ_BUILTIN_DIALECTSr>r>r?with_csv_dialect s rccsPddlm}|dkr|j}|j}|j}||||_dV||_||dS)Nr) expressions)Zpandas.core.computationrZ _MIN_ELEMENTSZ _USE_NUMEXPRZset_use_numexpr)ZuseZ min_elementsexprZolduseZoldminr>r>r? use_numexpr s  rrGcsFdks tdk r(tks(tddlfdd}|S)aDecorator to run the same function multiple times in parallel. Parameters ---------- num_threads : int, optional The number of times the function is run in parallel. kwargs_list : list of dicts, optional The list of kwargs to update original function kwargs on different threads. Notes ----- This decorator does not pass the return value of the decorated function. Original from scikit-image: https://github.com/scikit-image/scikit-image/pull/1519 rNcs tfdd}|S)Ncsrfdd}n fdd}g}x2tD]&}||}j||d}||q.Wx|D] }|q^Wx|D] }|qtWdS)Ncstf|S)N)r)r )r kwargs_listr>r?r rz?test_parallel..wrapper..inner..csS)Nr>)r )rr>r?r r)targetrsr)rThreadrrXr)rsrZ update_kwargsthreadsr Zupdated_kwargsthread)funchas_kwargs_listr num_threads threading)rr?inner s    z-test_parallel..wrapper..inner)r)rr)rrrr)rr?r sztest_parallel..wrapper)rr`r)rrrr>)rrrrr? test_parallel s rc@s,eZdZddgZeddZeddZdS)SubclassedSeriestestattrrcCstS)N)r)rr>r>r? _constructor szSubclassedSeries._constructorcCstS)N)SubclassedDataFrame)rr>r>r?_constructor_expanddim sz'SubclassedSeries._constructor_expanddimN)rrr _metadatapropertyr r r>r>r>r?r s rc@s*eZdZdgZeddZeddZdS)r r cCstS)N)r )rr>r>r?r ' sz SubclassedDataFrame._constructorcCstS)N)r)rr>r>r?_constructor_sliced+ sz'SubclassedDataFrame._constructor_slicedN)rrrr rr rr>r>r>r?r $ s r c@s*eZdZdgZeddZeddZdS)SubclassedSparseSeriesr cCstS)N)r)rr>r>r?r 3 sz#SubclassedSparseSeries._constructorcCstS)N)SubclassedSparseDataFrame)rr>r>r?r 7 sz-SubclassedSparseSeries._constructor_expanddimN)rrrr rr r r>r>r>r?r0 s rc@s*eZdZdgZeddZeddZdS)rr cCstS)N)r)rr>r>r?r ? sz&SubclassedSparseDataFrame._constructorcCstS)N)r)rr>r>r?rC sz-SubclassedSparseDataFrame._constructor_slicedN)rrrr rr rr>r>r>r?r< s rc@seZdZeddZdS)SubclassedCategoricalcCstS)N)r)rr>r>r?r I sz"SubclassedCategorical._constructorN)rrrrr r>r>r>r?rH src#sLddlddlfdd}jd}||z dVWd||XdS)aContext manager for temporarily setting a timezone. Parameters ---------- tz : str A string representing a valid timezone. Examples -------- >>> from datetime import datetime >>> from dateutil.tz import tzlocal >>> tzlocal().tzname(datetime.now()) 'IST' >>> with set_timezone('US/Eastern'): ... tzlocal().tzname(datetime.now()) ... 'EDT' rNcsB|dkr,y jd=Wq>tk r(Yq>Xn|jd<dS)NTZ)r8KeyErrortzset)r)r7timer>r?setTZh s  zset_timezone..setTZr)r7rr8r9)rrZorig_tzr>)r7rr? set_timezoneN s  rcs"rfdd}n fdd}|S)alCreate a function for calling on an array. Parameters ---------- alternative : function The function to be called on the array with no NaNs. Only used when 'skipna_alternative' is None. skipna_alternative : function The function to be called on the original array Returns ------- skipna_wrapper : function cs |jS)N)r)r)skipna_alternativer>r?skipna_wrapper sz,_make_skipna_wrapper..skipna_wrappercs"|}t|dkrtjS|S)Nr)Zdropnar`rr)rZnona) alternativer>r?r s r>)rrrr>)rrr?_make_skipna_wrapperz s rcCstj}|||}|S)as Convert list of CSV rows to single CSV-formatted string for current OS. This method is used for creating expected value of to_csv() method. Parameters ---------- rows_list : list The list of string. Each element represents the row of csv. Returns ------- expected : string Expected output of to_csv() in current OS )r7linesepr)Z rows_listsepr&r>r>r?convert_rows_list_to_csv_str sr)N)N)N)ri)rvF)T)r>r)r)r)N)NF)rvTFTTr")Tr{)r)TTr)rvr+)r,)r))r-)N)FTNNr )TFF) TrvTFTFFTr&) TrvrvTFTFFFTFr )T)TTTF)TTTTTTFr1)TTTTTFr4)rEN)rEN)rErAN)rEN)rEN)rEN)rEN)rEN)rEN)rErRN)rErWN)rEN)rEN)rE)rE)N)N)N)NrRN)NN)NrR)N)NrR)N)rzFNN) TTrYrYNNNNNN)N) rNTTrYrYNNNNNN)rN)N)N)rGN)N)rV collectionsr contextlibrr functoolsrrU http.clienthttpr7rshutilrrrrtypingrrr:r]ZnumpyrZ numpy.randomr r Zpandas._config.localizationr r r Zpandas._libs.testingr)ZtestingrZ pandas.compatrrrZpandas.core.dtypes.commonrrrrrrrrrrrrZpandas.core.dtypes.missingrZpandasrCrrr r!r"r#r$r%r&r'Zpandas.core.algorithmsr(Zpandas.core.arraysr)r*r+r,r-r.Zpandas.io.commonr/Zpandas.io.formats.printingr0r\rcriZ_RAISE_NETWORK_ERROR_DEFAULTrResourceWarningr<r@rBrDrKrQrSrhrurrrrrr ascii_lettersdigitsrrrmapchrrrrrrrGrrcrHrrrrr~rr}rrrrrrrrrr rrrr~rr#r'r%r0r3r6r:r<r>r?r@rCrFrHrIrLrMrQrVrYrZr]r_rarbrdrerfrjrlrmrnrorprqrwrxryrrrrrrrrZ_network_error_messagesZ_network_errno_valsIOErrorclient HTTPException TimeoutErrorZ_network_error_classesrrZwith_connectivity_checkrrWarningrrrrrrr r1rr4rrrrrr>r>r>r?s     8 0       - 4 R      3   $~  , .    M 7  +" ( < 7 E                          k \  !   :O}  0     ,