
    (i4                         d dl mZ d dlZd dlmZmZmZmZmZ d dl	m
Z
 d dlmZ erd dlmZmZ d dlmZ d dlmZmZmZmZmZ  G d	 d
      Zy)    )iscoroutinefunctionN)TYPE_CHECKINGAnyDictUnioncast)merge)PersistentConnectionProvider)	AsyncWeb3Web3)Self)AsyncMakeRequestFnMakeRequestFnRPCEndpoint
RPCRequestRPCResponsec                   T   e Zd ZdZ	 	 	 dded   deedef   ef   deedef   ef   deedef   ef   fd	Zd
e	fdZ
d dZdededed
dfdZddded
dfdZd dZdededed
dfdZ	 d!dddede	d
dfdZddded
dfdZddded
dfdZ	 	 	 	 d"dZedeeef   d
eeef   fd       Zy)#RequestMockeraj	  
    Context manager to mock requests made by a web3 instance. This is meant to be used
    via a ``request_mocker`` fixture defined within the appropriate context.

    ************************************************************************************
    Important: When mocking results, it's important to keep in mind the types that
        clients return. For example, what we commonly translate to integers are returned
        as hex strings in the RPC response and should be mocked as such for more
        accurate testing.
    ************************************************************************************


    Example:
    -------

        def test_my_w3(w3, request_mocker):
            assert w3.eth.block_number == 0

            with request_mocker(w3, mock_results={"eth_blockNumber": "0x1"}):
                assert w3.eth.block_number == 1

            assert w3.eth.block_number == 0

    Example with async and a mocked response object:
    -----------------------------------------------

        async def test_my_w3(async_w3, request_mocker):
            def _iter_responses():
                    while True:
                        yield {"error": {"message": "transaction indexing in progress"}}
                        yield {"error": {"message": "transaction indexing in progress"}}
                        yield {"result": {"status": "0x1"}}

            iter_responses = _iter_responses()

            async with request_mocker(
                async_w3,
                mock_responses={
                    "eth_getTransactionReceipt": lambda *_: next(iter_responses)
                },
            ):
                # assert that the first two error responses are handled and the result
                # is eventually returned when present
                assert await w3.eth.get_transaction_receipt("0x1") == "0x1"


    - ``mock_results`` is a dict mapping method names to the desired "result" object of
        the RPC response.
    - ``mock_errors`` is a dict mapping method names to the desired
        "error" object of the RPC response.
    -``mock_responses`` is a dict mapping method names to the entire RPC response
        object. This can be useful if you wish to return an iterator which returns
        different responses on each call to the method.

    If a method name is not present in any of the dicts above, the request is made as
    usual.

    Nw3)AsyncWeb3[Any]r   mock_resultsr   mock_errorsmock_responsesc                 ,   || _         |xs i | _        |xs i | _        |xs i | _        t	        |j
                  t              r7|j
                  j                  | _        |j
                  j                  | _
        y |j
                  j                  | _        y N)r   r   r   r   
isinstanceproviderr
   send_request_send_requestrecv_for_request_recv_for_requestmake_request_make_request)selfr   r   r   r   s        Q/var/www/br/venv/lib/python3.12/site-packages/web3/_utils/module_testing/utils.py__init__zRequestMocker.__init__b   s|     (.B&,",2bkk#?@!#!9!9D%'[[%A%AD" ((     returnc                     t        | j                  j                  d      r>t        t	        j
                  | j                  j                  j                              }|S d}|S )Nrequest_counter   )hasattrr   r   nextcopydeepcopyr*   )r$   
