Exemple #1
0
async def test_long_running_negative():
    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 = async_poller(CLIENT, response, TestArmPolling.mock_outputs,
                        AsyncARMPolling(0))
    with pytest.raises(DecodeError):
        await poll

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

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

    LOCATION_BODY = json.dumps({'name': TEST_NAME})
    POLLING_STATUS = 200
async def test_long_running_negative():
    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 = async_poller(CLIENT, response, TestBasePolling.mock_outputs,
                        AsyncLROBasePolling(0))
    with pytest.raises(DecodeError):
        await poll

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

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

    LOCATION_BODY = json.dumps({'name': TEST_NAME})
    POLLING_STATUS = 200
async def test_post(async_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',
        }, '')

    async 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 = async_pipeline_client_builder(send)

    # LRO options with Location final state
    poll = async_poller(client, initial_response, deserialization_cb,
                        AsyncLROBasePolling(0))
    result = await poll
    assert result['location_result'] == True

    # Location has no body
    async 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 = async_pipeline_client_builder(send)

    poll = async_poller(client, initial_response, deserialization_cb,
                        AsyncLROBasePolling(0))
    result = await poll
    assert result is None
Exemple #4
0
    async def create_certificate(
        self, name: str, policy: Optional[CertificatePolicy] = None, **kwargs: "**Any"
    ) -> Coroutine:
        """Creates a new certificate.

        If this is the first version, the certificate resource is created. This
        operation requires the certificates/create permission.

        :param str name: The name of the certificate.
        :param policy: The management policy for the certificate.
        :type policy:
         ~azure.keyvault.certificates.models.CertificatePolicy
        :returns: A coroutine for the creation of the certificate. Awaiting the coroutine
         returns the created Certificate if creation is successful, the CertificateOperation if not.
        :rtype: coroutine[~azure.keyvault.certificates.models.Certificate or
         ~azure.keyvault.certificates.models.CertificateOperation]
        :raises: :class:`~azure.core.exceptions.HttpResponseError`

        Keyword arguments
            - *enabled (bool)* - Determines whether the object is enabled.
            - *tags (dict[str, str])* - Application specific metadata in the form of key-value pairs.

        Example:
            .. literalinclude:: ../tests/test_examples_certificates_async.py
                :start-after: [START create_certificate]
                :end-before: [END create_certificate]
                :language: python
                :caption: Create a certificate
                :dedent: 8
        """

        enabled = kwargs.pop("enabled", None)
        tags = kwargs.pop('tags', None)

        if enabled is not None:
            attributes = self._client.models.CertificateAttributes(enabled=enabled)
        else:
            attributes = None

        if not policy:
            # pylint: disable=protected-access
            policy = CertificatePolicy._get_default_certificate_policy()
        cert_bundle = await self._client.create_certificate(
            vault_base_url=self.vault_endpoint,
            certificate_name=name,
            certificate_policy=policy._to_certificate_policy_bundle(),
            certificate_attributes=attributes,
            tags=tags,
            **kwargs
        )

        create_certificate_operation = CertificateOperation._from_certificate_operation_bundle(cert_bundle)

        command = partial(self.get_certificate_operation, name=name, **kwargs)

        get_certificate_command = partial(self.get_certificate_with_policy, name=name, **kwargs)

        create_certificate_polling = CreateCertificatePollerAsync(get_certificate_command=get_certificate_command)
        return async_poller(command, create_certificate_operation, None, create_certificate_polling)
    async def close_handles(
            self,
            handle=None,  # type: Union[str, HandleItem]
            recursive=False,  # type: bool
            timeout=None,  # type: Optional[int]
            **kwargs  # type: Any
    ):
        # type: (...) -> Any
        """Close open file handles.

        This operation may not finish with a single call, so a long-running poller
        is returned that can be used to wait until the operation is complete.

        :param handle:
            Optionally, a specific handle to close. The default value is '*'
            which will attempt to close all open handles.
        :type handle: str or ~azure.storage.file.models.Handle
        :param bool recursive:
            Boolean that specifies if operation should apply to the directory specified by the client,
            its files, its subdirectories and their files. Default value is False.
        :param int timeout:
            The timeout parameter is expressed in seconds.
        :returns: A long-running poller to get operation status.
        :rtype: ~azure.core.polling.LROPoller
        """
        try:
            handle_id = handle.id  # type: ignore
        except AttributeError:
            handle_id = handle or '*'
        command = functools.partial(self._client.directory.force_close_handles,
                                    handle_id,
                                    timeout=timeout,
                                    sharesnapshot=self.snapshot,
                                    recursive=recursive,
                                    cls=return_response_headers,
                                    **kwargs)
        try:
            start_close = await command()
        except StorageErrorException as error:
            process_storage_error(error)

        polling_method = CloseHandlesAsync(self._config.copy_polling_interval)
        return async_poller(command, start_close, None, polling_method)
