B
    Wcje                 @   s  U d Z ddlZddlZddlZddl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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%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l/m1Z1 dd l2m3Z3 dd!l2m4Z4 dd"l5m6Z6 dd#l7m8Z8 dd$l9m:Z: erddl;Z;d%Z<d&Z=d'Z>d(Z?d)Z@e<e=e>e?e@fZAdaBdaCeed*  eDd+< e(dd,d-d.ZEdd/d0d1ZFee-eed2  d3d4d5ZGeeHd6d7d8ZIe&ee-eHd9d:d;ZJeeHd6d<d=ZKG d>d? d?e ZLG d@dA dAeMZNedB d/dCdDZOdsed* eeH ePeHdBdFdGdHZQG dIdJ dJe.ZReeSePf d/dKdLZTdMdN ZUdOdP ZVG dQdR dRe6ZWdSddTdUdVZXeYeHdWdXdYZZe
edZ d/d[d\Z[G d]d^ d^e6Z\eRe+d_d`daZ]ed* d/dbdcZ^d*d/dddeZ_ePd/dfdgZ`ePd/dhdiZaePd/djdkZbeSePdldmdnZce*dodpeeSef d/dqdrZddS )tz4Discover and run doctests in modules and test files.    N)contextmanager)Path)Any)Callable)Dict)	Generator)Iterable)List)Optional)Pattern)Sequence)Tuple)Type)TYPE_CHECKING)Union)outcomes)ExceptionInfo)ReprFileLocation)TerminalRepr)TerminalWriter)safe_getattr)Config)Parser)fixture)FixtureRequest)	Collector)Item)OutcomeException)skip)
fnmatch_ex)import_path)Module)approx)PytestWarningZnoneZcdiffZndiffudiffZonly_first_failurezdoctest.OutputCheckerCHECKER_CLASS)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,   r2   choicesr3   z--doctest-globappendpatz2Doctests file matching pattern, default: test*.txtdoctestglob)r1   r,   metavarr2   r3   z--doctest-ignore-import-errorszIgnore doctest ImportErrors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@   .lib/python3.7/site-packages/_pytest/doctest.pypytest_addoptionE   sP    

rB   )r'   c               C   s   d a d S )N)RUNNER_CLASSr@   r@   r@   rA   pytest_unconfigurew   s    rD   )DoctestModuleDoctestTextfile)	file_pathparentr'   c             C   sb   |j }| jdkr@|jjr^tt| t| fs^tj|| d}|S nt	|| |r^t
j|| d}|S d S )Nz.py)path)configsuffixZoptionr0   any_is_setup_py_is_main_pyrE   from_parent_is_doctestrF   )rG   rH   rJ   modtxtr@   r@   rA   pytest_collect_file}   s    

rS   )rI   r'   c             C   s&   | j dkrdS |  }d|kp$d|kS )Nzsetup.pyFs
   setuptoolss	   distutils)nameZ
read_bytes)rI   contentsr@   r@   rA   rM      s    
rM   )rJ   rI   rH   r'   c                s@    j dkr|j rdS | dp(dg}t fdd|D S )N)z.txtz.rstTr8   z	test*.txtc             3   s   | ]}t | V  qd S )N)r   ).0Zglob)rI   r@   rA   	<genexpr>   s    z_is_doctest.<locals>.<genexpr>)rK   sessionZ
isinitpath	getoptionrL   )rJ   rI   rH   globsr@   )rI   rA   rP      s    rP   c             C   s
   | j dkS )Nz__main__.py)rT   )rI   r@   r@   rA   rN      s    rN   c               @   s<   e Zd Zeeeee f  ddddZeddddZ	dS )ReprFailDoctestN)reprlocation_linesr'   c             C   s
   || _ d S )N)r\   )selfr\   r@   r@   rA   __init__   s    zReprFailDoctest.__init__)twr'   c             C   s:   x4| j D ]*\}}x|D ]}|| qW || qW d S )N)r\   line
