
    9                         S r SSKrSSKrSSKrSSKJr  SSKJr  SSKJr  SSKJ	r	   " S S\
5      rS	 r " S
 S\5      r " S S\5      r " S S\5      r " S S\5      rS r " S S\5      rg)a  The mock module allows easy mocking of apitools clients.

This module allows you to mock out the constructor of a particular apitools
client, for a specific API and version. Then, when the client is created, it
will be run against an expected session that you define. This way code that is
not aware of the testing framework can construct new clients as normal, as long
as it's all done within the context of a mock.
    N)messages)base_api)encoding)
exceptionsc                       \ rS rSrSrSrg)Error$   zExceptions for this module. N)__name__
__module____qualname____firstlineno____doc____static_attributes__r
       0lib/third_party/apitools/base/py/testing/mock.pyr   r   $   s    %r   r   c                    [        U [        5      (       aI  [        U[        5      (       a4  [        U 5      [        U5      :w  a  g[        S [	        X5       5       5      $ [        U [
        R                  5      (       a  [        U[
        R                  5      (       d  X:H  $ U R                  5        H?  n[        XR                  5      n[        XR                  5      n[        X45      (       a  M?    g   g)a  Compare two protorpc messages for equality.

Using python's == operator does not work in all cases, specifically when
there is a list involved.

Args:
  msg1: protorpc.messages.Message or [protorpc.messages.Message] or number
      or string, One of the messages to compare.
  msg2: protorpc.messages.Message or [protorpc.messages.Message] or number
      or string, One of the messages to compare.

Returns:
  If the messages are isomorphic.
Fc              3   <   #    U  H  u  p[        X5      v   M     g 7fN)_MessagesEqual).0xys      r   	<genexpr>!_MessagesEqual.<locals>.<genexpr>;   s     DODA>!''Os   T)
isinstancelistlenallzipr   Message
all_fieldsgetattrnamer   )msg1msg2fieldfield1field2s        r   r   r   )   s     $*T4"8"8t9D	!DCODDDtX--..4!1!122|"zz*zz*f--	 #
 r   c                   (   ^  \ rS rSrU 4S jrSrU =r$ )UnexpectedRequestExceptionH   c                   > Uu  p4Uu  pV[         R                  " USS9n[         R                  " USS9nUR                  5       n	UR                  5       n
[        R                  " X5      nSR                  U5      nX5:w  a5  SR                  S5      R                  UUUUS9n[        [        U ]'  U5        g SR                  S5      R                  UUUUS9n[        [        U ]'  U5        g )NT	multiline
)z,expected: {expected_key}({expected_request})z,received: {received_key}({received_request}) )expected_keyexpected_requestreceived_keyreceived_request)zfor request to {key},zexpected: {expected_request}zreceived: {received_request}zdiff: {diff}r1   )keyr3   r5   diff)
r   MessageToRepr
splitlinesdifflibunified_diffjoinformatsuperr+   __init__)selfreceived_callexpected_callr2   r3   r4   r5   expected_reprreceived_reprexpected_linesreceived_lines
diff_linesr7   msg	__class__s                 r   r?   #UnexpectedRequestException.__init__J   s	   )6&)6& ... ... '113&113)).I
yy$'))   v)!.)!.	  0	  ,d<SA))   v !.!.	    ,d<SAr   r
   r   r   r   r   r?   r   __classcell__rI   s   @r   r+   r+   H   s    &B &Br   r+   c                   (   ^  \ rS rSrU 4S jrSrU =r$ )ExpectedRequestsExceptions   c           
         > SnU H+  u  p4USR                  U[        R                  " USS9S9-  nM-     [        [        U ]  U5        g )Nz
expected:
z{key}({request})
Tr.   )r6   request)r=   r   r8   r>   rO   r?   )r@   expected_callsrH   r6   rR   rI   s        r   r?   "ExpectedRequestsException.__init__u   sX    ,NS'.. ..w$G / I IC - 	'7<r   r
   rK   rM   s   @r   rO   rO   s   s    = =r   rO   c                   H    \ rS rSrSrS	S jr\S 5       r\S 5       rS r	Sr
g)
_ExpectedRequestResponse~   z@Encapsulation of an expected request and corresponding response.Nc                 l   Xl         X l        U(       a  U(       a  [        R                  " S5      eU(       a5  [	        U[        R
                  5      (       a  [        R                  " S5      eU(       a5  [	        U[        R
                  5      (       d  [        R                  " S5      eX0l        X@l        g )Nz4Should specify at most one of response and exceptionz,Responses should not be an instance of Errorz%Exceptions must be instances of Error)_ExpectedRequestResponse__key!_ExpectedRequestResponse__requestr   ConfigurationValueErrorr   r   "_ExpectedRequestResponse__response#_ExpectedRequestResponse__exception)r@   r6   rR   response	exceptions        r   r?   !_ExpectedRequestResponse.__init__   s    
 	44FH H
8Z-=-=>>44>@ @Z	:3C3CDD4479 9 #$r   c                     U R                   $ r   )rY   r@   s    r   r6   _ExpectedRequestResponse.key   s    zzr   c                     U R                   $ r   )rZ   rb   s    r   rR    _ExpectedRequestResponse.request   s    ~~r   c                    XR                   :w  d*  U R                  U:X  d=  [        X R                  5      (       d#  [        X4U R                   U R                  45      eU R                  (       a  U R                  eU R
                  $ )a  Validate that key and request match expectations, and respond if so.

Args:
  key: str, Actual key to compare against expectations.
  request: protorpc.messages.Message or [protorpc.messages.Message]
    or number or string, Actual request to compare againt expectations

Raises:
  UnexpectedRequestException: If key or request dont match
      expectations.
  apitools_base.Error: If a non-None exception is specified to
      be thrown.

Returns:
  The response that was specified to be returned.

)rY   rZ   r   r+   r]   r\   )r@   r6   rR   s      r   ValidateAndRespond+_ExpectedRequestResponse.ValidateAndRespond   sl    $ **T^^w%>%3G^^%L%L,c^.2jj$..-IK K """r   )__exception__key	__request
__responseNN)r   r   r   r   r   r?   propertyr6   rR   rg   r   r
   r   r   rV   rV   ~   s7    J%"    r   rV   c                   8    \ rS rSrSrS rS r  S	S jrS rSr	g)
_MockedMethod   zA mocked API service method.c                 H   UR                   U l         Xl        X l        X0l        UR                  U l        U R	                  5       n[        U R                  R                  UR                  5      U l        [        U R                  R                  UR                  5      U l
        g r   )r   _MockedMethod__key_MockedMethod__mocked_client_MockedMethod__real_methodmethod_configr#   MESSAGES_MODULErequest_type_name_MockedMethod__request_typeresponse_type_name_MockedMethod__response_type)r@   r6   mocked_clientreal_methodconfigs        r   r?   _MockedMethod.__init__   s    #,,
,((66##%%d&:&:&J&J&,&>&>@&t';';'K'K'-'@'@ Br   c           
          U(       a  SnU R                   nOSnU R                  n[        X5      (       d:  [        R                  " SR                  X0R                  U[        U5      5      5      eg)aK  Ensure the given message is of the expected type of this method.

Args:
  msg: The message instance to check.
  is_request: True to validate against the expected request type,
     False to validate against the expected response type.

Raises:
  exceptions.ConfigurationValueError: If the type of the message was
     not correct.
rR   r^   z[Expected {} is not of the correct type for method [{}].
   Required: [{}]
   Given:    [{}]N)ry   r{   r   r   r[   r=   rs   type)r@   rH   
is_requestmode	real_types        r   
_TypeCheck_MockedMethod._TypeCheck   sh     D++ID,,I#))44$$*F**ic%<= = *r   Nc           	          U(       a'  U R                  USS9  U(       a  U R                  USS9  U R                  R                  R                  [	        U R
                  UUUS95        g)a  Add an expectation on the mocked method.

Exactly one of response and exception should be specified.

Args:
  request: The request that should be expected
  response: The response that should be returned or None if
      exception is provided.
  exception: An exception that should be thrown, or None.
  enable_type_checking: When true, the message type of the request
      and response (if provided) will be checked against the types
      required by this method.
T)r   F)r^   r_   N)r   rt   _request_responsesappendrV   rs   )r@   rR   r^   r_   enable_type_checkingunused_kwargss         r   Expect_MockedMethod.Expect   s]    *  OOGO5U; 	//66$TZZ%,.6/8:	;r   c                 |   U R                   R                  (       a&  U R                   R                  R                  S5      nO[        U R                  U4S5      eUR                  U R                  U5      nUcC  U R                  (       a2  U R                  U5      n[        [        R                  " USSS95        U$ U$ )Nr   rm   T)r/   shortstrings)
rt   r   popr+   rs   rg   ru   printr   r8   )r@   rR   r   request_responser^   s        r   __call___MockedMethod.__call__  s     22#33FFJJ1M,W%|5 5 $66tzz7K 2 2))'2H(((Dt= >Or   )rj   __mocked_clientr   __real_method__request_type__response_typerv   )NNT)
r   r   r   r   r   r?   r   r   r   r   r
   r   r   rp   rp      s#    &
B=4 8<$( ;Fr   rp   c           
           " S S[         R                  5      nUR                  5        H;  nS nU(       a  [        XF5      n[	        UU[        U S-   U-   S-   U-   UU5      5        M=     U$ )Nc                       \ rS rSrSrg))_MakeMockedService.<locals>.MockedServicei"  r
   Nr   r   r   r   r   r
   r   r   MockedServicer   "  s    r   r   .)r   BaseApiServiceGetMethodsListr#   setattrrp   )api_namecollection_namemock_clientservicereal_servicer   methodr}   s           r   _MakeMockedServicer      ss    //  ((*!,7Khn>DvM))+	,	 + r   c                   D    \ rS rSrSrSS jrS rS rS rSS jr	S	 r
S
rg)Clienti1  zMock an apitools client.Nc                     U(       d  U" SS9nU R                   U l        Xl        0 U l        X l        / U l        SU l        g)a  Mock an apitools API, given its class.

Args:
  client_class: The class for the API. eg, if you
        from apis.sqladmin import v1beta3
      then you can pass v1beta3.SqladminV1beta3 to this class
      and anything within its context will use your mocked
      version.
  real_client: apitools Client, The client to make requests
      against when the expected response is None.

Fget_credentialsN)rI   _Client__orig_class_Client__client_class_Client__real_service_classes_Client__real_clientr   _Client__real_include_fields)r@   client_classreal_clients      r   r?   Client.__init__5  sA     &u=K NN*&(#("$%)"r   c                 "    U R                  5       $ r   )Mockrb   s    r   	__enter__Client.__enter__N  s    yy{r   c           
      N   U R                   =(       d    U R                  SS9n " S SU R                  U R                  5      nX l        [        U R                  5       H  n[	        U R                  U5      n[        U[        5      (       d  M0  [        U[        R                  5      (       d  MQ  X@R                  U'   UR                  nU R                  R                  < SU R                  R                  < 3n[        XeU UU R                   (       a  U" U5      OS5      n[        U R                  X75        [        XU" U 5      5        M     U R                  R                   U l        U R                   U R                  l        UR$                  U l        UR&                  U l        U $ )z/Stub out the client class with mocked services.Fr   c                       \ rS rSrSrg)Client.Mock.<locals>.PatchediV  r
   Nr   r
   r   r   Patchedr   V  s    r   r   _N)r   r   rI   dirr#   r   r   
issubclassr   r   r   _NAME_PACKAGE_URL_VERSIONr   r   IncludeFieldsr   _url_http)r@   clientr   r$   service_classr   r   mocked_service_classs           r   r   Client.MockQ  s_   ## #t':':! (; (#	dnnd&9&9 	 ++,D#D$7$7>MmT22mX-D-DEE0=''-+11O"&"5"5">">"&"5"5"B"BDH#54)-););f%$G 
 D''DD+?+EF' -* &*%8%8%F%F",0,>,>) KK	\\
r   c                 f    US LnU R                  US9  U(       a  [        R                  " XU5        g)N)suppressT)Unmocksixreraise)r@   exc_typevalue	tracebackis_active_exceptions        r   __exit__Client.__exit__x  s0    #4/01KK3r   c                     U R                   U l        U R                  R                  5        H0  u  p#[	        U R
                  X#5        [        XR                  5        M2     0 U l        U ?U ?	U R                  U R
                  l        S U l
        U R                   Vs/ s H  nUR                  UR                  4PM     nn/ U l        U(       a-  U(       d%  [        R                   " 5       S   c  [#        U5      eg g g s  snf )N   )r   rI   r   itemsr   r   delattrr   r   r   r   r   r   r6   rR   sysexc_inforO   )r@   r   r$   r   rq_rsrequestss         r   r   Client.Unmock  s    **#'#>#>#D#D#FDD''=D--. $G ')#IJ,0,F,F)%)" "&!8!8:!8 YY.!8 	 :"$H):)B+H55 *CH8	:s   "C;c                 ^    U R                   (       a  U R                  U R                   U5      $ g r   )r   r   )r@   include_fieldss     r   r   Client.IncludeFields  s.    --d.@.@.<> > r   )	rI   __client_class__orig_class__real_client__real_include_fields__real_service_classesr   r   r   r   )F)r   r   r   r   r   r?   r   r   r   r   r   r   r
   r   r   r   r   1  s$    "*2%N6&>r   r   )r   r:   r   r   apitools.base.protorpcliter   apitools.base.pyr   r   r   	Exceptionr   r   r+   rO   objectrV   rp   r   r   r
   r   r   <module>r      s|      
 
 / % % '&I &
>(B (BV= =8v 8vdF dN"d>V d>r   