a
    /§»a³2  ã                   @   sd  d 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 e d¡ZedƒZedƒZeed dœdd„ƒZeedœdd„Z eeeedœdd„Z!ee"eeef dœdd „Z#G d!d"„ d"ƒZ$e$ƒ Z%eG d#d$„ d$ƒƒZ&dS )%z)Monkeypatching and mocking functionality.é    N)Úcontextmanager)ÚPath)ÚAny)Ú	Generator)ÚList)ÚMutableMapping)ÚOptional)Úoverload)ÚTuple)ÚTypeVar)ÚUnion)Úfinal)Úfixture)ÚPytestWarningz^No module named (.*)$ÚKÚV©ÚMonkeyPatchNN©Úreturnc                  c   s   t ƒ } | V  |  ¡  dS )aþ  A convenient fixture for monkey-patching.

    The fixture provides these methods to modify objects, dictionaries or
    os.environ::

        monkeypatch.setattr(obj, name, value, raising=True)
        monkeypatch.delattr(obj, name, raising=True)
        monkeypatch.setitem(mapping, name, value)
        monkeypatch.delitem(obj, name, raising=True)
        monkeypatch.setenv(name, value, prepend=False)
        monkeypatch.delenv(name, raising=True)
        monkeypatch.syspath_prepend(path)
        monkeypatch.chdir(path)

    All modifications will be undone after the requesting test function or
    fixture has finished. The ``raising`` parameter determines if a KeyError
    or AttributeError will be raised if the set/deletion operation has no target.
    N)r   Úundo)Zmpatch© r   úM/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/_pytest/monkeypatch.pyÚmonkeypatch   s    r   )Únamer   c                 C   sÊ   |   d¡}| d¡}t|ƒ}|D ]¤}|d| 7 }zt||ƒ}W q  tyP   Y n0 q zt|ƒ W nV ty¶ } z>t|ƒ  ¡ d }||krŒ‚ ntd|› d|› �ƒ|‚W Y d }~n
d }~0 0 t|||ƒ}q |S )NÚ.r   éÿÿÿÿzimport error in z: )ÚsplitÚpopÚ
__import__ÚgetattrÚAttributeErrorÚImportErrorÚstrÚannotated_getattr)r   ÚpartsÚusedÚfoundÚpartÚexÚexpectedr   r   r   Úresolve6   s&    

,r+   )Úobjr   Úannr   c              
   C   sR   zt | |ƒ} W n> tyL } z&td t| ƒj||¡ƒ|‚W Y d }~n
d }~0 0 | S )Nz'{!r} object at {} has no attribute {!r})r    r!   ÚformatÚtypeÚ__name__)r,   r   r-   Úer   r   r   r$   R   s    ÿÿür$   )Úimport_pathÚraisingr   c                 C   sR   t | tƒrd| vr td| ›�ƒ‚|  dd¡\}}t|ƒ}|rJt|||d� ||fS )Nr   z)must be absolute import path string, not é   )r-   )Ú
isinstancer#   Ú	TypeErrorÚrsplitr+   r$   )r2   r3   ÚmoduleÚattrÚtargetr   r   r   Úderive_importpath^   s    r;   c                   @   s   e Zd Zedœdd„ZdS )ÚNotsetr   c                 C   s   dS )Nz<notset>r   ©Úselfr   r   r   Ú__repr__i   s    zNotset.__repr__N)r0   Ú
__module__Ú__qualname__r#   r?   r   r   r   r   r<   h   s   r<   c                   @   sX  e Zd ZdZddœdd„Zeeed dœdd„ƒƒZe	d%e
eeedd
œdd„ƒZe	d&ee
eedd
œdd„ƒZedfee
ef eee
f eedd
œdd„Zedfeee
f ee
ef eddœdd„Zeeef eeddœdd„Zd'eeef eeddœdd„Zd(e
e
ee
 ddœdd„Zd)e