toterminal)r]   r_   reprlocationlinesr`   r@   r@   rA   ra      s    
zReprFailDoctest.toterminal)
__name__
__module____qualname__r   r   r   r<   r^   r   ra   r@   r@   r@   rA   r[      s   r[   c                   s(   e Zd Zed dd fddZ  ZS )MultipleDoctestFailureszdoctest.DocTestFailureN)failuresr'   c                s   t    || _d S )N)superr^   rh   )r]   rh   )	__class__r@   rA   r^      s    
z MultipleDoctestFailures.__init__)rd   re   rf   r   r^   __classcell__r@   r@   )rj   rA   rg      s   rg   zdoctest.DocTestRunnerc                 s"   dd l  G  fddd j} | S )Nr   c                   sx   e Zd ZdZded ee eedd fddZd	d
eddfddZ	d	d
e
ee eejf 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   Tzdoctest.OutputChecker)checkerverboseoptionflagscontinue_on_failurer'   c                s   t  j|||d || _d S )N)rl   rm   rn   )ri   r^   ro   )r]   rl   rm   rn   ro   )rj   r@   rA   r^      s    z8_init_runner_class.<locals>.PytestDoctestRunner.__init__zdoctest.DocTestzdoctest.Example)testexamplegotr'   c                s(     |||}| jr || n|d S )N)DocTestFailurero   r6   )r]   outrp   rq   rr   failure)doctestr@   rA   report_failure   s    z>_init_runner_class.<locals>.PytestDoctestRunner.report_failure)rp   rq   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UnexpectedExceptionro   r6   )r]   rt   rp   rq   rx   ru   )rv   r@   rA   report_unexpected_exception   s    
zK_init_runner_class.<locals>.PytestDoctestRunner.report_unexpected_exception)NNr   T)rd   re   rf   __doc__r
   boolintr^   r<   rw   r   r   BaseExceptiontypesTracebackTyper~   rk   r@   )rv   )rj   rA   PytestDoctestRunner   s      
r   )rv   ZDebugRunner)r   r@   )rv   rA   _init_runner_class   s    /r   T)rl   rm   rn   ro   r'   c             C   s   t d krt a t | |||dS )N)rl   rm   rn   ro   )rC   r   )rl   rm   rn   ro   r@   r@   rA   _get_runner   s    r   c                   s   e Zd Zdeded ed dd fddZededdd fd	d
ZddddZddddZ	ddddZ
ee eeef d fddZeedef ee ef dddZ  ZS )DoctestItemNz%Union[DoctestTextfile, DoctestModule]zdoctest.DocTestRunnerzdoctest.DocTest)rT   rH   runnerdtestr'   c                s*   t  || || _|| _d | _d | _d S )N)ri   r^   r   r   objfixture_request)r]   rT   rH   r   r   )rj   r@   rA   r^      s
    zDoctestItem.__init__)rH   rT   r   r   c               s   t  j||||dS )zThe public named constructor.)rT   rH   r   r   )ri   rO   )clsrH   rT   r   r   )rj   r@   rA   rO   
  s    zDoctestItem.from_parent)r'   c             C   sZ   | j d k	rVt| | _t| jjd}x$| jd D ]\}}|||< q4W | j j| d S )N)Z
getfixturedoctest_namespace)r   _setup_fixturesr   dictZgetfixturevalueitemsrZ   update)r]   rZ   rT   valuer@   r@   rA   setup  s    

zDoctestItem.setupc             C   sT   | j d k	st| jd k	stt| j  |   g }| jj| j |d |rPt|d S )N)rt   )r   AssertionErrorr   _check_all_skipped$_disable_output_capturing_for_darwinrunrg   )r]   rh   r@   r@   rA   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).ZDarwinNZcapturemanagerT)Zin_)platformsystemrJ   pluginmanagerZ	getpluginZsuspend_global_captureZread_global_capturesysstdoutwritestderr)r]   Zcapmanrt   errr@   r@   rA   r   -  s    z0DoctestItem._disable_output_capturing_for_darwin)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 }x|D ]z}|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  }n:dg}d	}x.|j D ] }|d
| d|  d}qDW t||jr||||j|d7 }n:t|j }|dt!|j g7 }|dd t"j#|j  D 7 }||
|f q^W t$|S )Nr   ry   r4   Fc                s&   g | ]\}}d | j  d |f qS )z%03d %sry   )lineno)rV   ix)rp   r@   rA   
<listcomp>`  s    z,DoctestItem.repr_failure.<locals>.<listcomp>	   z?EXAMPLE LOCATION UNKNOWN, not showing all tests of that examplez>>>z???  z...
zUNEXPECTED EXCEPTION: %sc             S   s   g | ]}| d qS )r   )strip)rV   r   r@   r@   rA   r   t  s    )%rv   rz   r   rs   r}   rg   rh   ri   repr_failurerq   rp   filenamer   r+   rd   r   _get_checker_get_report_choicerJ   rY   Z	docstringr   
splitlines	enumeratemaxsourcer6   Zoutput_differencerr   splitr   Zfrom_exc_inforx   repr	tracebackformat_exceptionr[   )r]   r   rv   rh   r\   ru   rq   r   r   messagerb   rl   Zreport_choicerc   indentr`   Zinner_excinfo)rj   )rp   rA   r   9  sT    



 

zDoctestItem.repr_failurezos.PathLike[str]c             C   s$   | j d k	st| j| j jd| j fS )Nz[doctest] %s)r   r   rI   r   rT   )r]   r@   r@   rA   
reportinfoy  s    zDoctestItem.reportinfo)NN)rd   re   rf   r<   r
   r^   classmethodrO   r   r   r   r   r   r   r   r   r   r   r   rk   r@   r@   )rj   rA   r      s    
=r   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)rv   r   r   r   r   r*   r   r   _get_allow_unicode_flag_get_allow_bytes_flag_get_number_flag)rv   r@   r@   rA   _get_flag_lookup~  s    r   c             C   s4   | j d}t }d}x|D ]}||| O }qW |S )Nr(   r   )rJ   getinir   )rH   Zoptionflags_strZflag_lookup_tableZflag_accflagr@   r@   rA   get_optionflags  s    
r   c             C   s    |  d}|r|  drd}|S )Nr;   ZusepdbF)getvalue)rJ   ro   r@   r@   rA   _get_continue_on_failure  s
    

r   c               @   s"   e Zd ZdZee dddZdS )rF   N)r'   c             c   s   dd l }| jd}| j|}t| j}| jj}ddi}t| }td|t	 t
| jd}| }	|	||||d}
|
jrtj| |
j||
dV  d S )Nr   r-   rd   __main__F)rm   rn   rl   ro   )rT   r   r   )rv   rJ   r   rI   Z	read_textr<   rT   r   r   r   r   ZDocTestParserZget_doctestexamplesr   rO   )r]   rv   encodingtextr   rT   rZ   rn   r   r&   rp   r@   r@   rA   r.     s"    
zDoctestTextfile.collect)rd   re   rf   r   r   r   r.   r@   r@   r@   rA   rF     s   rF   zdoctest.DocTest)rp   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)ZoptionsgetZSKIP)rV   r   )rv   r@   rA   rW     s    z%_check_all_skipped.<locals>.<genexpr>z!all tests skipped by +SKIP option)rv   allr   r   )rp   Zall_skippedr@   )rv   rA   r     s    r   )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_existN)r   )r   r@   r@   rA   
_is_mocked  s    
r   )NNNc              #   sV   t j ddtdtf tttgtf  td fdd} | t _z
dV  W d 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)stop.)funcr   r'   c         
      st   y6|d ks|t krt dS |  fdddS  tk
rn } ztd|f t  W d d }~X Y nX d S )N)r   c                s   t | p S )N)r   )r   )_stopr   r@   rA   <lambda>      zF_patch_unwrap_mock_aware.<locals>._mock_aware_unwrap.<locals>.<lambda>zGot %r when unwrapping %r.  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)real_unwrap)r   r   rA   _mock_aware_unwrap  s    z4_patch_unwrap_mock_aware.<locals>._mock_aware_unwrap)inspectunwrapr   r   r
   )r   r@   )r   rA   _patch_unwrap_mock_aware  s     
r   c               @   s   e Zd Zee dddZdS )rE   )r'   c             c   s   dd l }G dd d|j}| jjdkrJ| jjj| j| jd| jjd}nTy t	| j| jj| jdd}W n2 t
k
r   | jdrtd	| j  n Y nX | }t| }td
|t t| jd}x2|||jD ] }|jrtj| |j||dV  qW d S )Nr   c                   s2   e Zd ZdZ fddZdd fddZ  ZS )z5DoctestModule.collect.<locals>.MockAwareDocTestFinderzA hackish doctest finder that overrides stdlib internals to fix a stdlib bug.

            https://github.com/pytest-dev/pytest/issues/3456
            https://bugs.python.org/issue25532
            c                s8   t |trt|d|}t|dr*t|}t ||S )a3  Doctest code does not take into account `@property`, this
                is a hackish way to fix it. https://bugs.python.org/issue17446

                Wrapped Doctests will need to be unwrapped so the correct
                line number is returned. This will be reported upstream. #8796
                fget__wrapped__)rz   propertygetattrhasattrr   r   ri   _find_lineno)r]   r   source_lines)rj   r@   rA   r     s    


zBDoctestModule.collect.<locals>.MockAwareDocTestFinder._find_linenoN)r'   c          
      s:   t |rd S t  t ||||||| W d Q R X d S )N)r   r   ri   _find)r]   Ztestsr   rT   moduler   rZ   seen)rj   r@   rA   r     s
    z;DoctestModule.collect.<locals>.MockAwareDocTestFinder._find)rd   re   rf   r   r   r   rk   r@   r@   )rj   rA   MockAwareDocTestFinder  s   r   zconftest.pyZ
importmode)rootpath)rootmoder:   zunable to import module %rF)rm   rn   rl   ro   )rT   r   r   )rv   ZDocTestFinderrI   rT   rJ   r   Z_importconftestrY   r   r    ImportErrorr   r   r   r   r   r   findrd   r   r   rO   )r]   rv   r   r   finderrn   r   rp   r@   r@   rA   r.     s6    '
zDoctestModule.collectN)rd   re   rf   r   r   r.   r@   r@   r@   rA   rE     s   rE   )doctest_itemr'   c             C   sH   dddd}i | _ | jj}|j| |ddd| _t| dd}|  |S )	zEUsed by DoctestTextfile and DoctestItem to setup fixture information.N)r'   c               S   s   d S )Nr@   r@   r@   r@   rA   r   B  s    z_setup_fixtures.<locals>.funcF)Znoder   r   funcargsT)Z	_ispytest)r   rX   Z_fixturemanagerZgetfixtureinfoZ_fixtureinfor   Z_fillfixtures)r   r   Zfmr   r@   r@   rA   r   ?  s    r   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e	e	e
ed fddZe	e	e	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+)
              )
            )
            )wantrr   rn   r'   c                s   t  |||rdS |t @ }|t @ }|t @ }|sB|sB|sBdS tt ttdfdd}|rx|| j|}|| j|}|r|| j|}|| j|}|r| 	||}t  |||S )NTF)regexrR   r'   c                s     | d|S )Nz\1\2)sub)r   rR   )rer@   rA   remove_prefixes|  s    zX_init_checker_class.<locals>.LiteralsOutputChecker.check_output.<locals>.remove_prefixes)
ri   check_outputr   r   r   r   r<   _unicode_literal_re_bytes_literal_re_remove_unwanted_precision)r]   r   rr   rn   Zallow_unicodeZallow_bytesZallow_numberr   )rj   r   r@   rA   r   q  s"    


z?_init_checker_class.<locals>.LiteralsOutputChecker.check_output)r   rr   r'   c             S   s  t | j|}t | j|}t|t|kr4|S d}xt||D ]\}}|d}|d}	|	d krr|d}	|d kr~dnt|}
|	d k	r|
t|	8 }
t| tt| d|
  dkrD|d |	 |  |  ||
 | d   }||
 |	  |
 |	   7 }qDW |S )Nr   fractionZ	exponent1Z	exponent2
   )abs)list
_number_refinditerlenzipr?   r   floatr"   startend)r]   r   rr   ZwantsZgotsoffsetwgr   ZexponentZ	precisionr@   r@   rA   r     s"    


&0(zM_init_checker_class.<locals>.LiteralsOutputChecker._remove_unwanted_precision)rd   re   rf   compileUNICODEr   r   VERBOSEr  r<   r   r   r   r   rk   r@   )r   )rj   rA   LiteralsOutputCheckerS  s   r  )rv   r   ZOutputChecker)rv   r  r@   )r   rA   _init_checker_classO  s    Qr  c               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@   rA   r     s    r   c              C   s   ddl } | dS )z+Register and return the ALLOW_UNICODE flag.r   Nr   )rv   register_optionflag)rv   r@   r@   rA   r     s    r   c              C   s   ddl } | dS )z)Register and return the ALLOW_BYTES flag.r   Nr   )rv   r  )rv   r@   r@   rA   r     s    r   c              C   s   ddl } | dS )z$Register and return the NUMBER flag.r   Nr   )rv   r  )rv   r@   r@   rA   r     s    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)
rv   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)r  rv   r@   r@   rA   r     s    r   rX   )Zscopec               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@   rA   r     s    r   )NNr   T)er   r{   r   osr   r   r   r   r   
contextlibr   Zpathlibr   typingr   r   r   r   r   r	   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   r    Z_pytest.pythonr!   Z_pytest.python_apir"   Z_pytest.warning_typesr#   rv   r  r  r  r  r  r>   rC   r%   __annotations__rB   rD   rS   r   rM   rP   rN   r[   r   rg   r   r   r   r   r<   r   r   r   rF   r   objectr   r   rE   r   r  r   r   r   r   r   r   r@   r@   r@   rA   <module>   s   26    	

	NX