Ejemplo n.º 1
0
def test_post(pipeline_client_builder, deserialization_cb):

    # Test POST LRO with both Location and Operation-Location

    # The initial response contains both Location and Operation-Location, a 202 and no Body
    initial_response = TestBasePolling.mock_send(
        'POST', 202, {
            'location': 'http://example.org/location',
            'operation-location': 'http://example.org/async_monitor',
        }, '')

    def send(request, **kwargs):
        assert request.method == 'GET'

        if request.url == 'http://example.org/location':
            return TestBasePolling.mock_send('GET',
                                             200,
                                             body={
                                                 'location_result': True
                                             }).http_response
        elif request.url == 'http://example.org/async_monitor':
            return TestBasePolling.mock_send('GET',
                                             200,
                                             body={
                                                 'status': 'Succeeded'
                                             }).http_response
        else:
            pytest.fail("No other query allowed")

    client = pipeline_client_builder(send)

    # LRO options with Location final state
    poll = LROPoller(client, initial_response, deserialization_cb,
                     LROBasePolling(0))
    result = poll.result()
    assert result['location_result'] == True

    # Location has no body

    def send(request, **kwargs):
        assert request.method == 'GET'

        if request.url == 'http://example.org/location':
            return TestBasePolling.mock_send('GET', 200,
                                             body=None).http_response
        elif request.url == 'http://example.org/async_monitor':
            return TestBasePolling.mock_send('GET',
                                             200,
                                             body={
                                                 'status': 'Succeeded'
                                             }).http_response
        else:
            pytest.fail("No other query allowed")

    client = pipeline_client_builder(send)

    poll = LROPoller(client, initial_response, deserialization_cb,
                     LROBasePolling(0))
    result = poll.result()
    assert result is None
Ejemplo n.º 2
0
def __long_poll(activity, machine, poller: LROPoller, configuration):
    logger.debug("Waiting for operation '{}' on machine '{}' to finish. Giving priority to other operations.".format(
        activity, machine['name']))
    poller.result(config.load_timeout(configuration))
    logger.debug("Finished operation '{}' on machine '{}'.".format(activity, machine['name']))

    return machine
Ejemplo n.º 3
0
    def wait_until_done(self, job_id, **kwargs):
        # type: (str, **Any) -> JobStatusDetail
        """

        :param job_id: guid id for job
        :type job_id: str
        :return: JobStatusDetail
        :rtype: JobStatusDetail
        """

        pipeline_response = self._client.document_translation.get_operation_status(
            job_id,
            cls=lambda pipeline_response, _, response_headers:
            pipeline_response)

        def callback(raw_response):
            detail = self._client._deserialize(_BatchStatusDetail,
                                               raw_response)  # pylint: disable=protected-access
            return JobStatusDetail._from_generated(detail)  # pylint: disable=protected-access

        poller = LROPoller(
            client=self._client._client,  # pylint: disable=protected-access
            initial_response=pipeline_response,
            deserialization_callback=callback,
            polling_method=LROBasePolling(
                timeout=30, lro_algorithms=[TranslationPolling()], **kwargs),
        )
        return poller.result()
 def test_long_running_delete(self):
     # Test polling from azure-asyncoperation header
     response = TestArmPolling.mock_send(
         'DELETE', 202, {'azure-asyncoperation': ASYNC_URL}, body="")
     poll = LROPoller(CLIENT, response, TestArmPolling.mock_outputs,
                      ARMPolling(0))
     poll.wait()
     assert poll.result() is None
     assert poll._polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollAsyncOpHeader is None
Ejemplo n.º 5
0
    def test_long_running_post_legacy(self):
        # Former oooooold tests to refactor one day to something more readble

        # Test polling from azure-asyncoperation header
        response = TestArmPolling.mock_send(
            'POST', 201,
            {'azure-asyncoperation': ASYNC_URL},
            body={'properties':{'provisioningState': 'Succeeded'}})
        poll = LROPoller(CLIENT, response,
            TestArmPolling.mock_deserialization_no_body,
            ARMPolling(0))
        poll.wait()
        assert poll._polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollAsyncOpHeader is None

        # Test polling from azure-asyncoperation header
        response = TestArmPolling.mock_send(
            'POST', 202,
            {'azure-asyncoperation': ASYNC_URL},
            body={'properties':{'provisioningState': 'Succeeded'}})
        poll = LROPoller(CLIENT, response,
            TestArmPolling.mock_deserialization_no_body,
            ARMPolling(0))
        poll.wait()
        assert poll._polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollAsyncOpHeader is None

        # Test polling from location header
        response = TestArmPolling.mock_send(
            'POST', 202,
            {'location': LOCATION_URL},
            body={'properties':{'provisioningState': 'Succeeded'}})
        poll = LROPoller(CLIENT, response,
            TestArmPolling.mock_outputs,
            ARMPolling(0))
        assert poll.result().name == TEST_NAME
        assert poll._polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollLocationHeader is None

        # Test fail to poll from azure-asyncoperation header
        response = TestArmPolling.mock_send(
            'POST', 202,
            {'azure-asyncoperation': ERROR})
        with pytest.raises(BadEndpointError):
            poll = LROPoller(CLIENT, response,
                TestArmPolling.mock_outputs,
                ARMPolling(0)).result()

        # Test fail to poll from location header
        response = TestArmPolling.mock_send(
            'POST', 202,
            {'location': ERROR})
        with pytest.raises(BadEndpointError):
            poll = LROPoller(CLIENT, response,
                TestArmPolling.mock_outputs,
                ARMPolling(0)).result()
