
    iO                         S r SSKJr  SSKJr   " S S\5      r " S S\5      r " S S	\5      r " S
 S\5      r	 " S S\5      r
 " S S\	5      r " S S\5      r " S S\	5      rg)z(Planned operations for spies to perform.    )unicode_literals)UnexpectedCallErrorc                   .    \ rS rSrSrS rSS jrS rSrg)	BaseSpyOperation   aI  Base class for a spy operation.

Spy operations can be performed when a spied-on function is called,
handling it according to a plan provided by the caller. They're registered
by passing ``op=`` when spying on the function.

There are a handful of built-in operations in KGB, but projects can
subclass this and define their own.
c                     [         e)a  Handle a call to this operation.

Args:
    spy_call (kgb.calls.SpyCall):
        The call to handle.

    *args (tuple):
        Positional arguments passed into the call. This will be
        normalized to not contain an object instance for bound
        method or class methods.

    **kwargs (tuple):
        Keyword arguments passed into the call.

Returns:
    object:
    The value to return to the caller of the spied function.

Raises:
    Exception:
        Any exception to raise to the caller of the spied function.
NotImplementedError)selfspy_callargskwargss       F/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/kgb/ops.pyhandle_callBaseSpyOperation.handle_call   s
    . "!    c                 t   ^  UT l         UR                  UR                  :X  a  U(       d  U 4S jnU$ U 4S jnU$ )a@  Set up the operation.

This associates the spy with the operation, and then returns a fake
function to set for the spy, which will in turn call the operation's
handler.

Args:
    spy (kgb.spies.FunctionSpy):
        The spy this operation is for.

    force_unbound (bool, optional):
        Whether to force building an unbound fake function. This is
        needed for any functions called by an operation itself (and
        is thus used for nested operations).

        Version Added:
            6.1

Returns:
    callable:
    The fake function to set up with the spy.