eddœdd„Zddœdd „Zddœd!d"„Zddœd#d$„ZdS )*r   až  Helper to conveniently monkeypatch attributes/items/environment
    variables/syspath.

    Returned by the :fixture:`monkeypatch` fixture.

    :versionchanged:: 6.2
        Can now also be used directly as `pytest.MonkeyPatch()`, for when
        the fixture is not available. In this case, use
        :meth:`with MonkeyPatch.context() as mp: <context>` or remember to call
        :meth:`undo` explicitly.
    Nr   c                 C   s   g | _ g | _d | _d | _d S ©N)Ú_setattrÚ_setitemÚ_cwdÚ_savesyspathr=   r   r   r   Ú__init__~   s    zMonkeyPatch.__init__r   c                 c   s(   | ƒ }z|V  W |  ¡  n
|  ¡  0 dS )aŠ  Context manager that returns a new :class:`MonkeyPatch` object
        which undoes any patching done inside the ``with`` block upon exit.

        Example:

        .. code-block:: python

            import functools


            def test_partial(monkeypatch):
                with monkeypatch.context() as m:
                    m.setattr(functools, "partial", 3)

        Useful in situations where it is desired to undo some patches before the test ends,
        such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples
        of this see `#3290 <https://github.com/pytest-dev/pytest/issues/3290>`_.
        N)r   )ÚclsÚmr   r   r   Úcontext„   s    zMonkeyPatch.context.)r:   r   Úvaluer3   r   c                 C   s   d S rB   r   ©r>   r:   r   rK   r3   r   r   r   ÚsetattrŸ   s    zMonkeyPatch.setattrc                 C   s   d S rB   r   rL   r   r   r   rM   ¥   s    Tc                 C   s²   d}ddl }t|tƒr<t|tƒs(tdƒ‚|}t||ƒ\}}nt|tƒsNtdƒ‚t||tƒ}|rx|tu rxt|›d|›�ƒ‚| 	|¡r�|j
 |t¡}| j |||f¡ t|||ƒ dS )aä  Set attribute value on target, memorizing the old value.

        For convenience you can specify a string as ``target`` which
        will be interpreted as a dotted import path, with the last part
        being the attribute name. For example,
        ``monkeypatch.setattr("os.getcwd", lambda: "/")``
        would set the ``getcwd`` function of the ``os`` module.

        Raises AttributeError if the attribute does not exist, unless
        ``raising`` is set to False.
        Tr   Nzcuse setattr(target, name, value) or setattr(target, value) with target being a dotted import stringz|use setattr(target, name, value) with name being a string or setattr(target, value) with target being a dotted import stringz has no attribute )Úinspectr5   r<   r#   r6   r;   r    Únotsetr!   ÚisclassÚ__dict__ÚgetrC   ÚappendrM   )r>   r:   r   rK   r3   Ú__tracebackhide__rN   Úoldvalr   r   r   rM   «   s(    

ÿ
ÿ
)r:   r   r3   r   c                 C   s’   d}ddl }t|tƒr6t|tƒs(tdƒ‚t||ƒ\}}t||ƒsN|rŽt|ƒ‚n@t||t	ƒ}| 
|¡rr|j |t	¡}| j |||f¡ t||ƒ dS )aK  Delete attribute ``name`` from ``target``.

        If no ``name`` is specified and ``target`` is a string
        it will be interpreted as a dotted import path with the
        last part being the attribute name.

        Raises AttributeError it the attribute does not exist, unless
        ``raising`` is set to False.
        Tr   NzUuse delattr(target, name) or delattr(target) with target being a dotted import string)rN   r5   r<   r#   r6   r;   Úhasattrr!   r    rO   rP   rQ   rR   rC   rS   Údelattr)r>   r:   r   r3   rT   rN   rU   r   r   r   rW   Û   s     

ÿ


zMonkeyPatch.delattr)Údicr   rK   r   c                 C   s&   | j  ||| |t¡f¡ |||< dS )z'Set dictionary entry ``name`` to value.N)rD   rS   rR   rO   )r>   rX   r   rK   r   r   r   Úsetitem  s    zMonkeyPatch.setitem)rX   r   r3   r   c                 C   s:   ||vr|r6t |ƒ‚n | j ||| |t¡f¡ ||= dS )z�Delete ``name`` from dict.

        Raises ``KeyError`` if it doesn't exist, unless ``raising`` is set to
        False.
        N)ÚKeyErrorrD   rS   rR   rO   )r>   rX   r   r3   r   r   r   Údelitem  s
    