Ejemplo n.º 6
0
    def test_long_running_negative(self):
        global LOCATION_BODY
        global POLLING_STATUS

        # Test LRO PUT throws for invalid json
        LOCATION_BODY = '{'
        response = TestBasePolling.mock_send('POST', 202,
                                             {'location': LOCATION_URL})
        poll = LROPoller(CLIENT, response, TestBasePolling.mock_outputs,
                         LROBasePolling(0))
        with pytest.raises(DecodeError):
            poll.result()

        LOCATION_BODY = '{\'"}'
        response = TestBasePolling.mock_send('POST', 202,
                                             {'location': LOCATION_URL})
        poll = LROPoller(CLIENT, response, TestBasePolling.mock_outputs,
                         LROBasePolling(0))
        with pytest.raises(DecodeError):
            poll.result()

        LOCATION_BODY = '{'
        POLLING_STATUS = 203
        response = TestBasePolling.mock_send('POST', 202,
                                             {'location': LOCATION_URL})
        poll = LROPoller(CLIENT, response, TestBasePolling.mock_outputs,
                         LROBasePolling(0))
        with pytest.raises(
                HttpResponseError):  # TODO: Node.js raises on deserialization
            poll.result()

        LOCATION_BODY = json.dumps({'name': TEST_NAME})
        POLLING_STATUS = 200
Ejemplo n.º 7
0
def test_final_get_via_location(port, http_request, deserialization_cb):
    client = TestRestClient(port)
    request = http_request(
        "PUT",
        "http://localhost:{}/polling/polling-with-options".format(port),
    )
    request.set_json_body({"hello": "world!"})
    initial_response = client._client._pipeline.run(request)
    poller = LROPoller(
        client._client,
        initial_response,
        deserialization_cb,
        LROBasePolling(0, lro_options={"final-state-via": "location"}),
    )
    result = poller.result()
    assert result == {"returnedFrom": "locationHeaderUrl"}
Ejemplo n.º 8
0
    def wait_until_done(self, job_id, **kwargs):
        # type: (str, **Any) -> JobStatusResult
        """Wait until the translation job is done.

        A job is considered "done" when it reaches a terminal state like
        Succeeded, Failed, Cancelled.

        :param str job_id: The translation job ID.
        :return: A JobStatusResult with information on the status of the translation job.
        :rtype: ~azure.ai.translation.document.JobStatusResult
        :raises ~azure.core.exceptions.HttpResponseError or ~azure.core.exceptions.ResourceNotFoundError:
            Will raise if validation fails on the input. E.g. insufficient permissions on the blob containers.

        .. admonition:: Example:

            .. literalinclude:: ../samples/sample_create_translation_job.py
                :start-after: [START wait_until_done]
                :end-before: [END wait_until_done]
                :language: python
                :dedent: 4
                :caption: Create a translation job and wait until it is done.
        """

        pipeline_response = self._client.document_translation.get_operation_status(
            job_id,
            cls=lambda pipeline_response, _, response_headers: pipeline_response
        )

        def callback(raw_response):
            detail = self._client._deserialize(_BatchStatusDetail, raw_response)  # pylint: disable=protected-access
            return JobStatusResult._from_generated(detail)  # pylint: disable=protected-access

        poller = LROPoller(
            client=self._client._client,  # pylint: disable=protected-access
            initial_response=pipeline_response,
            deserialization_callback=callback,
            polling_method=LROBasePolling(
                timeout=self._client._config.polling_interval,  # pylint: disable=protected-access
                lro_algorithms=[TranslationPolling()],
                **kwargs
            ),
        )
        return poller.result()
    def test_long_running_negative(self):
        global LOCATION_BODY
        global POLLING_STATUS

        # Test LRO PUT throws for invalid json
        LOCATION_BODY = '{'
        response = TestArmPolling.mock_send(
            'POST', 202,
            {'location': LOCATION_URL})
        poll = LROPoller(
            CLIENT,
            response,
            TestArmPolling.mock_outputs,
            ARMPolling(0)
        )
        with pytest.raises(DecodeError):
            poll.result()

        LOCATION_BODY = '{\'"}'
        response = TestArmPolling.mock_send(
            'POST', 202,
            {'location': LOCATION_URL})
        poll = LROPoller(CLIENT, response,
            TestArmPolling.mock_outputs,
            ARMPolling(0))
        with pytest.raises(DecodeError):
            poll.result()

        LOCATION_BODY = '{'
        POLLING_STATUS = 203
        response = TestArmPolling.mock_send(
            'POST', 202,
            {'location': LOCATION_URL})
        poll = LROPoller(CLIENT, response,
            TestArmPolling.mock_outputs,
            ARMPolling(0))
        with pytest.raises(HttpResponseError) as error: # TODO: Node.js raises on deserialization
            poll.result()
        assert error.value.continuation_token == base64.b64encode(pickle.dumps(response)).decode('ascii')

        LOCATION_BODY = json.dumps({ 'name': TEST_NAME })
        POLLING_STATUS = 200
