U
    42if                     @  s  U d 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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 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 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/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 erddl7Z7ddl8m9Z9 d Z:d!Z;d"Z<d#Z=d$Z>e:e;e<e=e>fZ?da@daAd%eBd&< d'd(d)d*d+ZCd(d,d-d.ZDd/d0d1d2d3d4ZEd/d5d6d7d8ZFd9d/d0d5d:d;d<ZGd/d5d6d=d>ZHG d?d@ d@eZIG dAdB dBeJZKdCd,dDdEZLd|dGdHdId5dJdKdLdMZMG dNdO dOe+ZNdPd,dQdRZOd9dIdSdTdUZPd9d5dSdVdWZQG dXdY dYe2ZRdZd(d[d\d]ZSd^d5d_d`daZTedbd,dcddZUG dedf dfe2ZVdgd,dhdiZWdjd,dkdlZXdId,dmdnZYdId,dodpZZdId,dqdrZ[dsdIdtdudvZ\e'dwdxdyd,dzd{Z]dS )}z4Discover and run doctests in modules and test files.    )annotationsN)contextmanager)Path)Any)Callable)	Generator)Iterable)Pattern)Sequence)TYPE_CHECKING)outcomes)ExceptionInfo)ReprFileLocation)TerminalRepr)TerminalWritersafe_getattr)Config)Parser)fixture)
TopRequest)	Collector)Item)OutcomeException)skip
fnmatch_ex)Module)approx)PytestWarning)SelfnoneZcdiffZndiffudiffZonly_first_failurez"type[doctest.OutputChecker] | NoneCHECKER_CLASSr   None)parserreturnc                 C  s   | j ddddgd | j dddd	 | d
}|jdddddd |jdtjddtdd |jddg dddd |jdddddd |jdddd d!d d S )"Ndoctest_optionflagszOption flags for doctestsargsELLIPSIS)typedefaultdoctest_encodingzEncoding used for doctest fileszutf-8)r+   collectz--doctest-modules
store_trueFzRun doctests in all .py modulesdoctestmodules)actionr+   helpdestz--doctest-reportr"   z9Choose another output format for diffs on doctest failuredoctestreport)r*   r+   r1   choicesr2   z--doctest-globappendpatz2Doctests file matching pattern, default: test*.txtdoctestglob)r0   r+   metavarr1   r2   z--doctest-ignore-import-errorsz Ignore doctest collection errorsdoctest_ignore_import_errorsz--doctest-continue-on-failurez<For a given doctest, continue to run after the first failuredoctest_continue_on_failure)ZaddiniZgetgroupZ	addoptionstrlowerDOCTEST_REPORT_CHOICES)r%   group r?   3/tmp/pip-unpacked-wheel-7n2p7kht/_pytest/doctest.pypytest_addoptionF   sb      
rA   r&   c                   C  s   d a d S N)RUNNER_CLASSr?   r?   r?   r@   pytest_unconfigurex   s    rE   r   r   z&DoctestModule | DoctestTextfile | None)	file_pathparentr&   c                 C  sZ   |j }| jdkr<|jjrVtt| t| fsVtj|| dS nt	|| |rVt
j|| dS d S )Nz.pypath)configsuffixoptionr/   any_is_setup_py_is_main_pyDoctestModulefrom_parent_is_doctestDoctestTextfile)rF   rG   rJ   r?   r?   r@   pytest_collect_file~   s    

rT   bool)rI   r&   c                 C  s&   | j dkrdS |  }d|kp$d|kS )Nzsetup.pyFs
   setuptoolss	   distutils)name
read_bytes)rI   contentsr?   r?   r@   rN      s    
rN   r   )rJ   rI   rG   r&   c                   s@    j dkr|j rdS | dp(dg}t fdd|D S )N)z.txtz.rstTr7   z	test*.txtc                 3  s   | ]}t | V  qd S rC   r   ).0globrH   r?   r@   	<genexpr>   s     z_is_doctest.<locals>.<genexpr>)rK   sessionZ
isinitpath	getoptionrM   )rJ   rI   rG   globsr?   rH   r@   rR      s    rR   c                 C  s
   | j dkS )Nz__main__.py)rV   rH   r?   r?   r@   rO      s    rO   c                   @  s,   e Zd ZdddddZddddd	Zd
