
    9[g                       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
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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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 erd dl m!Z! 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d2dZ" G d d      Z#d Z$ G d de#      Z% G d de#      Z& G d d e#      Z' G d! d"e#      Z( G d# d$e(      Z)d3d4d%Z*d5d&Z+d6d'Z,d7d(Z- ed)e.*      Z/ed+d,	 	 	 	 	 d8d-       Z0e	 	 	 	 	 	 	 	 	 	 d9d.       Z0	 	 	 	 	 	 	 	 d:d/Z0ejb                  e0_1        e G d0 d1eejd                  jf                  e/                   Z4y);    )annotations)
Collection)Sized)DecimalN)Complex)TracebackType)Any)Callable)cast)ContextManager)final)Mapping)overload)Pattern)Sequence)Tuple)Type)TYPE_CHECKING)TypeVar)fail)ndarrayc                   t        |      }|j                  dd       g d}|D ]W  \  }}	}
t        |d   t        |            |d<   t        |d   t        |	            |d<   t        |d   t        |
            |d<   Y dt        |       d| dd	| d
| g|D 	
cg c]%  \  }}	}
|d|d    d|	d|d    d|
d|d    ' c}
}	}z   }|S c c}
}	}w )Nr   )IndexObtainedExpected)r   r   r         z(comparison failed. Mismatched elements: z / :zMax absolute difference: zMax relative difference: <z | )listinsertmaxlen)full_objectmessage_datanumber_of_elementsdifferent_idsmax_abs_diffmax_rel_diffmessage_list	max_sizesindexobtainedexpectedindexesexplanations                M/var/www/html/bid-api/venv/lib/python3.12/site-packages/_pytest/python_api.py_compare_approxr2   "   s'    %L<=I%1!x9Q<U4	!9Q<X7	!9Q<X7	! &2
 33}3E2FcJ\I]]^_
#L>2
#L>2 ,8	+7'GXx 1Yq\N"
#3x)A,/?&@HQyYZ|nL\C]^+7		K 		s   *C
c                  b    e Zd ZdZdZdZdddZddZddZddZ	d Z
dZdd	Zdd
Zd ZddZy)
ApproxBasezhProvide shared utilities for making approximate comparisons between
    numbers or sequences of numbers.Nd   c                `    d}|| _         || _        || _        || _        | j	                          y )NT)r.   absrelnan_ok_check_type)selfr.   r8   r7   r9   __tracebackhide__s         r1   __init__zApproxBase.__init__G   s0          c                    t         NNotImplementedErrorr;   s    r1   __repr__zApproxBase.__repr__O   s    !!r>   c                    dd| d|  gS )Nzcomparison failedz
Obtained: z
Expected:  )r;   
other_sides     r1   _repr_comparezApproxBase._repr_compareR   s#    %
 	
r>   c                J     t         fd j                  |      D              S )Nc              3  L   K   | ]  \  }}|j                  |      k(    y wr@   _approx_scalar).0axr;   s      r1   	<genexpr>z$ApproxBase.__eq__.<locals>.<genexpr>Z   s*      
4SDAqA$$Q''4Ss   !$)all_yield_comparisonsr;   actuals   ` r1   __eq__zApproxBase.__eq__Y   s(     
484K4KF4S
 
 	
r>   c                    d}t        d      )NTzVapprox() is not supported in a boolean context.
Did you mean: `assert a == approx(b)`?)AssertionError)r;   r<   s     r1   __bool__zApproxBase.__bool__^   s     e
 	
r>   c                    || k(   S r@   rF   rS   s     r1   __ne__zApproxBase.__ne__g   s    dN##r>   c                    t        |t              r-t        || j                  | j                  | j
                        S t        || j                  | j                  | j
                        S )N)r8   r7   r9   )
