U
    M8c0;                     @   sv   d dl Z d dlmZ d dlmZ d dlmZ d dlmZm	Z	m
Z
mZ d dlmZ G dd dZe ZG d	d
 d
ZdS )    N)deque)pformat)AWSResponse)ParamValidationErrorStubAssertionErrorStubResponseErrorUnStubbedResponseError)validate_parametersc                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	_ANYzZ
    A helper object that compares equal to everything. Copied from
    unittest.mock
    c                 C   s   dS )NT selfotherr   r   1/tmp/pip-unpacked-wheel-ozje0y8b/botocore/stub.py__eq__!   s    z_ANY.__eq__c                 C   s   dS )NFr   r   r   r   r   __ne__$   s    z_ANY.__ne__c                 C   s   dS )Nz<ANY>r   r   r   r   r   __repr__'   s    z_ANY.__repr__N)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r
      s   r
   c                   @   s   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zd#ddZ	dd Z
d$ddZdd Zdd Zdd Zdd Zdd Zdd  Zd!d" ZdS )%Stubbera  
    This class will allow you to stub out requests so you don't have to hit
    an endpoint to write tests. Responses are returned first in, first out.
    If operations are called out of order, or are called with no remaining
    queued responses, an error will be raised.

    **Example:**
    ::
        import datetime
        import botocore.session
        from botocore.stub import Stubber


        s3 = botocore.session.get_session().create_client('s3')
        stubber = Stubber(s3)

        response = {
            'IsTruncated': False,
            'Name': 'test-bucket',
            'MaxKeys': 1000, 'Prefix': '',
            'Contents': [{
                'Key': 'test.txt',
                'ETag': '"abc123"',
                'StorageClass': 'STANDARD',
                'LastModified': datetime.datetime(2016, 1, 20, 22, 9),
                'Owner': {'ID': 'abc123', 'DisplayName': 'myname'},
                'Size': 14814
            }],
            'EncodingType': 'url',
            'ResponseMetadata': {
                'RequestId': 'abc123',
                'HTTPStatusCode': 200,
                'HostId': 'abc123'
            },
            'Marker': ''
        }

        expected_params = {'Bucket': 'test-bucket'}

        stubber.add_response('list_objects', response, expected_params)
        stubber.activate()

        service_response = s3.list_objects(Bucket='test-bucket')
        assert service_response == response


    This class can also be called as a context manager, which will handle
    activation / deactivation for you.

    **Example:**
    ::
        import datetime
        import botocore.session
        from botocore.stub import Stubber


        s3 = botocore.session.get_session().create_client('s3')

        response = {
            "Owner": {
                "ID": "foo",
                "DisplayName": "bar"
            },
            "Buckets": [{
                "CreationDate": datetime.datetime(2016, 1, 20, 22, 9),
                "Name": "baz"
            }]
        }


        with Stubber(s3) as stubber:
            stubber.add_response('list_buckets', response, {})
            service_response = s3.list_buckets()

        assert service_response == response


    If you have an input parameter that is a randomly generated value, or you
    otherwise don't care about its value, you can use ``stub.ANY`` to ignore
    it in validation.

    **Example:**
    ::
        import datetime
        import botocore.session
        from botocore.stub import Stubber, ANY


        s3 = botocore.session.get_session().create_client('s3')
        stubber = Stubber(s3)

        response = {
            'IsTruncated': False,
            'Name': 'test-bucket',
            'MaxKeys': 1000, 'Prefix': '',
            'Contents': [{
                'Key': 'test.txt',
                'ETag': '"abc123"',
                'StorageClass': 'STANDARD',
                'LastModified': datetime.datetime(2016, 1, 20, 22, 9),
                'Owner': {'ID': 'abc123', 'DisplayName': 'myname'},
                'Size': 14814
            }],
            'EncodingType': 'url',
            'ResponseMetadata': {
                'RequestId': 'abc123',
                'HTTPStatusCode': 200,
                'HostId': 'abc123'
            },
            'Marker': ''
        }

        expected_params = {'Bucket': ANY}
        stubber.add_response('list_objects', response, expected_params)

        with stubber:
            service_response = s3.list_objects(Bucket='test-bucket')

        assert service_response == response
    c                 C   s   || _ d| _d| _t | _dS )zA
        :param client: The client to add your stubs to.
        Zboto_stubberZboto_stubber_expected_paramsN)client	_event_id_expected_params_event_idr   _queue)r   r   r   r   r   __init__   s    zStubber.__init__c                 C   s   |    | S N)activater   r   r   r   	__enter__   s    zStubber.__enter__c                 C   s   |    d S r   )
deactivate)r   Zexception_typeZexception_value	tracebackr   r   r   __exit__   s    zStubber.__exit__c                 C   s8   | j jjjd| j| jd | j jjjd| j| jd dS )z5
        Activates the stubber on the client
        before-parameter-build.*.*Z	unique_idbefore-call.*.*N)	r   metaeventsZregister_first_assert_expected_paramsr   register_get_response_handlerr   r   r   r   r   r      s    

zStubber.activatec                 C   s8   | j jjjd| j| jd | j jjjd| j| jd dS )z7
        Deactivates the stubber on the client
        r$   r%   r&   N)r   r'   r(   
unregisterr)   r   r+   r   r   r   r   r   r!      s    