S )ReprFailDoctestz0Sequence[tuple[ReprFileLocation, Sequence[str]]]r$   )reprlocation_linesr&   c                 C  s
   || _ d S rC   )r`   )selfr`   r?   r?   r@   __init__   s    zReprFailDoctest.__init__r   )twr&   c                 C  s2   | j D ]&\}}|D ]}|| q|| qd S rC   )r`   line
toterminal)ra   rc   reprlocationlinesrd   r?   r?   r@   re      s    zReprFailDoctest.toterminalN)__name__
__module____qualname__rb   re   r?   r?   r?   r@   r_      s   r_   c                      s$   e Zd Zddd fddZ  ZS )MultipleDoctestFailuresz Sequence[doctest.DocTestFailure]r$   )failuresr&   c                   s   t    || _d S rC   )superrb   rl   ra   rl   	__class__r?   r@   rb      s    
z MultipleDoctestFailures.__init__)rh   ri   rj   rb   __classcell__r?   r?   ro   r@   rk      s   rk   ztype[doctest.DocTestRunner]c                    s"   dd l  G  fddd j} | S )Nr   c                      s`   e Zd ZdZdddddd	d
 fddZdddd	dfddZdddd	dfddZ  ZS )z/_init_runner_class.<locals>.PytestDoctestRunnerzRunner to collect failures.

        Note that the out variable in this case is a list instead of a
        stdout-like object.
        Nr   Tdoctest.OutputChecker | Nonebool | NoneintrU   r$   checkerverboseoptionflagscontinue_on_failurer&   c                   s   t  j|||d || _d S )N)rv   rw   rx   )rm   rb   ry   )ra   rv   rw   rx   ry   ro   r?   r@   rb      s    z8_init_runner_class.<locals>.PytestDoctestRunner.__init__doctest.DocTestzdoctest.Exampler;   )testexamplegotr&   c                   s(     |||}| jr || n|d S rC   )DocTestFailurery   r5   )ra   outr{   r|   r}   failuredoctestr?   r@   report_failure   s    z>_init_runner_class.<locals>.PytestDoctestRunner.report_failurez>tuple[type[BaseException], BaseException, types.TracebackType])r{   r|   exc_infor&   c                   sX   t |d tr|d t |d tjr0td  |||}| jrP|| n|d S )N   zQuitting debugger)	
isinstancer   bdbZBdbQuitr   exitUnexpectedExceptionry   r5   )ra   r   r{   r|   r   r   r   r?   r@   report_unexpected_exception   s    
zK_init_runner_class.<locals>.PytestDoctestRunner.report_unexpected_exception)NNr   T)rh   ri   rj   __doc__rb   r   r   rq   r?   r   ro   r@   PytestDoctestRunner   s       
r   )r   ZDebugRunner)r   r?   r   r@   _init_runner_class   s    /r   Trr   rs   rt   doctest.DocTestRunnerru   c                 C  s   t d krt a t | |||dS )Nrv   rw   rx   ry   )rD   r   r   r?   r?   r@   _get_runner   s    r   c                      s   e Zd Zdddddd fddZeddddd	d
 fddZddddZddddZddddZddddZ	ddd fddZ