isinstancer   ApproxDecimalr8   r7   r9   ApproxScalar)r;   rO   s     r1   rL   zApproxBase._approx_scalarj   sF    a! dhht{{SSA488$++NNr>   c                    t         )zoYield all the pairs of numbers to be compared.

        This is used to implement the `__eq__` method.
        rA   rS   s     r1   rR   zApproxBase._yield_comparisonso   s
    
 "!r>   c                     y)z<Raise a TypeError if the expected value is not a valid type.NrF   rC   s    r1   r:   zApproxBase._check_typev   s    r>   NNF)r9   boolreturnNonerc   str)rG   r	   rc   	list[str]rc   rb   )rc   r^   rc   rd   )__name__
__module____qualname____doc____array_ufunc____array_priority__r=   rD   rH   rU   rX   __hash__rZ   rL   rR   r:   rF   r>   r1   r4   r4   ?   sJ    ( O"



 H$O
"Kr>   r4   c                     t        |t        t        f      rt        |      } | fd|D              S t	        |      r|D cg c]  }t         |       c}S   |      S c c}w )z=Recursively map a function over a sequence of arbitrary depthc              3  6   K   | ]  }t        |        y wr@   )_recursive_sequence_map)rM   xifs     r1   rP   z*_recursive_sequence_map.<locals>.<genexpr>   s     C2/26s   )r\   r    tupletype_is_sequence_likers   )ru   rO   seq_typert   s   `   r1   rs   rs      s^    !dE]#7CCCC	1	9:;2'2.;;t <s   A!c                  :     e Zd ZdZddZddZd fdZd Z xZS )	ApproxNumpyzHPerform approximate comparisons where the expected value is numpy array.c                j    t        | j                  | j                  j                               }d|dS Napprox())rs   rL   r.   tolist)r;   list_scalarss     r1   rD   zApproxNumpy.__repr__   s6    .!5!5!7
 (**r>   c                N   dd l }dd l}	 	 	 	 	 	 dd}| j                  j                  }t	        | j
                  | j                  j                               }t        |      }|J ||j                  k7  rdd| d|j                   gS | j                  j                  }|j                   }	|j                   }
g } |j                  d |D         D ]y  } |||      } |||      }||k7  st        |j                  |z
        }t        |	|      }	|dk(  r|j                  }
nt        |
|t        |      z        }
|j                  |       { |D cg c]0  }t        |      t         |||            t         |||            f2 }}t        | j                  ||||	|
      S c c}w )	Nr   c                "    | }|D ]  }||   }	 |S )z
            Helper function to get the value out of a nested list, given an n-dimensional index.
            This mimics numpy's indexing, but for raw nested python lists.
            rF   )nested_listnd_indexvalueis       r1   get_value_from_nested_listz=ApproxNumpy._repr_compare.<locals>.get_value_from_nested_list   s!     %Ea Lr>   z3Impossible to compare arrays with different shapes.zShapes:  and c              3  2   K   | ]  }t        |        y wr@   )range)rM   r   s     r1   rP   z,ApproxNumpy._repr_compare.<locals>.<genexpr>   s     (J>aq>s           )r   z	list[Any]r   ztuple[Any, ...]rc   r	   )	itertoolsmathr.   shapers   rL   r   _as_numpy_arraysizeinfproductr7   r"   appendrf   r2   )r;   rG   r   r   r   np_array_shapeapprox_side_as_seqother_side_as_arrayr&   r(   r)   r'   r,   approx_valueother_valueabs_diffr%   s                    r1   rH   zApproxNumpy._repr_compare   s   
	"
	.=
	
	 ,,4!5!5!7

 .j9"...0666E>*%0C0I0I/JK 
 "]]//yy&Y&&(J>(JKE56H%PL45H%PK{*|44{BC"<:#%#'88L#&|XK@P5P#QL$$U+ L$ '
 '	 E
./BEJK./A5IJ
 ' 	 
 MM
 	

s   5F"c                   dd l }|j                  |      s	 |j                  |      }|j                  |      s$|j
                  | j                  j
                  k7  ryt        | !  |      S # t        $ r}t	        d| d      |d }~ww xY w)Nr   zcannot compare 'z' to numpy.ndarrayF)	numpyisscalarasarray	Exception	TypeErrorr   r.   superrU   )r;   rT   npe	__class__s       r1   rU   zApproxNumpy.__eq__   s     {{6"VF+ {{6"v||t}}7J7J'Jw~f%%  V"26(:L MNTUUVs   A- -	B6BBc              #    K   dd l }|j                  |      rL|j                  | j                  j                        D ]#  }|| j                  |   j                         f % y |j                  | j                  j                        D ]4  }||   j                         | j                  |   j                         f 6 y w)Nr   )r   r   ndindexr.   r   item)r;   rT   r   r   s       r1   rR   zApproxNumpy._yield_comparisons   s      ;;vZZ 3 34dmmA.33555 5 ZZ 3 34Qinn&a(8(=(=(??? 5s   B?Cre   )rG   zndarray | list[Any]rc   rg   rh   )	rj   rk   rl   rm   rD   rH   rU   rR   __classcell__r   s   @r1   r{   r{      s    R+>
