
    gM7                     8   d dl Z ddlmZ ddlmZ ddlmZmZ ddlmZ ddl	m	Z	 ddlm
Z
  G d	 d
e      Z e j                  dee
f      Zd Zd Zd Z	 ddZd dZd Z	 	 d!dZ G d de      Z e       Zd dZd Zd"dZ	 	 d#dZd Zd Zd Zd Z d Z!d Z"y)$    N   )
invocation)verification)get_objget_obj_attr_tuple)Mock)mock_registry)VerificationErrorc                       e Zd Zy)ArgumentErrorN)__name__
__module____qualname__     D/var/www/openai/venv/lib/python3.12/site-packages/mockito/mockito.pyr   r       s    r   r   errisinstancec                  J    t        | D cg c]  }|s|	 c}      dkD  S c c}w )Nr   )len)argsxs     r   _multiple_arguments_in_user   )   s&    4%4a14%&**%s     c                 &    | d uxr | dk  xs | dk(  S )Nr   r   r   )values    r   _invalid_argumentr   -   s    +%!):
:r   c                 H    | 	 | \  }}||kD  s|dk  ryy# t         $ r Y yw xY w)NTr   F)	Exception)betweenstartends      r   _invalid_betweenr!   1   s?    	 JE3 3;%!)  		s    	!!c                    | | dk  rt        d| z        t        |||      rt        d      t        |      rt        d|z        t        |      rt        d|z        t        |      rt        d|      |rt	        j
                  |      S |rt	        j                  |      S |rt	        j                  | S | t	        j                  |       S y )Nr   zX'times' argument has invalid value.
It should be at least 0. You wanted to set it to: %izHYou can set only one of the arguments: 'atleast', 'atmost' or 'between'.z['atleast' argument has invalid value.
It should be at least 1.  You wanted to set it to: %izZ'atmost' argument has invalid value.
It should be at least 1.  You wanted to set it to: %iz'between' argument has invalid value.
It should consist of positive values with second number not greater
than first e.g. (1, 4) or (0, 3) or (2, 2).
You wanted to set it to: )	r   r   r   r!   r   AtLeastAtMostBetweenTimestimesatleastatmostr   s       r   _get_wanted_verificationr+   <   s   UQY "$)* + 	+ "'67;%& 	& ! %'./ 0 	0   %'-. / 	/   #*,- 	- ##G,,	""6**	##W--		!!%(( 
r   c                 |    t        j                  |       }|$t        | ||       }t        j                  | |       |S )N)strictspec)r	   mock_forr   register)objr-   theMocks      r   	_get_mockr3   ^   s:    $$S)Gs64sG,Nr   c                 P    t        j                  |       }|t        d| z        |S )Nzobj '%s' is not registered)r	   r/   r   )r1   r2   s     r   _get_mock_or_raiser5   e   s-    $$S)G83>??Nr   c                     t        | t              rt        |       } t        ||||      |rt	        j
                        t        |        G fddt              } |       S )a  Central interface to verify interactions.

    `verify` uses a fluent interface::

        verify(<obj>, times=2).<method_name>(<args>)

    `args` can be as concrete as necessary. Often a catch-all is enough,
    especially if you're working with strict mocks, bc they throw at call
    time on unwanted, unconfigured arguments::

        from mockito import ANY, ARGS, KWARGS
        when(manager).add_tasks(1, 2, 3)
        ...
        # no need to duplicate the specification; every other argument pattern
        # would have raised anyway.
        verify(manager).add_tasks(1, 2, 3)  # duplicates `when`call
        verify(manager).add_tasks(*ARGS)
        verify(manager).add_tasks(...)       # Py3
        verify(manager).add_tasks(Ellipsis)  # Py2

    r'   c                       e Zd Z fdZy)verify.<locals>.Verifyc                 2    t        j                  |      S N)r   VerifiableInvocation)selfmethod_namer2   verification_fns     r   __getattr__z"verify.<locals>.Verify.__getattr__   s    22o7 7r   Nr   r   r   r?   )r2   r>   s   r   Verifyr8      s    	7r   rA   )