request_ids     r%   _build_request_idzRequestMocker._build_request_idu   s[     tww''):; tww//??@A 	
   	
 r'   c                     | j                   | j                  j                  _        d| j                  j                  _        | S N)NN)_mock_request_handlerr   r   r"   _request_func_cacher$   s    r%   	__enter__zRequestMocker.__enter__}   s1    (,(B(B%/;,r'   exc_type	exc_value	tracebackc                     | j                   | j                  j                  _        d| j                  j                  _        y r3   )r#   r   r   r"   r5   r$   r8   r9   r:   s       r%   __exit__zRequestMocker.__exit__   s1     	% 0<,r'   methodparamsr   c                    t        d| j                        | _        t        d| j                        | _        t        fd| j                  | j
                  | j                  fD              r| j                  |      S | j                         }d|d}| j                  v rT| j                     }t        |      r	 ||      }d|v rd|d   i}nd|v r| j                  |d         }t        ||      n| j
                  v r2| j
                     }t        |      r	 ||      }t        |d|i      nX| j                  v r?| j                     }t        |      r	 ||      }t        || j                  |            nt        d      t        | j                  d	d       }|'  |fd
      | j                  j                  |      S S )Nr   r   c              3   &   K   | ]  }|v 
 y wr    .0	mock_dictr>   s     r%   	<genexpr>z6RequestMocker._mock_request_handler.<locals>.<genexpr>         
 )#
   2.0jsonrpcidresulterror Invariant: unreachable code path
_decoratorc                      S r   rB   )_mocked_responses    r%   <lambda>z5RequestMocker._mock_request_handler.<locals>.<lambda>   s     r'   )r   r   r#   allr   r   r   r1   callable_create_error_objectr	   	Exceptiongetattrr   )	r$   r>   r?   r0   response_dictmock_returnrN   	decoratorrS   s	    `      @r%   r4   z#RequestMocker._mock_request_handler   s    vtww'!/43E3EF 
"..0A0A4CVCVW
 
 %%ff55++-
$)<T(((--f5K$)&&9;&'X)>?K'"77G8LM#M;?Ot(((++F3K$)&&9#MHk3JKOt'''$$V,Eff-#M43L3LU3STO>??D..dC	  9978  &&  #"r'   c                   K   t        | j                  j                  t              sB| j                  | j                  j                  _        d| j                  j                  _        | S | j                  | j                  j                  _        | j                  | j                  j                  _
        d| j                  j                  _        d| j                  j                  _        | S wr3   )r   r   r   r
   _async_mock_request_handlerr"   r5   _async_mock_send_handlerr   _async_mock_recv_handlerr    _send_func_cache_recv_func_cacher6   s    r%   
__aenter__zRequestMocker.__aenter__   s     $''**,HI,0,L,LDGG)3?DGG0 	 -1,I,IDGG)040M0MDGG-0<DGG-0<DGG-s   C)C+c                   K   t        | j                  j                  t              sA| j                  | j                  j                  _        d| j                  j                  _        y | j                  | j                  j                  _        | j                  | j                  j                  _
        d| j                  j                  _        d| j                  j                  _        y wr3   )r   r   r   r
   r#   r"   r5   r   r   r!   r    ra   rb   r<   s       r%   	__aexit__zRequestMocker.__aexit__   s     $''**,HI,0,>,>DGG)3?DGG0,0,>,>DGG)040F0FDGG-0<DGG-0<DGG-s   C'C)r0   c                   K   |r|n| j                         }d|d}|| j                  v rr| j                  |   }t        |      r
 |||      }nt        |      r |||       d {   }d|v rd|d   i}nd|v r| j	                  |d         }t        ||      }|S || j                  v rP| j                  |   }t        |      r
 |||      }nt        |      r |||       d {   }t        |d|i      }|S || j                  v r]| j                  |   }t        |      r
 |||      }nt        |      r |||       d {   }t        || j	                  |            }|S t        d      7 7 7 1w)NrI   rJ   rM   rN   rO   )	r1   r   rV   r   rW   r	   r   r   rX   )r$   r>   r?   r0   rZ   r[   mocked_resultrN   s           r%   _async_build_mock_resultz&RequestMocker._async_build_mock_result   s     $.Z43I3I3K
$)<T(((--f5K$)&&9$[1$/$??;&'X)>?K'"77G8LM!-=M. - t(((++F3K$)&&9$[1$/$??!-(K1HIM  t'''$$V,Eff-$U+#FF33!-1J1J51QRM
  >??9 @ @ 4s8   A#E7%E0&A?E7%E3&AE7E5-E73E75E7c                   K   t        d| j                        | _        t        d| j                        | _        t        fd| j                  | j
                  | j                  fD              r| j                  |       d {   S | j                  |       d {   t        | j                  dd       }|Bdt        dddt        d	d
ffd}  ||      | j                  j                  |       d {   S S 7 {7 c7 
w)Nr   r   c              3   &   K   | ]  }|v 
 y wr   rB   rC   s     r%   rF   z<RequestMocker._async_mock_request_handler.<locals>.<genexpr>  rG   rH   rP   	_provider_methodr   _paramsr(   r   c                    K   S wr   rB   )rk   rl   rm   rg   s      r%   _coroz8RequestMocker._async_mock_request_handler.<locals>._coro        %$   )r   r   r#   rU   r   r   r   rh   rY   r   r   )r$   r>   r?   r\   ro   rg   s    `   @r%   r^   z)RequestMocker._async_mock_request_handler  s     '1!"68J8JK 
"..0A0A4CVCVW
 
 ++FF;;;";;FFKKD..dC	 
%%)6%AD%%
 *5)$''*:*:FFKKK   <K Ls7   BDDDD AD:D;DDDr   c                    K   t        fd| j                  | j                  | j                  fD              r| j	                  |       d {   S | j                         }||dS 7 w)Nc              3   &   K   | ]  }|v 
 y wr   rB   rC   s     r%   rF   z9RequestMocker._async_mock_send_handler.<locals>.<genexpr>#  rG   rH   )rL   r>   r?   )rU   r   r   r   r   r1   )r$   r>   r?   r0   s    `  r%   r_   z&RequestMocker._async_mock_send_handler   so       