@& @r>   r{   c                  B     e Zd ZdZddZddZd	 fdZd Zd
dZ xZ	S )ApproxMappingzyPerform approximate comparisons where the expected value is a mapping
    with numeric values (the keys can be anything).c           	         d| j                   j                         D ci c]  \  }}|| j                  |       c}}dS c c}}w r}   )r.   itemsrL   )r;   kvs      r1   rD   zApproxMapping.__repr__   sH    ATATAVWAVA1d11!44AVW[[\]]Ws   Ac           	     *   dd l }| j                  j                         D ci c]  \  }}|| j                  |       }}}t	        |      }|j
                   }|j
                   }g }	t        |j                         |j                               D ]  \  \  }
}}||k7  s|j                  p|n	 t        |t        |j                  |z
              }|j                  dk(  r|j
                  }n/t        |t        |j                  |z
  |j                  z              }|	j                  |
        |	D cg c](  }t        |      t        ||         t        ||         f* }}t        | j                  |||	||      S c c}}w # t        $ r Y qw xY wc c}w )Nr   r   )r   r.   r   rL   r#   r   zipvaluesr"   r7   ZeroDivisionErrorr   rf   r2   )r;   rG   r   r   r   approx_side_as_mapr&   r(   r)   r'   
approx_keyr   r   keyr%   s                  r1   rH   zApproxMapping._repr_compare   s    37--2E2E2G
2G$!QAt""1%%2G 	 
 !!34yy7:$$&
(9(9(;8
3&Z {*((49P'*(#l.C.Ck.Q*R( (00C7+/88L+. , #%1%:%:[%H&2&;&;%<!",L $$Z0+8
2 %
$ Xs:c?+S1CC1H-IJ$ 	 

 MM
 	
I
6 - 
s   E;.A-F2-F	FFc                    	 t        |j                               t        | j                  j                               k7  ry	 t        |   |      S # t        $ r Y yw xY wNF)setkeysr.   AttributeErrorr   rU   r;   rT   r   s     r1   rU   zApproxMapping.__eq__)  sZ    	6;;=!S););)=%>> ?
 w~f%%  		s   =A 	AAc              #  v   K   | j                   j                         D ]  }||   | j                   |   f  y wr@   )r.   r   )r;   rT   r   s      r1   rR   z ApproxMapping._yield_comparisons2  s5     ##%A)T]]1--- &s   79c           
         d}| j                   j                         D ]_  \  }}t        |t        | j                               s&d}t	        |j                  ||t        j                  | j                                      y )NTz[pytest.approx() does not support nested dictionaries: key={!r} value={!r}
  full mapping={})r.   r   r\   rw   r   formatpprintpformat)r;   r<   r   r   msgs        r1   r:   zApproxMapping._check_type6  s`     ----/JC%dmm!45t

3v~~dmm7T UVV 0r>   re   )rG   zMapping[object, float]rc   rg   rh   ri   
rj   rk   rl   rm   rD   rH   rU   rR   r:   r   r   s   @r1   r   r      s$    7^.
`&.Wr>   r   c                  B     e Zd ZdZddZddZd	 fdZd Zd
dZ xZ	S )ApproxSequenceLikezRPerform approximate comparisons where the expected value is a sequence of numbers.c                     t         j                        }|t        t        fvrt        }d | fd j                  D              dS )Nr~   c              3  @   K   | ]  }j                  |        y wr@   rK   )rM   rO   r;   s     r1   rP   z.ApproxSequenceLike.__repr__.<locals>.<genexpr>E  s     !P-Q$"5"5a"8-   r   )rw   r.   rv   r    )r;   ry   s   ` r1   rD   zApproxSequenceLike.__repr__A  sB    &E4=(H!P$--!PPSSTUUr>   c           	        dd l }t        | j                        t        |      k7  r&ddt        | j                         dt        |       gS t        | j                  | j                        }t        |      }|j
                   }|j
                   }g }t        t        ||            D ]m  \  }\  }	}
|	|
k7  st        |	j                  |
z
        }t        ||      }|
dk(  r|j
                  }nt        ||t        |
      z        }|j                  |       o |D cg c](  }t        |      t        ||         t        ||         f* }}t        | j                  |||||      S c c}w )Nr   z1Impossible to compare lists with different sizes.z	Lengths: r   r   )r   r#   r.   rs   rL   r   	enumerater   r7   r"   r   rf   r2   )r;   rG   r   r   r&   r(   r)   r'   r   r   r   r   r%   s                r1   rH   z ApproxSequenceLike._repr_compareG  su   t}}Z0CC./uS_4EF 
 5T5H5H$--X !34yy.7"J//