isinstancestrr   r+   r   InOrderr5   object)	r1   r(   r)   r*   r   inorderrA   r2   r>   s	          @@r   verifyrG   k   s^    0 #scl.WVWFO&..? %G7 7
 8Or   c                       e Zd Zd Zy)_OMITTEDc                      y)NOMITTEDr   )r<   s    r   __repr__z_OMITTED.__repr__   s    r   N)r   r   r   rL   r   r   r   rI   rI      s    r   rI   c                     t        | t              rt        |       } t        |        G fddt              } |       S )a	  Central interface to stub functions on a given `obj`

    `obj` should be a module, a class or an instance of a class; it can be
    a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface
    where you configure a stub in three steps::

        when(<obj>).<method_name>(<args>).thenReturn(<value>)

    Compared to simple *patching*, stubbing in mockito requires you to specify
    concrete `args` for which the stub will answer with a concrete `<value>`.
    All invocations that do not match this specific call signature will be
    rejected. They usually throw at call time.

    Stubbing in mockito's sense thus means not only to get rid of unwanted
    side effects, but effectively to turn function calls into constants.

    E.g.::

        # Given ``dog`` is an instance of a ``Dog``
        when(dog).bark('Grrr').thenReturn('Wuff')
        when(dog).bark('Miau').thenRaise(TypeError())

        # With this configuration set up:
        assert dog.bark('Grrr') == 'Wuff'
        dog.bark('Miau')  # will throw TypeError
        dog.bark('Wuff')  # will throw unwanted interaction

    Stubbing can effectively be used as monkeypatching; usage shown with
    the `with` context managing::

        with when(os.path).exists('/foo').thenReturn(True):
            ...

    Most of the time verifying your interactions is not necessary, because
    your code under tests implicitly verifies the return value by evaluating
    it. See :func:`verify` if you need to, see also :func:`expect` to setup
    expected call counts up front.

    If your function is pure side effect and does not return something, you
    can omit the specific answer. The default then is `None`::

        when(manager).do_work()

    `when` verifies the method name, the expected argument signature, and the
    actual, factual arguments your code under test uses against the original
    object and its function so its easier to spot changing interfaces.

    Sometimes it's tedious to spell out all arguments::

        from mockito import ANY, ARGS, KWARGS
        when(requests).get('http://example.com/', **KWARGS).thenReturn(...)
        when(os.path).exists(ANY)
        when(os.path).exists(ANY(str))

    .. note:: You must :func:`unstub` after stubbing, or use `with`
        statement.

    Set ``strict=False`` to bypass the function signature checks.

    See related :func:`when2` which has a more pythonic interface.

    r-   c                       e Zd Z fdZy)when.<locals>.Whenc                 4    t        j                  |      S )NrN   r   StubbedInvocation)r<   r=   r-   r2   s     r   r?   zwhen.<locals>.When.__getattr__   s    //V5 5r   Nr@   )r-   r2   s   r   WhenrP      s    	5r   rT   )rB   rC   r   r3   rE   )r1   r-   rT   r2   s    ` @r   whenrU      s:    @ #sclF+G5v 5
 6Mr   c                 p    t        |       \  }}t        |d      } t        j                  ||      |i |S )a
  Stub a function call with the given arguments

    Exposes a more pythonic interface than :func:`when`. See :func:`when` for
    more documentation.

    Returns `AnswerSelector` interface which exposes `thenReturn`,
    `thenRaise`, `thenAnswer`, and `thenCallOriginalImplementation` as usual.
    Always `strict`.

    Usage::

        # Given `dog` is an instance of a `Dog`
        when2(dog.bark, 'Miau').thenReturn('Wuff')

    .. note:: You must :func:`unstub` after stubbing, or use `with`
        statement.

    TrN   )r   r3   r   rS   )fnr   kwargsr1   namer2   s         r   when2rZ      s=    & #2&ICD)G6:''6GGGr   c                     |!|}t        | t              j                  |      S | |}}t        |d      } t	        j
                  ||d      t              j                  |      S )aw  Patch/Replace a function.

    This is really like monkeypatching, but *note* that all interactions
    will be recorded and can be verified. That is, using `patch` you stay in
    the domain of mockito.

    Two ways to call this. Either::

        patch(os.path.exists, lambda str: True)  # two arguments
        # OR
        patch(os.path, 'exists', lambda str: True)  # three arguments

    If called with three arguments, the mode is *not* strict to allow *adding*
    methods. If called with two arguments, mode is always `strict`.

    .. note:: You must :func:`unstub` after stubbing, or use `with`
        statement.

    TrN   F)rZ   Ellipsis