"..0A0A4CVCVW
 
 ++FF;;;//1J$&II <s   AA+A)A+c                   K   t        d| j                        | _        |d   |d   }t        fd| j                  | j                  | j
                  fD              r| j                  |       d {   S | j                  |d   t        |             d {   t        | j                  dd       }|;dt        d	d
ddffd}  ||      | j                  j                  |       d {   S S 7 7 \7 
w)Nr   r>   rL   c              3   &   K   | ]  }|v 
 y wr   rB   rC   s     r%   rF   z9RequestMocker._async_mock_recv_handler.<locals>.<genexpr>2  rG   rH   r?   )r0   rP   rk   _rpc_requestr   r(   r   c                    K   S wr   rB   )rk   rv   rg   s     r%   ro   z5RequestMocker._async_mock_recv_handler.<locals>._coro@  rp   rq   )r   r   rU   r   r   r   r!   rh   intrY   r   r   )r$   rpc_requestr0   r\   ro   r>   rg   s        @@r%   r`   z&RequestMocker._async_mock_recv_handler,  s     '1X& &
 
"..0A0A4CVCVW
 
 //
;;;";;K)c*o < 
 
 D22L$G	 
%%.:%%
 *5)$''*:*:KHHH  # <
 Is7   A/C<3C64'C<C8AC</C:0C<8C<:C<rN   c                 l    | j                  dd      }| j                  dd      }dt        ||d|       iS )Ncodei messagezMocked errorrN   )r{   r|   )getr	   )rN   r{   r|   s      r%   rW   z"RequestMocker._create_error_objectI  s9    yy())I~6A5IJJr'   )NNN)r(   r   r   )ry   r   r(   r   )__name__
__module____qualname____doc__r   r   strr   r&   rx   r1   r7   r=   r4   rc   re   rh   r^   r_   r`   staticmethodrW   rB   r'   r%   r   r   &   s   9| >B<@?C)*+) 5!34c9:) %s 23S89	)
 U=##56;<)&3 < < < < <0##0#-00#	0#h
= 
= 
= 
=PT 
= EI+#+-0+>A+	+Z!#!-0!	!4
J#
J-0
J	
J!'!	!: KDcN KtCH~ K Kr'   r   )asyncior   r.   typingr   r   r   r   r   eth_utils.toolzr	   web3.providers.persistentr
   web3r   r   web3._utils.compatr   
web3.typesr   r   r   r   r   r   rB   r'   r%   <module>r      sJ       gK gKr'   