*A*k {*|44{BC"<:#%#'88L#&|XK@P5P#QL$$Q'/
 #
" VSA'-?-B)CD" 	 

 MM
 	

s   -E%c                    	 t        |      t        | j                        k7  ry	 t        |   |      S # t        $ r Y yw xY wr   )r#   r.   r   r   rU   r   s     r1   rU   zApproxSequenceLike.__eq__p  sJ    	6{c$--00 1 w~f%%  		s   !5 	A Ac                .    t        || j                        S r@   )r   r.   rS   s     r1   rR   z%ApproxSequenceLike._yield_comparisonsx  s    64==))r>   c           
         d}t        | j                        D ]_  \  }}t        |t        | j                              s&d}t	        |j                  ||t        j                  | j                                     y )NTz]pytest.approx() does not support nested data structures: {!r} at index {}
  full sequence: {})r   r.   r\   rw   r   r   r   r   )r;   r<   r,   rO   r   s        r1   r:   zApproxSequenceLike._check_type{  s\     !$--0HE1!T$--01v

1eV^^DMM5R STT 1r>   re   )rG   zSequence[float]rc   rg   rh   ri   r   r   s   @r1   r   r   >  s"    \V'
R&*Ur>   r   c                  R    e Zd ZU dZdZded<   dZded<   ddZddZd	Z	e
d
        Zy	)r^   zLPerform approximate comparisons where the expected value is a single number.g-q=zfloat | DecimalDEFAULT_ABSOLUTE_TOLERANCEgư>DEFAULT_RELATIVE_TOLERANCEc                2   t        | j                  t              sdt        | j                  t        t        f      rDt        j                  t        | j                        xs t        | j                  t                    rt        | j                        S 	 | j                  d}t        | j                  t              r:| j                  j                  r$t        j                  | j                        s|dz  }| j                   d| S # t        $ r d}Y w xY w)u   Return a string communicating both the expected value and the
        tolerance for the comparison being made.

        For example, ``1.0 ± 1e-6``, ``(3+4j) ± 5e-6 ∠ ±180°``.
        z.1eu    ∠ ±180°z???u    ± )r\   r.   rb   r   r   r   isinfr7   rf   	toleranceimag
ValueError)r;   vetted_tolerances     r1   rD   zApproxScalar.__repr__  s     t}}d+t}}w.@Azz#dmm,O
4==$0OPt}}%%		%"&..!54=='2MM&&