zMonkeyPatch.delitem)r   rK   Úprependr   c                 C   sj   t |tƒs6tjtdj||t|ƒjd�ƒdd� t|ƒ}|rV|tj	v rV|| tj	|  }|  
tj	||¡ dS )zßSet environment variable ``name`` to ``value``.

        If ``prepend`` is a character, read the current environment variable
        value and prepend the ``value`` adjoined with the ``prepend``
        character.
        zvValue of environment variable {name} type should be str, but got {value!r} (type: {type}); converted to str implicitly)r   rK   r/   é   )Ú
stacklevelN)r5   r#   ÚwarningsÚwarnr   r.   r/   r0   ÚosÚenvironrY   )r>   r   rK   r\   r   r   r   Úsetenv  s    
þÿù	zMonkeyPatch.setenv)r   r3   r   c                 C   s   t j}| j|||d� dS )z�Delete ``name`` from the environment.

        Raises ``KeyError`` if it does not exist, unless ``raising`` is set to
        False.
        )r3   N)ra   rb   r[   )r>   r   r3   rb   r   r   r   Údelenv)  s    zMonkeyPatch.delenvc                 C   sZ   ddl m} | jdu r&tjdd… | _tj dt|ƒ¡ |t|ƒƒ ddlm} |ƒ  dS )z:Prepend ``path`` to ``sys.path`` list of import locations.r   )Úfixup_namespace_packagesN)Úinvalidate_caches)	Úpkg_resourcesre   rF   ÚsysÚpathÚinsertr#   Ú	importlibrf   )r>   ri   re   rf   r   r   r   Úsyspath_prepend2  s    
	zMonkeyPatch.syspath_prependc                 C   sP   | j du rt ¡ | _ t|dƒr(| ¡  n$t|tƒrBt t|ƒ¡ n
t |¡ dS )z}Change the current working directory to the specified path.

        Path can be a string or a py.path.local object.
        NÚchdir)rE   ra   ÚgetcwdrV   rm   r5   r   r#   )r>   ri   r   r   r   rm   H  s    




zMonkeyPatch.chdirc              	   C   sØ   t | jƒD ]*\}}}|tur*t|||ƒ q
t||ƒ q
g | jdd…< t | jƒD ]:\}}}|tu r€z
||= W qˆ ty|   Y qˆ0 qN|||< qNg | jdd…< | jdur¸| jtj	dd…< d| _| j
durÔt | j
¡ d| _
dS )aD  Undo previous changes.

        This call consumes the undo stack. Calling it a second time has no
        effect unless you do more monkeypatching after the undo call.

        There is generally no need to call `undo()`, since it is
        called automatically during tear-down.

        Note that the same `monkeypatch` fixture is used across a
        single test function invocation. If `monkeypatch` is used both by
        the test function itself and one of the test fixtures,
        calling `undo()` will undo all of the changes made in
        both functions.
        N)ÚreversedrC   rO   rM   rW   rD   rZ   rF   rh   ri   rE   ra   rm   )r>   r,   r   rK   Ú
dictionaryÚkeyr   r   r   r   W  s&    



zMonkeyPatch.undo)..).)T)N)T)r0   r@   rA   Ú__doc__rG   Úclassmethodr   r   rJ   r	   r#   Úobjectr<   ÚboolrM   rO   r   rW   r   r   r   rY   r[   r   rc   rd   rl   rm   r   r   r   r   r   r   p   sR    ÿþ ÿþ	û

ú3ü

û&	r   )'rr   ra   Úrerh   r_   Ú
contextlibr   Úpathlibr   Útypingr   r   r   r   r   r	   r
   r   r   Z_pytest.compatr   Z_pytest.fixturesr   Z_pytest.warning_typesr   ÚcompileZRE_IMPORT_ERROR_NAMEr   r   r   r#   rt   r+   r$   ru   r;   r<   rO   r   r   r   r   r   Ú<module>   s<   