c                 (   > TR                   " U0 UD6$ N_on_spy_call)_selfr   r   r   s      r   	fake_func)BaseSpyOperation.setup.<locals>.fake_funcF       (($9&99r   c                  (   > TR                   " U 0 UD6$ r   r   )r   r   r   s     r   r   r   I   r   r   )spy	func_typeTYPE_BOUND_METHOD)r   r   force_unboundr   s   `   r   setupBaseSpyOperation.setup,   s:    . ==C111-: : r   c                     U R                   nUR                  nUR                  UR                  :X  a  UR                  " USS 0 UD6(       d   eOUR                  " U0 UD6(       d   eU R
                  " U/UQ70 UD6$ )a/  Internal handler for a call to this operation.

This normalizes and sanity-checks the arguments and then calls
:py:meth:`handle_call`.

Args:
    *args (tuple):
        All positional arguments made in the call. This may include the
        object instance for bound methods or the class for
        classmethods.

    **kwargs (dict):
        All keyword arguments made in the call.

Returns:
    object:
    The value to return to the caller of the spied function.

Raises:
    Exception:
        Any exception to raise to the caller of the spied function.
   N)r   	last_callr   TYPE_UNBOUND_METHODcalled_withr   )r   r   r   r   r   s        r   r   BaseSpyOperation._on_spy_callN   s{    . hh====C333''ab<V<<<''8888:4:6::r   )r   N)F)	__name__
__module____qualname____firstlineno____doc__r   r!   r   __static_attributes__ r   r   r   r      s    "2 D;r   r   c                   J   ^  \ rS rSrSrU 4S jrU 4S jrS rS rS r	Sr
U =r$ )	BaseMatchingSpyOperationp   zBase class for a operation that handles calls based on matched rules.

This helps subclasses to call consumer-defined handlers for calls based on
some kind of conditions. For instance, based on arguments, or the order in
which calls are made.
c                 6   > [         [        U ]  5         Xl        g)a  Initialize the operation.

By default, this takes a list of configurations for matching calls,
which the subclass will use to validate and handle a call.

The calls are a list of dictionaries with the following keys:

``args`` (:py:class:`tuple`, optional):
    Positional arguments for a match.

``kwargs`` (:py:class:`dict`, optional):
    Keyword arguments for a match.

``call_fake`` (:py:class:`callable`, optional):
    A function to call when all arguments have matched. This takes
    precedence over ``call_original``.

``call_original`` (:py:class:`bool`, optional):
    Whether to call the original function. This is the default if
    ``call_fake`` is not provided.

``op`` (:py:class:`BaseSpyOperation`, optional):
    A spy operation to call instead of ``call_fake`` or
    ``call_original``.

Subclasses may define custom keys.

Version Changed:
    6.1:
    Added support for ``op``.

Args:
    calls (list of dict):
        A list of call match configurations.
N)superr1   __init___callsr   calls	__class__s     r   r5   !BaseMatchingSpyOperation.__init__x   s    H 	&68r   c                    > [         [        U ]
  " U40 UD6n/ nU R                   HL  nSU;   a2  UR	                  5       nUR                  S5      R                  USS9US'   UR                  U5        MN     X@l        U$ )a  Set up the operation.

This invokes the common behavior for setting up a spy operation, and
then goes through all registered calls to see if any call-provided
operations also need to be set up.

Version Added:
    6.1

Args:
    spy (kgb.spies.FunctionSpy):
        The spy this operation is for.

    **kwargs (dict):
        Additional keyword arguments to pass to the parent.

Returns:
    callable:
    The fake function to set up with the spy.
opT)r    	call_fake)r4   r1   r!   r6   copypopappend)r   r   r   result	new_callscallr9   s         r   r!   BaseMatchingSpyOperation.setup   s    * /<SKFK	 KKDt|yy{$(HHTN$8$8GK %9 %M[! T"    r   c                     [         e)a  Return a call match configuration for a call.

This will typically be one of the call match configurations provided
during initialization.

Subclasses must override this to return a dictionary containing
information that can be used to assert, track, and handle a call.
If they can't find a suitable call, they must raise
:py:class:`kgb.errors.UnexpectedCallError`.

Args:
    spy_call (kgb.calls.SpyCall):
        The call to return a match for.

Returns:
    dict:
    The call match configuration.

Raises:
    kgb.errors.UnexpectedCallError:
        A call match configuration could not be found. Details should
        be in the error message.
r	   )r   r   s     r   get_call_match_config.BaseMatchingSpyOperation.get_call_match_config   s
    0 "!r   c                     U R                   R                  R                  " U R                   R                  /UR	                  SS5      Q70 UR	                  S0 5      D6  g)a  Validate that the last call matches the call configuration.

This will assert that the last call matches the ``args`` and ``kwargs``
from the given call match configuration.

Subclasses can override this to check other conditions.

Args:
    call_match_config (dict):
        The call match configuration returned from
        :py:meth:`get_call_match_config` for the last call.

Raises:
    AssertionError:
        The call did not match the configuration.
r   r/   r   N)r   agencyassertSpyCalledWithr%   get)r   call_match_configs     r   validate_call&BaseMatchingSpyOperation.validate_call   sS    " 	++HH	3""62.	3  ##Hb1	3r   c                     U R                  U5      nUc   eU R                  U5        UR                  S5      nUb  U" U0 UD6$ UR                  SS5      (       a  U R                  R                  " U0 UD6$ g)a  Handle a call to this operation.

This will find a suitable call match configuration, if one was
provided, and then call one of the following, in order of preference:

1. The spy operation (if ``op`` is set)
2. The fake function (if ``call_fake`` was provided)
3. The original function (if ``call_original`` is not set to
   ``False``)

If none of the above are invoked, ``None`` will be returned instead.

Version Changed:
    6.1:
    Added support for ``op``.

Args:
    spy_call (kgb.calls.SpyCall):
        The call to handle.

    *args (tuple):
        Positional arguments passed into the call. This will be
        normalized to not contain an object instance for bound
        method or class methods.

    **kwargs (tuple):
        Keyword arguments passed into the call.

Returns:
    object:
    The value to return to the caller of the spied function.
    This may be returned by a fake or original function.

Raises:
    AssertionError:
        The call did not match the returned configuration.

    Exception:
        Any exception to raise to the caller of the spied function.
        This may be raised by a fake or original function.

    kgb.errors.UnexpectedCallError:
        A call match configuration could not be found. Details should
        be in the error message.
Nr=   call_originalT)rF   rM   rK   r   rP   )r   r   r   r   rL   funcs         r   r   $BaseMatchingSpyOperation.handle_call   s    \ !66x@ ,,,,- !$$[1(((  $7788))4:6::r   )r6   )r)   r*   r+   r,   r-   r5   r!   rF   rM   r   r.   __classcell__r9   s   @r   r1   r1   p   s(    &P(T"43,= =r   r1   c                   2   ^  \ rS rSrSrU 4S jrS rSrU =r$ )SpyOpMatchAnyi:  aP  A operation for handling one or more expected calls in any order.

This is used to list the calls (specifying positional and keyword
arguments) that are expected to be made, raising an error if any calls are
made that weren't expected.

Each of those expected sets of arguments can optionally result in a call to
a fake function or the original function. This can be specified per set of
arguments.

Example:
    spy_on(traps.trigger, op=SpyOpMatchAny([
        {
            'args': ('hallway_lasers',),
            'call_fake': _send_wolves,
        },
        {
            'args': ('trap_tile',),
            'call_fake': _spill_hot_oil,
        },
        {
            'args': ('infrared_camera',),
            'kwargs': {
                'sector': 'underground_passage',
            },
            'call_original': False,
        },
    ]))
c                 ,   > [         [        U ]  U5        g)a  Initialize the operation.

This takes a list of configurations for matching calls, which can be
called in any order.
those calls are expected.

The calls are a list of dictionaries with the following keys:

``args`` (:py:class:`tuple`, optional):
    Positional arguments for a match.

``kwargs`` (:py:class:`dict`, optional):
    Keyword arguments for a match.

``call_fake`` (:py:class:`callable`, optional):
    A function to call when all arguments have matched. This takes
    precedence over ``call_original``.

``call_original`` (:py:class:`bool`, optional):
    Whether to call the original function. This is the default if
    ``call_fake`` is not provided.

Args:
    calls (list of dict):
        A list of call match configurations.
N)r4   rV   r5   r7   s     r   r5   SpyOpMatchAny.__init__Y  s    6 	mT+E2r   c           	          U R                    H>  nUR                  " UR                  SS5      0 UR                  S0 5      D6(       d  M<  Us  $    [        SSU R                  R
                  0-  5      e)a  Return a call match configuration for a call.

This will check if there are any call match configurations provided
during initialization that match the call.

Args:
    spy_call (kgb.calls.SpyCall):
        The call to return a match for.

Returns:
    dict:
    The call match configuration.

Raises:
    kgb.errors.UnexpectedCallError:
        A call match configuration could not be found. Details should
        be in the error message.
r   r/   r   z3%(spy)s was not called with any expected arguments.r   )r6   r'   rK   r   r   	func_name)r   r   rL   s      r   rF   #SpyOpMatchAny.get_call_match_configv  s    & "&##%6%:%:62%F K&7&;&;Hb&IK K(( "-
 "Atxx)) 	r   r/   	r)   r*   r+   r,   r-   r5   rF   r.   rS   rT   s   @r   rV   rV   :  s    <3: r   rV   c                   2   ^  \ rS rSrSrU 4S jrS rSrU =r$ )SpyOpMatchInOrderi  aY  A operation for handling expected calls in a given order.

This is used to list the calls (specifying positional and keyword
arguments) that are expected to be made, in the order they should be made,
raising an error if too many calls were made or a call didn't match the
expected arguments.

Each of those expected sets of arguments can optionally result in a call to
a fake function or the original function. This can be specified per set of
arguments.

Example:
    spy_on(lockbox.enter_code, op=SpyOpMatchInOrder([
        {
            'args': (1, 2, 3, 4, 5, 6),
            'call_original': False,
        },
        {
            'args': (9, 0, 2, 1, 0, 0),
            'call_fake': _start_countdown,
        },
        {
            'args': (4, 8, 15, 16, 23, 42),
            'kwargs': {
                'secret_button_pushed': True,
            },
            'call_original': True,
        },
        {
            'args': (4, 8, 15, 16, 23, 42),
            'kwargs': {
                'secret_button_pushed': True,
            },
            'op': SpyOpRaise(Exception('Oh no')),
        },
    ]))
c                 :   > [         [        U ]  U5        SU l        g)aU  Initialize the operation.

This takes a list of configurations for matching calls, in the order
those calls are expected.

The calls are a list of dictionaries with the following keys:

``args`` (:py:class:`tuple`, optional):
    Positional arguments for a match.

``kwargs`` (:py:class:`dict`, optional):
    Keyword arguments for a match.

``call_fake`` (:py:class:`callable`, optional):
    A function to call when all arguments have matched. This takes
    precedence over ``call_original``.

``call_original`` (:py:class:`bool`, optional):
    Whether to call the original function. This is the default if
    ``call_fake`` is not provided.

``op`` (:py:class:`BaseSpyOperation`, optional):
    A spy operation to call instead of ``call_fake`` or
    ``call_original``.

Args:
    calls (list of dict):
        A list of call match configurations.
r   N)r4   r^   r5   _nextr7   s     r   r5   SpyOpMatchInOrder.__init__  s    < 	/6
r   c           	          U R                   n U R                  U   nU =R                   S-  sl         U$ ! [         a>    [        S[	        U R                  5      UUS-   U R
                  R                  S.-  5      ef = f)a  Return a call match configuration for a call.

This will check if the spy call matches the next call match
configuration in the list provided by the consumer.

Args:
    spy_call (kgb.calls.SpyCall):
        The call to return a match for.

Returns:
    dict:
    The call match configuration.

Raises:
    kgb.errors.UnexpectedCallError:
        Too many calls were made to the function.
zy%(spy)s was called %(num_calls)s time(s), but only %(expected_calls)s call(s) were expected. Latest call: %(latest_call)sr$   )expected_callslatest_call	num_callsr   )r`   r6   
IndexErrorr   lenr   rZ   )r   r   irL   s       r   rF   'SpyOpMatchInOrder.get_call_match_config  s    $ JJ	 $A 	