4>>2 N2  --%5$677  	%$	%s   A"D DDc                    t        |      }|t         fd|j                  D              S t         j                  t
              rt        |t
              sy| j                  k(  ryt         j                  t
              s6t         j                  t        t        f      rt        |t        t        f      syt        j                  t         j                              r, j                  xr t        j                  t        |            S t        j                  t         j                              ryt         j                  |z
         j                  k  }|S )ziReturn whether the given value is equal to the expected value
        within the pre-specified tolerance.c              3  @   K   | ]  }j                  |        y wr@   )rU   )rM   rN   r;   s     r1   rP   z&ApproxScalar.__eq__.<locals>.<genexpr>  s     <|!t{{1~|r   FT)r   rQ   flatr\   r.   rb   r   r   r   isnanr7   r9   r   r   )r;   rT   r   results   `   r1   rU   zApproxScalar.__eq__  s     "&) <w||<<< dmmT*:fd3Kt}}$ dmmT*t}}w&896GW#56
 ::c$--();;:4::c&k#:: ::c$--() 4==612dnnDr>   Nc                   d } || j                   | j                        }|dk  rt        d|       t        j                  |      rt        d      | j
                  | j                   |S  || j
                  | j                        t        | j                        z  }|dk  rt        d|       t        j                  |      rt        d      t        ||      S )zReturn the tolerance for the comparison.

        This could be either an absolute tolerance or a relative tolerance,
        depending on what the user specified or which would be larger.
        c                    | | S |S r@   rF   )rO   defaults     r1   set_defaultz+ApproxScalar.tolerance.<locals>.set_default  s    1272r>   r   z&absolute tolerance can't be negative: z absolute tolerance can't be NaN.z&relative tolerance can't be negative: z relative tolerance can't be NaN.)	r7   r   r   r   r   r8   r   r.   r"   )r;   r   absolute_tolerancerelative_tolerances       r1   r   zApproxScalar.tolerance  s    	3
 )43R3RS!89K8LM  ::()?@@ 88xx#)) )HHd55
 !89K8LM  ::()?@@ %'9::r>   re   rh   )rj   rk   rl   rm   r   __annotations__r   rD   rU   rp   propertyr   rF   r>   r1   r^   r^     sA    V 3872668>*Z H,; ,;r>   r^   c                  0    e Zd ZdZ ed      Z ed      Zy)r]   zFPerform approximate comparisons where the expected value is a Decimal.z1e-12z1e-6N)rj   rk   rl   rm   r   r   r   rF   r>   r1   r]   r]   	  s    P!(!1!(r>   r]   c                N   d}t        | t              rt        }nt        | t              rt        }nkt        |       rt        |       } t        }nNt        |       rt        }n<t        | t              r&t        | t        t        f      sd| }t        |      t        } || |||      S )a   Assert that two numbers (or two ordered sequences of numbers) are equal to each other
    within some tolerance.

    Due to the :doc:`python:tutorial/floatingpoint`, numbers that we
    would intuitively expect to be equal are not always so::

        >>> 0.1 + 0.2 == 0.3
        False

    This problem is commonly encountered when writing tests, e.g. when making
    sure that floating-point values are what you expect them to be.  One way to
    deal with this problem is to assert that two floating-point numbers are
    equal to within some appropriate tolerance::

        >>> abs((0.1 + 0.2) - 0.3) < 1e-6
        True

    However, comparisons like this are tedious to write and difficult to
    understand.  Furthermore, absolute comparisons like the one above are
    usually discouraged because there's no tolerance that works well for all
    situations.  ``1e-6`` is good for numbers around ``1``, but too small for
    very big numbers and too big for very small ones.  It's better to express
    the tolerance as a fraction of the expected value, but relative comparisons
    like that are even more difficult to write correctly and concisely.

    The ``approx`` class performs floating-point comparisons using a syntax
    that's as intuitive as possible::

        >>> from pytest import approx
        >>> 0.1 + 0.2 == approx(0.3)
        True

    The same syntax also works for ordered sequences of numbers::

        >>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6))
        True

    ``numpy`` arrays::

        >>> import numpy as np                                                          # doctest: +SKIP
        >>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) # doctest: +SKIP
        True

    And for a ``numpy`` array against a scalar::

        >>> import numpy as np                                         # doctest: +SKIP
        >>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) # doctest: +SKIP
        True

    Only ordered sequences are supported, because ``approx`` needs
    to infer the relative position of the sequences without ambiguity. This means
    ``sets`` and other unordered sequences are not supported.

    Finally, dictionary *values* can also be compared::

        >>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6})
        True

    The comparison will be true if both mappings have the same keys and their
    respective values match the expected tolerances.

    **Tolerances**

    By default, ``approx`` considers numbers within a relative tolerance of
    ``1e-6`` (i.e. one part in a million) of its expected value to be equal.
    This treatment would lead to surprising results if the expected value was
    ``0.0``, because nothing but ``0.0`` itself is relatively close to ``0.0``.
    To handle this case less surprisingly, ``approx`` also considers numbers
    within an absolute tolerance of ``1e-12`` of its expected value to be
    equal.  Infinity and NaN are special cases.  Infinity is only considered
    equal to itself, regardless of the relative tolerance.  NaN is not
    considered equal to anything by default, but you can make it be equal to
    itself by setting the ``nan_ok`` argument to True.  (This is meant to
    facilitate comparing arrays that use NaN to mean "no data".)

    Both the relative and absolute tolerances can be changed by passing
    arguments to the ``approx`` constructor::

        >>> 1.0001 == approx(1)
        False
        >>> 1.0001 == approx(1, rel=1e-3)
        True
        >>> 1.0001 == approx(1, abs=1e-3)
        True

    If you specify ``abs`` but not ``rel``, the comparison will not consider
    the relative tolerance at all.  In other words, two numbers that are within
    the default relative tolerance of ``1e-6`` will still be considered unequal
    if they exceed the specified absolute tolerance.  If you specify both
    ``abs`` and ``rel``, the numbers will be considered equal if either
    tolerance is met::

        >>> 1 + 1e-8 == approx(1)
        True
        >>> 1 + 1e-8 == approx(1, abs=1e-12)
        False
        >>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12)
        True

    You can also use ``approx`` to compare nonnumeric types, or dicts and
    sequences containing nonnumeric types, in which case it falls back to
    strict equality. This can be useful for comparing dicts and sequences that
    can contain optional values::

        >>> {"required": 1.0000005, "optional": None} == approx({"required": 1, "optional": None})
        True
        >>> [None, 1.0000005] == approx([None,1])
        True
        >>> ["foo", 1.0000005] == approx([None,1])
        False

    If you're thinking about using ``approx``, then you might want to know how
    it compares to other good ways of comparing floating-point numbers.  All of
    these algorithms are based on relative and absolute tolerances and should
    agree for the most part, but they do have meaningful differences:

    - ``math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)``:  True if the relative
      tolerance is met w.r.t. either ``a`` or ``b`` or if the absolute
      tolerance is met.  Because the relative tolerance is calculated w.r.t.
      both ``a`` and ``b``, this test is symmetric (i.e.  neither ``a`` nor
      ``b`` is a "reference value").  You have to specify an absolute tolerance
      if you want to compare to ``0.0`` because there is no tolerance by
      default.  More information: :py:func:`math.isclose`.

    - ``numpy.isclose(a, b, rtol=1e-5, atol=1e-8)``: True if the difference
      between ``a`` and ``b`` is less that the sum of the relative tolerance
      w.r.t. ``b`` and the absolute tolerance.  Because the relative tolerance
      is only calculated w.r.t. ``b``, this test is asymmetric and you can
      think of ``b`` as the reference value.  Support for comparing sequences
      is provided by :py:func:`numpy.allclose`.  More information:
      :std:doc:`numpy:reference/generated/numpy.isclose`.

    - ``unittest.TestCase.assertAlmostEqual(a, b)``: True if ``a`` and ``b``
      are within an absolute tolerance of ``1e-7``.  No relative tolerance is
      considered , so this function is not appropriate for very large or very
      small numbers.  Also, it's only available in subclasses of ``unittest.TestCase``
      and it's ugly because it doesn't follow PEP8.  More information:
      :py:meth:`unittest.TestCase.assertAlmostEqual`.

    - ``a == pytest.approx(b, rel=1e-6, abs=1e-12)``: True if the relative
      tolerance is met w.r.t. ``b`` or if the absolute tolerance is met.
      Because the relative tolerance is only calculated w.r.t. ``b``, this test
      is asymmetric and you can think of ``b`` as the reference value.  In the
      special case that you explicitly specify an absolute tolerance but not a
      relative tolerance, only the absolute tolerance is considered.

    .. note::

        ``approx`` can handle numpy arrays, but we recommend the
        specialised test helpers in :std:doc:`numpy:reference/routines.testing`
        if you need support for comparisons, NaNs, or ULP-based tolerances.

        To match strings using regex, you can use
        `Matches <https://github.com/asottile/re-assert#re_assertmatchespattern-str-args-kwargs>`_
        from the
        `re_assert package <https://github.com/asottile/re-assert>`_.

    .. warning::

       .. versionchanged:: 3.2

       In order to avoid inconsistent behavior, :py:exc:`TypeError` is
       raised for ``>``, ``>=``, ``<`` and ``<=`` comparisons.
       The example below illustrates the problem::

           assert approx(0.1) > 0.1 + 1e-10  # calls approx(0.1).__gt__(0.1 + 1e-10)
           assert 0.1 + 1e-10 > approx(0.1)  # calls approx(0.1).__lt__(0.1 + 1e-10)

       In the second example one expects ``approx(0.1).__le__(0.1 + 1e-10)``
       to be called. But instead, ``approx(0.1).__lt__(0.1 + 1e-10)`` is used to
       comparison. This is because the call hierarchy of rich comparisons
       follows a fixed behavior. More information: :py:meth:`object.__ge__`

    .. versionchanged:: 3.7.1
       ``approx`` raises ``TypeError`` when it encounters a dict value or
       sequence element of nonnumeric type.

    .. versionchanged:: 6.1.0
       ``approx`` falls back to strict equality for nonnumeric types instead
       of raising ``TypeError``.
    Tz:pytest.approx() only supports ordered sequences, but got: )r\   r   r]   r   r   _is_numpy_arrayr   r{   rx   r   r   rf   bytesr   r^   )r.   r8   r7   r9   r<   clsr   s          r1   approxr     s    J (G$ -	Hg	&		""8,	8	$ 	Hj	)*XU|2TJ8,Wnxc6**r>   c                p    t        | d      xr) t        | t              xr t        | t        t        f       S )N__getitem__)hasattrr\   r   rf   r   )r.   s    r1   rx   rx     s6    -( 	3x'	38c5\22r>   c                    t        |       duS )zr
    Return true if the given object is implicitly convertible to ndarray,
    and numpy is already imported.
    N)r   )objs    r1   r   r     s    
 3t++r>   c                    ddl }|j                  j                  d      }|S|j                  |       ryt	        | |j
                        r| S t        | d      st        dd      r|j                  |       S y)z
    Return an ndarray if the given object is implicitly convertible to ndarray,
    and numpy is already imported, otherwise None.
    r   Nr   	__array__r   __array_interface__)sysmodulesgetr   r\   r   r   r   )r   r   r   s      r1   r   r     se    
 kkoog&B	~;;sRZZ(JS+&'%9N*O::c?"r>   E)bound.)matchc                    y r@   rF   )expected_exceptionr   s     r1   raisesr     s    
 r>   c                     y r@   rF   )r   funcargskwargss       r1   r   r     s     &)r>   c                   d}| st        d| d      t        | t              r| f}n| }|D ]o  }t        |t              rt        |t              r$d}t        |t              r|j
                  nt        |      j
                  }t        |j                  |             d|  }|sP|j                  dd      }	|r/d}|d	j                  t        |            z  }|d