zStubber.deactivateNc                 C   s   |  ||| dS )ax  
        Adds a service response to the response queue. This will be validated
        against the service model to ensure correctness. It should be noted,
        however, that while missing attributes are often considered correct,
        your code may not function properly if you leave them out. Therefore
        you should always fill in every value you see in a typical response for
        your particular request.

        :param method: The name of the client method to stub.
        :type method: str

        :param service_response: A dict response stub. Provided parameters will
            be validated against the service model.
        :type service_response: dict

        :param expected_params: A dictionary of the expected parameters to
            be called for the provided service response. The parameters match
            the names of keyword arguments passed to that client call. If
            any of the parameters differ a ``StubResponseError`` is thrown.
            You can use stub.ANY to indicate a particular parameter to ignore
            in validation. stub.ANY is only valid for top level params.
        N)_add_response)r   methodservice_responseexpected_paramsr   r   r   add_response   s    zStubber.add_responsec                 C   sn   t | j|s$td| jjjj|f td di d }| jjj|}| 	|| |||f|d}| j
| d S )Nz"Client %s does not have method: %s   operation_nameresponser0   )hasattrr   
ValueErrorr'   service_modelZservice_namer   method_to_api_mappingget_validate_operation_responser   append)r   r.   r/   r0   http_responser4   r5   r   r   r   r-      s    zStubber._add_response   c	                 C   s   t d|i d}	d|i||dd}
|dk	r8|
d | |dk	rN|
d | |dk	r| jjj}||}| || |
| | jjj|}||	|
f|d}| j	
| dS )aG  
        Adds a ``ClientError`` to the response queue.

        :param method: The name of the service method to return the error on.
        :type method: str

        :param service_error_code: The service error code to return,
                                   e.g. ``NoSuchBucket``
        :type service_error_code: str

        :param service_message: The service message to return, e.g.
                        'The specified bucket does not exist.'
        :type service_message: str

        :param http_status_code: The HTTP status code to return, e.g. 404, etc
        :type http_status_code: int

        :param service_error_meta: Additional keys to be added to the
            service Error
        :type service_error_meta: dict

        :param expected_params: A dictionary of the expected parameters to
            be called for the provided service response. The parameters match
            the names of keyword arguments passed to that client call. If
            any of the parameters differ a ``StubResponseError`` is thrown.
            You can use stub.ANY to indicate a particular parameter to ignore
            in validation.

        :param response_meta: Additional keys to be added to the
            response's ResponseMetadata
        :type response_meta: dict

        :param modeled_fields: Additional keys to be added to the response
            based on fields that are modeled for the particular error code.
            These keys will be validated against the particular error shape
            designated by the error code.
        :type modeled_fields: dict

        NZHTTPStatusCode)MessageZCode)ResponseMetadataErrorrB   rA   r3   )r   updater   r'   r8   Zshape_for_error_code_validate_responser9   r:   r   r<   )r   r.   Zservice_error_codeZservice_messageZhttp_status_codeZservice_error_metar0   Zresponse_metaZmodeled_fieldsr=   Zparsed_responser8   shaper4   r5   r   r   r   add_client_error  s&    2


zStubber.add_client_errorc                 C   s$   t | j}|dkr t| ddS )z<
        Asserts that all expected calls were made.
        r   z responses remaining in queue.N)lenr   AssertionError)r   	remainingr   r   r   assert_no_pending_responsesV  s    
z#Stubber.assert_no_pending_responsesc                 C   sF   | j st|jdd| j d d }||jkrBt|jd| ddd S )NzUnexpected API Call: A call was made but no additional calls expected. Either the API Call was not stubbed or it was called multiple times.r4   reasonr   r4   z'Operation mismatch: found response for .)r   r   namer   )r   modelparamsrN   r   r   r   _assert_expected_call_order^  s    	

z#Stubber._assert_expected_call_orderc                 K   s   |  || | j d S )Nr5   )rQ   r   popleft)r   rO   rP   contextkwargsr   r   r   r+   p  s    zStubber._get_response_handlerc                 K   s   |  |rd S | || | jd d }|d kr4d S | D ]>\}}||ks\|| || kr<t|jdt|t|f dq<t| t| krt|jdt|t|f dd S )Nr   r0   z)Expected parameters:
%s,
but received:
%srK   )	_should_not_stubrQ   r   itemsr   rN   r   sortedkeys)r   rO   rP   rS   rT   r0   paramvaluer   r   r   r)   u  s*    
zStubber._assert_expected_paramsc                 C   s   |r| drdS d S )NZis_presign_requestT)r:   )r   rS   r   r   r   rU     s    zStubber._should_not_stubc                 C   sF   | j jj}||}|j}|}d|kr6t|}|d= | || d S )NrA   )r   r'   r8   operation_modeloutput_shapecopyrD   )r   r4   r/   r8   r[   r\   r5   r   r   r   r;     s    


z$Stubber._validate_operation_responsec                 C   s&   |d k	rt || n|r"tddd S )Nz6Service response should only contain ResponseMetadata.)report)r	   r   )r   rE   r5   r   r   r   rD     s    zStubber._validate_response)N)r>   r>   r?   NNNN)r   r   r   r   r   r    r#   r   r!   r1   r-   rF   rJ   rQ   r+   r)   rU   r;   rD   r   r   r   r   r   .   s.   y	
       
Rr   )r]   collectionsr   pprintr   Zbotocore.awsrequestr   Zbotocore.exceptionsr   r   r   r   Zbotocore.validater	   r
   ANYr   r   r   r   r   <module>   s   