a
    
	%" '*$++&6#+!"Q88--		 	
	s
   4 AA<)r`   r\   rT   s   @r   r^   r^     s    $L D$! $!r   r^   c                   $    \ rS rSrSrS rS rSrg)
SpyOpRaisei  zAn operation for raising an exception.

This is used to simulate a failure of some sort in a function or method.

Example:
    spy_on(pen.emit_poison, op=SpyOpRaise(PoisonEmptyError()))
c                     Xl         g)z{Initialize the operation.

Args:
    exc (Exception):
        The exception instance to raise when the function is called.
Nexc)r   rn   s     r   r5   SpyOpRaise.__init__  s	     r   c                     U R                   e)aJ  Handle a call to this operation.

This will raise the exception provided to the operation.

Args:
    *args (tuple, ignored):
        Positional arguments passed into the call.

    **kwargs (tuple, ignored):
        Keyword arguments passed into the call.

Raises:
    Exception:
        The exception provided to the operation.
rm   r   r   r   s      r   r   SpyOpRaise.handle_call  s      hhr   rm   Nr)   r*   r+   r,   r-   r5   r   r.   r/   r   r   rk   rk     s    r   rk   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )SpyOpRaiseInOrderi*  aL  An operation for raising exceptions in the order of calls.

This is similar to :py:class:`SpyOpRaise`, but will raise a different
exception for each call, based on a provided list.

Example:
    spy_on(our_agent.get_identities, op=SpyOpRaiseInOrder([
        PoisonEmptyError(),
        Kaboom(),
        MissingPenError(),
    ]))
c           	      n   > [         [        U ]  U Vs/ s H  nS[        U5      0PM     sn5        gs  snf )zInitialize the operation.

Args:
    exceptions (list of Exception):
        The list of exceptions, one for each function call.
r<   N)r4   ru   r5   rk   )r   
exceptionsrn   r9   s      r   r5   SpyOpRaiseInOrder.__init__8  sF     	/ "	1
 " jo "	1
 	 1
   2r/   r)   r*   r+   r,   r-   r5   r.   rS   rT   s   @r   ru   ru   *       r   ru   c                   $    \ rS rSrSrS rS rSrg)SpyOpReturniG  zAn operation for returning a value.

This is used to simulate a simple result from a function call without
having to override the method or provide a lambda.

Example:
    spy_on(our_agent.get_identity, op=SpyOpReturn('nobody...'))
c                     Xl         g)zuInitialize the operation.

Args:
    return_value (object):
        The value to return when the function is called.
Nreturn_value)r   r   s     r   r5   SpyOpReturn.__init__Q  s
     )r   c                     U R                   $ )aD  Handle a call to this operation.

This will return the value provided to the operation.

Args:
    *args (tuple, ignored):
        Positional arguments passed into the call.

    **kwargs (tuple, ignored):
        Keyword arguments passed into the call.

Returns:
    object:
    The return value provided to the operation.
r   rq   s      r   r   SpyOpReturn.handle_callZ  s         r   r   Nrs   r/   r   r   r}   r}   G  s    )!r   r}   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )SpyOpReturnInOrderim  a2  An operation for returning a value.

This is similar to :py:class:`SpyOpReturn`, but will return a different
value for each call, based on a provided list.

Example:
    spy_on(our_agent.get_identities, op=SpyOpReturnInOrder([
        'nobody...',
        'who?',
        'never heard of them...',
    ]))
c           	      n   > [         [        U ]  U Vs/ s H  nS[        U5      0PM     sn5        gs  snf )zsInitialize the operation.

Args:
    return_values (list):
        The list of values, one for each function call.
r<   N)r4   r   r5   r}   )r   return_valuesvaluer9   s      r   r5   SpyOpReturnInOrder.__init__{  sG     	 $0 '	2
 ' k%( '	2
 	 2
ry   r/   rz   rT   s   @r   r   r   m  r{   r   r   N)r-   
__future__r   
kgb.errorsr   objectr   r1   rV   r^   rk   ru   r}   r   r/   r   r   <module>r      s    . ' *e;v e;PG/ GTX, Xvm!0 m!`"! "J) :#!" #!L* r   