async def test_post(async_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',
            },
            ''
        )

        async 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 = async_pipeline_client_builder(send)

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

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

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

        # Test 4, location has no body

        async 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 = async_pipeline_client_builder(send)

        poll = async_poller(
            client,
            initial_response,
            deserialization_cb,
            AsyncARMPolling(0, lro_options={"final-state-via": "location"}))
        result = await poll
        assert result is None
    async def create_certificate(self,
                                 name: str,
                                 policy: Optional[CertificatePolicy] = None,
                                 enabled: Optional[bool] = None,
                                 tags: Optional[Dict[str, str]] = None,
                                 **kwargs: "**Any") -> CertificateOperation:
        """Creates a new certificate.

        If this is the first version, the certificate resource is created. This
        operation requires the certificates/create permission.

        :param str name: The name of the certificate.
        :param policy: The management policy for the certificate.
        :type policy:
         ~azure.keyvault.certificates.models.CertificatePolicy
        :param bool enabled: Determines whether the object is enabled.
        :param tags: Application specific metadata in the form of key-value pairs.
        :type tags: dict(str, str)
        :returns: The created CertificateOperation
        :rtype: coroutine
        :raises: :class:`~azure.core.exceptions.HttpResponseError`

        Example:
            .. literalinclude:: ../tests/test_examples_certificates_async.py
                :start-after: [START create_certificate]
                :end-before: [END create_certificate]
                :language: python
                :caption: Create a certificate
                :dedent: 8
        """
        if enabled is not None:
            attributes = self._client.models.CertificateAttributes(
                enabled=enabled)
        else:
            attributes = None

        if not policy:
            lifetime_actions = [
                LifetimeAction(days_before_expiry=90, action_type="AutoRenew")
            ]
            policy = CertificatePolicy(key_properties=KeyProperties(
                exportable=True,
                key_type='RSA',
                key_size=2048,
                reuse_key=True,
                key_usage=[
                    KeyUsageType.c_rl_sign, KeyUsageType.data_encipherment,
                    KeyUsageType.digital_signature, KeyUsageType.key_agreement,
                    KeyUsageType.key_cert_sign, KeyUsageType.key_encipherment
                ]),
                                       issuer_name="Self",
                                       lifetime_actions=lifetime_actions,
                                       content_type=SecretContentType.PKCS12,
                                       subject_name="CN=DefaultPolicy",
                                       validity_in_months=12)

        create_certificate_operation = await self._client.create_certificate(
            vault_base_url=self.vault_url,
            certificate_name=name,
            certificate_policy=policy._to_certificate_policy_bundle(),
            certificate_attributes=attributes,
            tags=tags,
            **kwargs)

        command = partial(self._client.get_certificate_operation,
                          vault_base_url=self.vault_url,
                          certificate_name=name,
                          **kwargs)

        create_certificate_polling = CreateCertificatePollerAsync(
            unknown_issuer=(policy.issuer_name.lower() == 'unknown'))
        return async_poller(command,
                            create_certificate_operation.status.lower(), None,
                            create_certificate_polling)