z  }t        |      t        | ||	      S |d   }
t        |
      st        |
dt        |
       d      	  |
|dd i | t#        |       y# | $ r3}t        j                  j                  j!                  |      cY d}~S d}~ww xY w)a  Assert that a code block/function call raises an exception type, or one of its subclasses.

    :param expected_exception:
        The expected exception type, or a tuple if one of multiple possible
        exception types are expected. Note that subclasses of the passed exceptions
        will also match.

    :kwparam str | re.Pattern[str] | None match:
        If specified, a string containing a regular expression,
        or a regular expression object, that is tested against the string
        representation of the exception and its :pep:`678` `__notes__`
        using :func:`re.search`.

        To match a literal string that may contain :ref:`special characters
        <re-syntax>`, the pattern can first be escaped with :func:`re.escape`.

        (This is only used when ``pytest.raises`` is used as a context manager,
        and passed through to the function otherwise.
        When using ``pytest.raises`` as a function, you can use:
        ``pytest.raises(Exc, func, match="passed on").match("my pattern")``.)

    Use ``pytest.raises`` as a context manager, which will capture the exception of the given
    type, or any of its subclasses::

        >>> import pytest
        >>> with pytest.raises(ZeroDivisionError):
        ...    1/0

    If the code block does not raise the expected exception (:class:`ZeroDivisionError` in the example
    above), or no exception at all, the check will fail instead.

    You can also use the keyword argument ``match`` to assert that the
    exception matches a text or regex::

        >>> with pytest.raises(ValueError, match='must be 0 or None'):
        ...     raise ValueError("value must be 0 or None")

        >>> with pytest.raises(ValueError, match=r'must be \d+$'):
        ...     raise ValueError("value must be 42")

    The ``match`` argument searches the formatted exception string, which includes any
    `PEP-678 <https://peps.python.org/pep-0678/>`__ ``__notes__``:

        >>> with pytest.raises(ValueError, match=r"had a note added"):  # doctest: +SKIP
        ...     e = ValueError("value must be 42")
        ...     e.add_note("had a note added")
        ...     raise e

    The context manager produces an :class:`ExceptionInfo` object which can be used to inspect the
    details of the captured exception::

        >>> with pytest.raises(ValueError) as exc_info:
        ...     raise ValueError("value must be 42")
        >>> assert exc_info.type is ValueError
        >>> assert exc_info.value.args[0] == "value must be 42"

    .. warning::

       Given that ``pytest.raises`` matches subclasses, be wary of using it to match :class:`Exception` like this::

           with pytest.raises(Exception):  # Careful, this will catch ANY exception raised.
               some_function()

       Because :class:`Exception` is the base class of almost all exceptions, it is easy for this to hide
       real bugs, where the user wrote this expecting a specific exception, but some other exception is being
       raised due to a bug introduced during a refactoring.

       Avoid using ``pytest.raises`` to catch :class:`Exception` unless certain that you really want to catch
       **any** exception raised.

    .. note::

       When using ``pytest.raises`` as a context manager, it's worthwhile to
       note that normal context manager rules apply and that the exception
       raised *must* be the final line in the scope of the context manager.
       Lines of code after that, within the scope of the context manager will
       not be executed. For example::

           >>> value = 15
           >>> with pytest.raises(ValueError) as exc_info:
           ...     if value > 10:
           ...         raise ValueError("value must be <= 10")
           ...     assert exc_info.type is ValueError  # This will not execute.

       Instead, the following approach must be taken (note the difference in
       scope)::

           >>> with pytest.raises(ValueError) as exc_info:
           ...     if value > 10:
           ...         raise ValueError("value must be <= 10")
           ...
           >>> assert exc_info.type is ValueError

    **Using with** ``pytest.mark.parametrize``

    When using :ref:`pytest.mark.parametrize ref`
    it is possible to parametrize tests such that
    some runs raise an exception and others do not.

    See :ref:`parametrizing_conditional_raising` for an example.

    .. seealso::

        :ref:`assertraises` for more examples and detailed discussion.

    **Legacy form**

    It is possible to specify a callable by passing a to-be-called lambda::

        >>> raises(ZeroDivisionError, lambda: 1/0)
        <ExceptionInfo ...>

    or you can specify an arbitrary callable with arguments::

        >>> def f(x): return 1/x
        ...
        >>> raises(ZeroDivisionError, f, 0)
        <ExceptionInfo ...>
        >>> raises(ZeroDivisionError, f, x=0)
        <ExceptionInfo ...>

    The form above is fully supported but discouraged for new code because the
    context manager form is regarded as more readable and less error-prone.

    .. note::
        Similar to caught exception objects in Python, explicitly clearing
        local references to returned ``ExceptionInfo`` objects can
        help the Python interpreter speed up its garbage collection.

        Clearing those references breaks a reference cycle
        (``ExceptionInfo`` --> caught exception --> frame stack raising
        the exception --> current frame stack --> local variables -->
        ``ExceptionInfo``) which makes Python keep all objects referenced
        from that cycle (including all local variables in the current
        frame) alive until the next cyclic garbage collection run.
        More detailed information can be found in the official Python
        documentation for :ref:`the try statement <python:try>`.
    TzCExpected an exception type or a tuple of exception types, but got `z`. Raising exceptions is already understood as failing the test, so you don't need any special code to say 'this should never raise an exception'.z7expected exception must be a BaseException type, not {}zDID NOT RAISE r   Nz6Unexpected keyword arguments passed to pytest.raises: z, z"