Ejemplo n.º 10
0
    def test_long_running_patch(self):

        # Test polling from location header
        response = TestArmPolling.mock_send(
            'PATCH', 202,
            {'location': LOCATION_URL},
            body={'properties':{'provisioningState': 'Succeeded'}})
        poll = LROPoller(CLIENT, response,
            TestArmPolling.mock_outputs,
            ARMPolling(0))
        assert poll.result().name == TEST_NAME
        assert poll._polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollLocationHeader is None

        # Test polling from azure-asyncoperation header
        response = TestArmPolling.mock_send(
            'PATCH', 202,
            {'azure-asyncoperation': ASYNC_URL},
            body={'properties':{'provisioningState': 'Succeeded'}})
        poll = LROPoller(CLIENT, response,
            TestArmPolling.mock_outputs,
            ARMPolling(0))
        assert poll.result().name == TEST_NAME
        assert not hasattr(poll._polling_method._pipeline_response, 'randomFieldFromPollAsyncOpHeader')

        # Test polling from location header
        response = TestArmPolling.mock_send(
            'PATCH', 200,
            {'location': LOCATION_URL},
            body={'properties':{'provisioningState': 'Succeeded'}})
        poll = LROPoller(CLIENT, response,
            TestArmPolling.mock_outputs,
            ARMPolling(0))
        assert poll.result().name == TEST_NAME
        assert poll._polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollLocationHeader is None

        # Test polling from azure-asyncoperation header
        response = TestArmPolling.mock_send(
            'PATCH', 200,
            {'azure-asyncoperation': ASYNC_URL},
            body={'properties':{'provisioningState': 'Succeeded'}})
        poll = LROPoller(CLIENT, response,
            TestArmPolling.mock_outputs,
            ARMPolling(0))
        assert poll.result().name == TEST_NAME
        assert not hasattr(poll._polling_method._pipeline_response, 'randomFieldFromPollAsyncOpHeader')

        # Test fail to poll from azure-asyncoperation header
        response = TestArmPolling.mock_send(
            'PATCH', 202,
            {'azure-asyncoperation': ERROR})
        with pytest.raises(BadEndpointError):
            poll = LROPoller(CLIENT, response,
                TestArmPolling.mock_outputs,
                ARMPolling(0)).result()

        # Test fail to poll from location header
        response = TestArmPolling.mock_send(
            'PATCH', 202,
            {'location': ERROR})
        with pytest.raises(BadEndpointError):
            poll = LROPoller(CLIENT, response,
                TestArmPolling.mock_outputs,
                ARMPolling(0)).result()