thenAnswerr3   r   rS   )rW   attr_or_replacementreplacementr1   rY   r2   s         r   patchr`     sn    ( )R"--k::+TC-)z++T%))133=:k3J	Kr   c                     t        | t              rt        |       } t        |       t	        ||||       G fddt
              } |       S )a1  Stub a function call, and set up an expected call count.

    Usage::

        # Given `dog` is an instance of a `Dog`
        expect(dog, times=1).bark('Wuff').thenReturn('Miau')
        dog.bark('Wuff')
        dog.bark('Wuff')  # will throw at call time: too many invocations

        # maybe if you need to ensure that `dog.bark()` was called at all
        verifyNoUnwantedInteractions()

    .. note:: You must :func:`unstub` after stubbing, or use `with`
        statement.

    See :func:`when`, :func:`when2`, :func:`verifyNoUnwantedInteractions`

    rN   r'   c                       e Zd Z fdZy)expect.<locals>.Expectc                 6    t        j                  |      S )N)r   r-   rR   )r<   r=   r-   r2   r>   s     r   r?   z"expect.<locals>.Expect.__getattr__?  s     //? r   Nr@   )r-   r2   r>   s   r   Expectrc   >  s    	r   re   )rB   rC   r   r3   r+   rE   )	r1   r-   r(   r)   r*   r   re   r2   r>   s	    `     @@r   expectrf   !  sR    * #sclF+G.WVWFO   8Or   c                  j    | r| D ]  }t        j                  |        yt        j                          y)aS  Unstubs all stubbed methods and functions

    If you don't pass in any argument, *all* registered mocks and
    patched modules, classes etc. will be unstubbed.

    Note that additionally, the underlying registry will be cleaned.
    After an `unstub` you can't :func:`verify` anymore because all
    interactions will be forgotten.
    N)r	   unstub
unstub_all)objsr1   s     r   rh   rh   H  s-     C  %  	  "r   c                  H    | D ]  }t        |      }|j                           y)a`  Forget all invocations of given objs.

    If you already *call* mocks during your setup routine, you can now call
    ``forget_invocations`` at the end of your setup, and have a clean
    'recording' for your actual test code. T.i. you don't have
    to count the invocations from your setup code anymore when using
    :func:`verify` afterwards.
    N)r5   clear_invocationsrj   r1   r2   s      r   forget_invocationsrn   Z  s$     $S)!!# r   c                      t        |   | D ]8  }t        |      }|j                  D ]  }|j                  rt	        d|z         : y )N
Unwanted interaction: %s)verifyNoUnwantedInteractionsr5   invocationsverifiedr
   )rj   r1   r2   is       r   verifyNoMoreInteractionsru   h  sF     $'$S)$$A::'(Dq(HII % r   c                      | D ]@  }t        |      }t        |j                        dkD  s't        d|j                  d   z         y)aq  Verify that no methods have been called on given objs.

    Note that strict mocks usually throw early on unexpected, unstubbed
    invocations. Partial mocks ('monkeypatched' objects or modules) do not
    support this functionality at all, bc only for the stubbed invocations
    the actual usage gets recorded. So this function is of limited use,
    nowadays.

    r   rp   N)r5   r   rr   r
   rm   s      r   verifyZeroInteractionsrw   s  sM     $S)w""#a'#,w/B/B1/EEG G	 r   c                      | rt        t        |       }nt        j                         }|D ]#  }|j                  D ]  }|j                           % y)a  Verifies that expectations set via `expect` are met

    E.g.::

        expect(os.path, times=1).exists(...).thenReturn(True)
        os.path('/foo')
        verifyNoUnwantedInteractions(os.path)  # ok, called once

    If you leave out the argument *all* registered objects will
    be checked.

    .. note:: **DANGERZONE**: If you did not :func:`unstub` correctly,
        it is possible that old registered mocks, from other tests
        leak.

    See related :func:`expect`
    N)mapr5   r	   get_registered_mocksstubbed_invocationsrG   rj   theMocksmockrt   s       r   rq   rq     sE    & )40 557))AHHJ * r   c                      | rt        t        |       }nt        j                         }|D ]#  }|j                  D ]  }|j                           % y)a  Ensure stubs are actually used.

    This functions just ensures that stubbed methods are actually used. Its
    purpose is to detect interface changes after refactorings. It is meant
    to be invoked usually without arguments just before :func:`unstub`.

    N)ry   r5   r	   rz   r{   
check_usedr|   s       r   verifyStubbedInvocationsAreUsedr     sG     )40 557 ))ALLN * r   )NNNN)T)r   NNNFr:   )TNNNN)#operator r   r   utilsr   r   mockingr   r	   r
   r   r   methodcaller__tracebackhide__r   r   r!   r+   r3   r5   rG   rE   rI   rK   rU   rZ   r`   rf   rh   rn   ru   rw   rq   r   r   r   r   <module>r      s   *    .  ( +	I 	 *H))m%67 
+;	 8< )D =A'Tv 
 *JZH0K> :>#N#$$JG&8r   