Use context-manager form instead?r   z object (type: z) must be callabler   )r   r\   rw   
issubclassBaseExceptionrj   r   r   popjoinsortedRaisesContextcallable_pytest_codeExceptionInfofrom_exceptionr   )r   r   r   r<   expected_exceptionsexcr   not_amessager   r   r   s               r1   r   r   "  s   Z QRdQg hN O
 	

 $d+4F3H0"#t$JsM,JKC$.sD$9CLLtCy?Q?QECJJu-..	 # 123G+1::gt+DJC499VF^,,C88CC. /%@@Aw~thod4j\ASTUU	A$qr(%f% 	M " 	A==..==a@@	As    D7 7E/<(E*$E/*E/c                  F    e Zd Z	 d	 	 	 	 	 	 	 ddZddZ	 	 	 	 	 	 	 	 ddZy)	r  Nc                    || _         || _        || _        d | _        | j                  4d }	 t	        j
                  | j                         |t        d|        y y y # t        j                  $ r}|}Y d }~-d }~ww xY w)Nz+Invalid regex pattern provided to 'match': )r   r  
match_exprexcinforecompileerrorr   )r;   r   r  r  re_errorr   s         r1   r=   zRaisesContext.__init__  s     #5$>B??&H

4??+ #B8*MN $ ' 88 s   A A=1A88A=c                t    t         j                  j                  j                         | _        | j                  S r@   )r  r  r	  	for_laterr  rC   s    r1   	__enter__zRaisesContext.__enter__  s&    }}22<<>||r>   c                p   d}|t        | j                         | j                  J t        || j                        syt        t        t        t           t        t        f   |||f      }| j                  j                  |       | j                  %| j                  j                  | j                         y)NTF)r   r  r  r   r   r   r   r   r   r   fill_unfilledr  r   )r;   exc_typeexc_valexc_tbr<   exc_infos         r1   __exit__zRaisesContext.__exit__  s     !||'''(D$;$;<d1gq-788Wf:UV""8,??&LLt/r>   r@   )r   type[E] | tuple[type[E], ...]r  rf   r  str | Pattern[str] | Nonerc   rd   )rc   _pytest._code.ExceptionInfo[E])r  ztype[BaseException] | Noner  zBaseException | Noner  zTracebackType | Nonerc   rb   )rj   rk   rl   r=   r  r   rF   r>   r1   r  r    sg     15	O9O O .	O
 
O&, & %	
 
r>   r  )r$   objectr%   zSequence[tuple[str, str, str]]r&   intr'   zSequence[object]r(   floatr)   r&  rc   rg   ra   )r9   rb   rc   r4   )r.   r$  rc   rb   )r   r$  rc   rb   )r   r$  rc   zndarray | None)r   r!  r   r"  rc   zRaisesContext[E])
r   r!  r   zCallable[..., Any]r   r	   r   r	   rc   r#  )r   r!  r   r	   r   r	   rc   z1RaisesContext[E] | _pytest._code.ExceptionInfo[E])5
__future__r   collections.abcr   r   decimalr   r   numbersr   r   r  typesr   typingr	   r
   r   r   r   r   r   r   r   r   r   r   r   _pytest._coder  _pytest.outcomesr   r   r   r2   r4   rs   r{   r   r   r^   r]   r   rx   r   r   r  r   r   r   r  r	  r  rF   r>   r1   <module>r/     s   " & !     	     !            ! 0  $	
   :8K 8K@e@* e@PIWJ IWXBU BUJC;: C;L1L 1V+r,* C}% 
 (+5 % 	 
 
)5)
) ) 	)
 $) 
)q5q>AqMPq6qj >>  )N7==#>#>q#AB ) )r>   