Ejemplo n.º 11
0
    def test_long_running_put(self):
        #TODO: Test custom header field

        # Test throw on non LRO related status code
        response = TestArmPolling.mock_send('PUT', 1000, {})
        with pytest.raises(HttpResponseError):
            LROPoller(CLIENT, response,
                TestArmPolling.mock_outputs,
                ARMPolling(0)).result()

        # Test with no polling necessary
        response_body = {
            'properties':{'provisioningState': 'Succeeded'},
            'name': TEST_NAME
        }
        response = TestArmPolling.mock_send(
            'PUT', 201,
            {}, response_body
        )
        def no_update_allowed(url, headers=None):
            raise ValueError("Should not try to update")
        poll = LROPoller(CLIENT, response,
            TestArmPolling.mock_outputs,
            ARMPolling(0)
        )
        assert poll.result().name == TEST_NAME
        assert not hasattr(poll._polling_method._pipeline_response, 'randomFieldFromPollAsyncOpHeader')

        # Test polling from azure-asyncoperation header
        response = TestArmPolling.mock_send(
            'PUT', 201,
            {'azure-asyncoperation': ASYNC_URL})
        poll = LROPoller(CLIENT, response,
            TestArmPolling.mock_outputs,
            ARMPolling(0))
        assert poll.result().name == TEST_NAME
        assert not hasattr(poll._polling_method._pipeline_response, 'randomFieldFromPollAsyncOpHeader')

        # Test polling location header
        response = TestArmPolling.mock_send(
            'PUT', 201,
            {'location': LOCATION_URL})
        poll = LROPoller(CLIENT, response,
            TestArmPolling.mock_outputs,
            ARMPolling(0))
        assert poll.result().name == TEST_NAME
        assert poll._polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollLocationHeader is None

        # Test polling initial payload invalid (SQLDb)
        response_body = {}  # Empty will raise
        response = TestArmPolling.mock_send(
            'PUT', 201,
            {'location': LOCATION_URL}, response_body)
        poll = LROPoller(CLIENT, response,
            TestArmPolling.mock_outputs,
            ARMPolling(0))
        assert poll.result().name == TEST_NAME
        assert poll._polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollLocationHeader is None

        # Test fail to poll from azure-asyncoperation header
        response = TestArmPolling.mock_send(
            'PUT', 201,
            {'azure-asyncoperation': ERROR})
        with pytest.raises(BadEndpointError):
            poll = LROPoller(CLIENT, response,
                TestArmPolling.mock_outputs,
                ARMPolling(0)).result()

        # Test fail to poll from location header
        response = TestArmPolling.mock_send(
            'PUT', 201,
            {'location': ERROR})
        with pytest.raises(BadEndpointError):
            poll = LROPoller(CLIENT, response,
                TestArmPolling.mock_outputs,
                ARMPolling(0)).result()
Ejemplo n.º 12
0
def test_post(pipeline_client_builder, deserialization_cb):

        # Test POST LRO with both Location and Azure-AsyncOperation

        # The initial response contains both Location and Azure-AsyncOperation, a 202 and no Body
        initial_response = TestArmPolling.mock_send(
            'POST',
            202,
            {
                'location': 'http://example.org/location',
                'azure-asyncoperation': 'http://example.org/async_monitor',
            },
            ''
        )

        def send(request, **kwargs):
            assert request.method == 'GET'

            if request.url == 'http://example.org/location':
                return TestArmPolling.mock_send(
                    'GET',
                    200,
                    body={'location_result': True}
                ).http_response
            elif request.url == 'http://example.org/async_monitor':
                return TestArmPolling.mock_send(
                    'GET',
                    200,
                    body={'status': 'Succeeded'}
                ).http_response
            else:
                pytest.fail("No other query allowed")

        client = pipeline_client_builder(send)

        # Test 1, LRO options with Location final state
        poll = LROPoller(
            client,
            initial_response,
            deserialization_cb,
            ARMPolling(0, lro_options={"final-state-via": "location"}))
        result = poll.result()
        assert result['location_result'] == True

        # Test 2, LRO options with Azure-AsyncOperation final state
        poll = LROPoller(
            client,
            initial_response,
            deserialization_cb,
            ARMPolling(0, lro_options={"final-state-via": "azure-async-operation"}))
        result = poll.result()
        assert result['status'] == 'Succeeded'

        # Test 3, "do the right thing" and use Location by default
        poll = LROPoller(
            client,
            initial_response,
            deserialization_cb,
            ARMPolling(0))
        result = poll.result()
        assert result['location_result'] == True

        # Test 4, location has no body

        def send(request, **kwargs):
            assert request.method == 'GET'

            if request.url == 'http://example.org/location':
                return TestArmPolling.mock_send(
                    'GET',
                    200,
                    body=None
                ).http_response
            elif request.url == 'http://example.org/async_monitor':
                return TestArmPolling.mock_send(
                    'GET',
                    200,
                    body={'status': 'Succeeded'}
                ).http_response
            else:
                pytest.fail("No other query allowed")

        client = pipeline_client_builder(send)

        poll = LROPoller(
            client,
            initial_response,
            deserialization_cb,
            ARMPolling(0, lro_options={"final-state-via": "location"}))
        result = poll.result()
        assert result is None