ddddZ  ZS )DoctestItemr;   zDoctestTextfile | DoctestModuler   rz   r$   )rV   rG   runnerdtestr&   c                   sR   t  || || _|| _d | _| jj}|j| d d d}|| _|j	| _
|   d S )N)nodefunccls)rm   rb   r   r   objr\   _fixturemanagerZgetfixtureinfoZ_fixtureinfoZnames_closureZfixturenames_initrequest)ra   rV   rG   r   r   ZfmZfixtureinforo   r?   r@   rb      s    zDoctestItem.__init__r    )rG   rV   r   r   r&   c                  s   t  j||||dS )zThe public named constructor.)rV   rG   r   r   )rm   rQ   )r   rG   rV   r   r   ro   r?   r@   rQ     s    zDoctestItem.from_parentrB   c                 C  s   i | _ t| dd| _d S )NT)Z	_ispytest)Zfuncargsr   _requestra   r?   r?   r@   r     s    zDoctestItem._initrequestc                 C  sL   | j   t| j jd}| j d D ]\}}|||< q(| jj| d S )N)Z
getfixturedoctest_namespace)r   Z_fillfixturesdictZgetfixturevalueitemsr   r^   update)ra   r^   rV   valuer?   r?   r@   setup   s
    

zDoctestItem.setupc                 C  s8   t | j |   g }| jj| j|d |r4t|d S )N)r   )_check_all_skippedr   $_disable_output_capturing_for_darwinr   runrk   rn   r?   r?   r@   runtest'  s    
zDoctestItem.runtestc                 C  sV   t  dkrdS | jjd}|rR|jdd | \}}tj	| tj
	| dS )zFDisable output capturing. Otherwise, stdout is lost to doctest (#985).DarwinNZcapturemanagerT)Zin_)platformsystemrJ   ZpluginmanagerZ	getpluginZsuspend_global_captureZread_global_capturesysstdoutwritestderr)ra   Zcapmanr   errr?   r?   r@   r   1  s    z0DoctestItem._disable_output_capturing_for_darwinzExceptionInfo[BaseException]zstr | TerminalRepr)excinfor&   c                   s  dd l }d }t|j|j|jfr*|jg}nt|jtr>|jj}|d krRt |S g }|D ]t}|j	}|j
  j} jd krd }n j|j d }t|j}	t|||	}
t }t| jd}|d k	r*|j
jd k	st|j
jd} jd k	st fddt|D }|t|jd d|jd  }n6dg}d	}|j D ] }|d
| d|  d}q>t||jr||||j|d7 }n8t|j }|d|jg7 }|dd t!j"|j  D 7 }||
|f qZt#|S )Nr   r   r3   Fc                   s&   g | ]\}}d | j  d |f qS )z%03d %sr   )lineno)rY   ixr{   r?   r@   
<listcomp>c  s    z,DoctestItem.repr_failure.<locals>.<listcomp>	   z?EXAMPLE LOCATION UNKNOWN, not showing all tests of that examplez>>>z???  z...
zUNEXPECTED EXCEPTION: c                 S  s   g | ]}| d qS )r   )striprY   r   r?   r?   r@   r   w  s    )$r   r   r   r~   r   rk   rl   rm   repr_failurer|   r{   filenamer   r*   rh   r   _get_checker_get_report_choicerJ   r]   Z	docstringAssertionError
splitlines	enumeratemaxsourcer5   Zoutput_differencer}   splitr   Zfrom_exc_infor   	tracebackformat_exceptionr_   )ra   r   r   rl   r`   r   r|   r   r   messagerf   rv   Zreport_choicerg   indentrd   Zinner_excinforo   r   r@   r   =  sj     






   
zDoctestItem.repr_failurez.tuple[os.PathLike[str] | str, int | None, str]c                 C  s   | j | jjd| j fS )Nz
[doctest] )rI   r   r   rV   r   r?   r?   r@   
reportinfo}  s    zDoctestItem.reportinfo)rh   ri   rj   rb   classmethodrQ   r   r   r   r   r   r   rq   r?   r?   ro   r@   r      s   
@r   zdict[str, int]c                  C  s4   dd l } t| j| j| j| j| j| jt t	 t
 d	S )Nr   )	DONT_ACCEPT_TRUE_FOR_1DONT_ACCEPT_BLANKLINENORMALIZE_WHITESPACEr)   IGNORE_EXCEPTION_DETAILCOMPARISON_FLAGSALLOW_UNICODEALLOW_BYTESNUMBER)r   r   r   r   r   r)   r   r   _get_allow_unicode_flag_get_allow_bytes_flag_get_number_flagr   r?   r?   r@   _get_flag_lookup  s    r   )rJ   r&   c                 C  s.   |  d}t }d}|D ]}||| O }q|S )Nr'   r   )getinir   )rJ   Zoptionflags_strZflag_lookup_tableZflag_accflagr?   r?   r@   get_optionflags  s    
r   c                 C  s    |  d}|r|  drd}|S )Nr:   ZusepdbF)getvalue)rJ   ry   r?   r?   r@   _get_continue_on_failure  s
    

r   c                   @  s   e Zd ZdZddddZdS )rS   NIterable[DoctestItem]rB   c                 c  s   dd l }| jd}| j|}t| j}| jj}ddi}t| j}td|t	 t
| jd}| }	|	||||d}
|
jrtj| |
j||
dV  d S )Nr   r,   rh   __main__Frw   rx   rv   ry   rV   r   r   )r   rJ   r   rI   	read_textr;   rV   r   r   r   r   ZDocTestParserZget_doctestexamplesr   rQ   )ra   r   encodingtextr   rV   r^   rx   r   r%   r{   r?   r?   r@   r-     s,    

   zDoctestTextfile.collect)rh   ri   rj   r   r-   r?   r?   r?   r@   rS     s   rS   rz   )r{   r&   c                   s0   ddl  t fdd| jD }|r,td dS )zVRaise pytest.skip() if all examples in the given DocTest have the SKIP
    option set.r   Nc                 3  s   | ]}|j  jd V  qdS )FN)optionsgetZSKIPr   r   r?   r@   r[     s     z%_check_all_skipped.<locals>.<genexpr>z!all tests skipped by +SKIP option)r   allr   r   )r{   Zall_skippedr?   r   r@   r     s    r   object)r   r&   c                 C  s   t | dddk	S )zmReturn if an object is possibly a mock object by checking the
    existence of a highly improbable attribute.Z1pytest_mock_example_attribute_that_shouldnt_existNr   r   r?   r?   r@   
_is_mocked  s    
r   zGenerator[None]c                  #  s@   t j dddddd fdd} | t _z
dV  W 5  t _X dS )	zContext manager which replaces ``inspect.unwrap`` with a version
    that's aware of mock objects and doesn't recurse into them.NstopzCallable[..., Any]zCallable[[Any], Any] | Noner   )r   r   r&   c             
     s~   z:|d ks|t kr t dW S |  fdddW S  tk
rx } z td|ddt  W 5 d }~X Y nX d S )Nr   c                   s   t | p S rC   )r   r   _stopr   r?   r@   <lambda>      zF_patch_unwrap_mock_aware.<locals>._mock_aware_unwrap.<locals>.<lambda>zGot z when unwrapping z.  This is usually caused by a violation of Python's object protocol; see e.g. https://github.com/pytest-dev/pytest/issues/5080)r   	Exceptionwarningswarnr   )r   r   eZreal_unwrapr   r@   _mock_aware_unwrap  s    z4_patch_unwrap_mock_aware.<locals>._mock_aware_unwrap)inspectunwrap)r   r?   r   r@   _patch_unwrap_mock_aware  s    
r   c                   @  s   e Zd ZddddZdS )rP   r   rB   c                 c  s   dd l }G dd d|j}z
| j}W n6 tjk
rZ   | jdrTtd| j n Y nX | j	j
|  | }t| j}td|t t| jd}|||jD ] }|jrtj| |j||dV  qd S )	Nr   c                      s   e Zd Zejdd Zedk pDedkr2ejjdk pDedkoDejjdk ZerV fddZejd	k rrd
d fddZ	ejdk r fddZ
  ZS )z5DoctestModule.collect.<locals>.MockAwareDocTestFinderN   )      r   )r      r   c                   s8   t |trt|d|}t|dr*t|}t ||S )a%  On older Pythons, doctest code does not take into account
                    `@property`. https://github.com/python/cpython/issues/61648

                    Moreover, wrapped Doctests need to be unwrapped so the correct
                    line number is returned. #8796
                    fget__wrapped__)r   propertygetattrhasattrr   r   rm   _find_lineno)ra   r   source_linesro   r?   r@   r     s    


zBDoctestModule.collect.<locals>.MockAwareDocTestFinder._find_lineno)r   
   r$   rB   c              
     s:   t |rdS t  t ||||||| W 5 Q R X dS )zOverride _find to work around issue in stdlib.

                    https://github.com/pytest-dev/pytest/issues/3456
                    https://github.com/python/cpython/issues/69718
                    N)r   r   rm   _find)ra   testsr   rV   moduler  r^   seenro   r?   r@   r    s          z;DoctestModule.collect.<locals>.MockAwareDocTestFinder._find)r      c                   s    t |tjr|j}t ||S )a>  `cached_property` objects are never considered a part
                    of the 'current module'. As such they are skipped by doctest.
                    Here we override `_from_module` to check the underlying
                    function instead. https://github.com/python/cpython/issues/107995
                    )r   	functoolscached_propertyr   rm   _from_module)ra   r  r   ro   r?   r@   r
  )  s    zBDoctestModule.collect.<locals>.MockAwareDocTestFinder._from_module)rh   ri   rj   r   version_infoZpy_ver_info_minormicroZis_find_lineno_brokenr   r  r
  rq   r?   r?   ro   r@   MockAwareDocTestFinder  s   

r  r9   zunable to import module Fr   r   )r   ZDocTestFinderr   r   ZCollectErrorrJ   r   r   rI   r\   r   Zparsefactoriesr   r   r   r   findrh   r   r   rQ   rV   )ra   r   r  r  finderrx   r   r{   r?   r?   r@   r-     s2    =

   zDoctestModule.collectN)rh   ri   rj   r-   r?   r?   r?   r@   rP     s   rP   ztype[doctest.OutputChecker]c                    s*   dd l } dd l G  fddd| j}|S )Nr   c                      sf   e Zd ZdjZdjZdjZddddd fdd	Z	dddd
ddZ
  ZS )z2_init_checker_class.<locals>.LiteralsOutputCheckerz(\W|^)[uU]([rR]?[\'\"])z(\W|^)[bB]([rR]?[\'\"])a  
            (?P<number>
              (?P<mantissa>
                (?P<integer1> [+-]?\d*)\.(?P<fraction>\d+)
                |
                (?P<integer2> [+-]?\d+)\.
              )
              (?:
                [Ee]
                (?P<exponent1> [+-]?\d+)
              )?
              |
              (?P<integer3> [+-]?\d+)
              (?:
                [Ee]
                (?P<exponent2> [+-]?\d+)
              )
            )
            r;   rt   rU   )wantr}   rx   r&   c                   s   t  |||rdS |t @ }|t @ }|t @ }|sB|sB|sBdS ddddfdd}|rt|| j|}|| j|}|r|| j|}|| j|}|r| ||}t  |||S )NTFzPattern[str]r;   )regextxtr&   c                   s     | d|S )Nz\1\2)sub)r  r  rer?   r@   remove_prefixes  s    zX_init_checker_class.<locals>.LiteralsOutputChecker.check_output.<locals>.remove_prefixes)rm   check_outputr   r   r   _unicode_literal_re_bytes_literal_re_remove_unwanted_precision)ra   r  r}   rx   Zallow_unicodeZallow_bytesZallow_numberr  )rp   r  r?   r@   r  t  s"    


z?_init_checker_class.<locals>.LiteralsOutputChecker.check_output)r  r}   r&   c                 S  s  t | j|}t | j|}t|t|kr4|S d}t||D ]\}}|d}|d}	|	d krp|d}	|d kr|dnt|}
|	d k	r|
t|	8 }
t| tt| d|
  dkrB|d |	 |  |  ||
 | d   }||
 |	  |
 |	   7 }qB|S )Nr   fractionZ	exponent1Z	exponent2r  )abs)list
_number_refinditerlenzipr>   rt   floatr   startend)ra   r  r}   Zwantsgotsoffsetwgr  exponentZ	precisionr?   r?   r@   r    s$    


&.&zM_init_checker_class.<locals>.LiteralsOutputChecker._remove_unwanted_precision)rh   ri   rj   compileUNICODEr  r  VERBOSEr  r  r  rq   r?   r  ro   r@   LiteralsOutputCheckerV  s   r-  )r   r  ZOutputChecker)r   r-  r?   r  r@   _init_checker_classR  s    Qr.  zdoctest.OutputCheckerc                   C  s   t dkrt a t  S )a  Return a doctest.OutputChecker subclass that supports some
    additional options:

    * ALLOW_UNICODE and ALLOW_BYTES options to ignore u'' and b''
      prefixes (respectively) in string literals. Useful when the same
      doctest should run in Python 2 and Python 3.

    * NUMBER to ignore floating-point differences smaller than the
      precision of the literal number in the doctest.

    An inner class is used to avoid importing "doctest" at the module
    level.
    N)r#   r.  r?   r?   r?   r@   r     s    r   c                  C  s   ddl } | dS )z+Register and return the ALLOW_UNICODE flag.r   Nr   r   Zregister_optionflagr   r?   r?   r@   r     s    r   c                  C  s   ddl } | dS )z)Register and return the ALLOW_BYTES flag.r   Nr   r/  r   r?   r?   r@   r     s    r   c                  C  s   ddl } | dS )z$Register and return the NUMBER flag.r   Nr   r/  r   r?   r?   r@   r     s    r   r;   )keyr&   c              
   C  s,   ddl }t|jt|jt|jt|jt	di|  S )zReturn the actual `doctest` module flag value.

    We want to do it as late as possible to avoid importing `doctest` and all
    its dependencies when parsing options, as it adds overhead and breaks tests.
    r   N)
r   DOCTEST_REPORT_CHOICE_UDIFFZREPORT_UDIFFDOCTEST_REPORT_CHOICE_CDIFFZREPORT_CDIFFDOCTEST_REPORT_CHOICE_NDIFFZREPORT_NDIFF(DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILUREZREPORT_ONLY_FIRST_FAILUREDOCTEST_REPORT_CHOICE_NONE)r0  r   r?   r?   r@   r     s         r   r\   )Zscopezdict[str, Any]c                   C  s   t  S )a  Fixture that returns a :py:class:`dict` that will be injected into the
    namespace of doctests.

    Usually this fixture is used in conjunction with another ``autouse`` fixture:

    .. code-block:: python

        @pytest.fixture(autouse=True)
        def add_np(doctest_namespace):
            doctest_namespace["np"] = numpy

    For more details: :ref:`doctest_namespace`.
    )r   r?   r?   r?   r@   r     s    r   )NNr   T)^r   
__future__r   r   
contextlibr   r  r   ospathlibr   r   r   r   typestypingr   r   r   r   r	   r
   r   r   Z_pytestr   Z_pytest._code.coder   r   r   Z_pytest._ior   Z_pytest.compatr   Z_pytest.configr   Z_pytest.config.argparsingr   Z_pytest.fixturesr   r   Z_pytest.nodesr   r   Z_pytest.outcomesr   r   Z_pytest.pathlibr   Z_pytest.pythonr   Z_pytest.python_apir   Z_pytest.warning_typesr   r   Ztyping_extensionsr    r5  r2  r3  r1  r4  r=   rD   r#   __annotations__rA   rE   rT   rN   rR   rO   r_   r   rk   r   r   r   r   r   r   rS   r   r   r   rP   r.  r   r   r   r   r   r   r?   r?   r?   r@   <module>   s   	26     	

	^X