Ejemplo n.º 1
0
class CustomerIntelligenceClient(VssClient):
    """CustomerIntelligence
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """
    def __init__(self, base_url=None, creds=None):
        super(CustomerIntelligenceClient, self).__init__(base_url, creds)
        client_models = {
            k: v
            for k, v in models.__dict__.items() if isinstance(v, type)
        }
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = None

    def publish_events(self, events):
        """PublishEvents.
        [Preview API]
        :param [CustomerIntelligenceEvent] events:
        """
        content = self._serialize.body(events, '[CustomerIntelligenceEvent]')
        self._send(http_method='POST',
                   location_id='b5cc35c2-ff2b-491d-a085-24b6e9f396fd',
                   version='4.0-preview.1',
                   content=content)
Ejemplo n.º 2
0
class ProvenanceClient(Client):
    """Provenance
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """
    def __init__(self, base_url=None, creds=None):
        super(ProvenanceClient, self).__init__(base_url, creds)
        client_models = {
            k: v
            for k, v in models.__dict__.items() if isinstance(v, type)
        }
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = 'b40c1171-807a-493a-8f3f-5c26d5e2f5aa'

    def create_session(self, session_request, protocol):
        """CreateSession.
        [Preview API] Creates a session, a wrapper around a feed that can store additional metadata on the packages published to it.
        :param :class:`<SessionRequest> <azure.devops.v5_1.provenance.models.SessionRequest>` session_request: The feed and metadata for the session
        :param str protocol: The protocol that the session will target
        :rtype: :class:`<SessionResponse> <azure.devops.v5_1.provenance.models.SessionResponse>`
        """
        route_values = {}
        if protocol is not None:
            route_values['protocol'] = self._serialize.url(
                'protocol', protocol, 'str')
        content = self._serialize.body(session_request, 'SessionRequest')
        response = self._send(
            http_method='POST',
            location_id='503b4e54-ebf4-4d04-8eee-21c00823c2ac',
            version='5.1-preview.1',
            route_values=route_values,
            content=content)
        return self._deserialize('SessionResponse', response)
class ClientTraceClient(VssClient):
    """ClientTrace
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """
    def __init__(self, base_url=None, creds=None):
        super(ClientTraceClient, self).__init__(base_url, creds)
        client_models = {
            k: v
            for k, v in models.__dict__.items() if isinstance(v, type)
        }
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = None

    def publish_events(self, events):
        """PublishEvents.
        [Preview API]
        :param [ClientTraceEvent] events:
        """
        content = self._serialize.body(events, '[ClientTraceEvent]')
        self._send(http_method='POST',
                   location_id='06bcc74a-1491-4eb8-a0eb-704778f9d041',
                   version='4.1-preview.1',
                   content=content)
Ejemplo n.º 4
0
class BaseAKSModels:
    """A base class for storing the models used by aks commands.

    The api version of the class corresponding to a model is determined by resource_type.
    """
    def __init__(
        self,
        cmd: AzCommandsLoader,
        resource_type: ResourceType,
    ):
        self.__cmd = cmd
        self.__model_module = None
        self.__model_dict = None
        self.__serializer = None
        self.resource_type = resource_type
        self.__set_up_base_aks_models()

    @property
    def model_module(self) -> ModuleType:
        """Load the module that stores all aks models.

        :return: the models module in SDK
        """
        if self.__model_module is None:
            self.__model_module = self.__cmd.get_models(
                resource_type=self.resource_type,
                operation_group="managed_clusters",
            ).models
        return self.__model_module

    @property
    def models_dict(self) -> Dict[str, Type]:
        """Filter out aks models from the model module and store it as a dictionary with the model name-class as
        the key-value pair.

        :return: dictionary
        """
        if self.__model_dict is None:
            self.__model_dict = {}
            for k, v in vars(self.model_module).items():
                if isinstance(v, type):
                    self.__model_dict[k] = v
        return self.__model_dict

    def __set_up_base_aks_models(self) -> None:
        """Expose all aks models as properties of the class.
        """
        for model_name, model_class in self.models_dict.items():
            setattr(self, model_name, model_class)

    def serialize(self, data: Any, model_type: str) -> Dict:
        """Serialize the data according to the provided model type.

        :return: dictionary
        """
        if self.__serializer is None:
            self.__serializer = Serializer(self.models_dict)
        # will also perfrom client side validation
        return self.__serializer.body(data, model_type)
Ejemplo n.º 5
0
    def luis_result_as_dict(luis_result: LuisResult) -> Dict[str, object]:
        if luis_result is None:
            return None

        client_models = {
            k: v
            for k, v in runtime_models.__dict__.items() if isinstance(v, type)
        }
        serializer = Serializer(client_models)
        result = serializer.body(luis_result, "LuisResult")
        return result
Ejemplo n.º 6
0
    def get_curated_environment(self, scenario, enable_dnn, enable_gpu,
                                compute):
        """
        get automl curated environment for specified configuration
        :param scenario:
        :type scenario: str
        :param enable_dnn:
        :type bool:
        :param enable_gpu:
        :type bool:
        :param compute:
        :type str:
        :return: The environment object.
        :rtype: azureml.core.environment.Environment
        """
        from azureml._restclient.models import EnvironmentDefinition
        from azureml.core import Environment
        from msrest import Serializer

        from .models import AutoMLCuratedEnvInput

        automl_curated_env_input = AutoMLCuratedEnvInput(version=1,
                                                         enable_dnn=enable_dnn,
                                                         enable_gpu=enable_gpu,
                                                         scenario=scenario,
                                                         compute=compute)

        automl_curated_env_output = self._execute_with_experimentid_arguments(
            self._client.jasmine.get_curated_environment,
            automl_curated_env_input)

        # This is a workaround to convert EnvironmentDefinition => azureml.core.Environment
        client_models = {"EnvironmentDefinition": EnvironmentDefinition}
        serializer = Serializer(client_models)
        environment_json = serializer.body(
            automl_curated_env_output.environment, "EnvironmentDefinition")
        environment = Environment._deserialize_and_add_to_object(
            environment_json)

        return environment
def _build_request(endpoint, content_type, events):
    serialize = Serializer()
    header_parameters = {}  # type: Dict[str, Any]
    header_parameters['Content-Type'] = serialize.header(
        "content_type", content_type, 'str')

    query_parameters = {}  # type: Dict[str, Any]
    query_parameters['api-version'] = serialize.query("api_version",
                                                      "2018-01-01", 'str')

    body = serialize.body(events, '[object]')
    if body is None:
        data = None
    else:
        data = json.dumps(body)
        header_parameters['Content-Length'] = str(len(data))

    request = HttpRequest(method="POST",
                          url=endpoint,
                          headers=header_parameters,
                          data=data)
    request.format_parameters(query_parameters)
    return request
Ejemplo n.º 8
0
class EditorService(object):
    """The Editor service leverages state of the art natural language components, such as spelling and grammar, to provide advanced proofing support through different REST APIs using the Azure infrastructure. You can find out more about editor service at [http://aka.ms/editorservice](http://aka.ms/editorservice).
    Explore this specification through a user-friendly UI [here](http://aka.ms/editorservice/swagger).
    ### Environments
     | Type       | Link                                 |
     |------------|--------------------------------------|
     | Int        | https://nleditor.osi.office-int.net/ |
     | EDog       | https://nleditor.osi.officeppe.net   |
     | Production | https://nleditor.osi.office.net      |

    :ivar config: Configuration for client.
    :vartype config: EditorServiceConfiguration

    :param x_correlation_id: Generated by the client and checked for validity.
     If non empty and valid, use as the telemetry log Correlation ID. Else,
     generate a new GUID (use this instead of the RequestId).
    :type x_correlation_id: str
    :param x_user_session_id: Generated by the client to track the user
     session Id.
    :type x_user_session_id: str
    :param x_user_id: Generated by the client to track the user Id.
    :type x_user_id: str
    :param str base_url: Service URL
    """
    def __init__(self,
                 x_correlation_id=None,
                 x_user_session_id=None,
                 x_user_id=None,
                 base_url=None):

        self.config = EditorServiceConfiguration(x_correlation_id,
                                                 x_user_session_id, x_user_id,
                                                 base_url)
        self._client = ServiceClient(None, self.config)

        client_models = {
            k: v
            for k, v in models.__dict__.items() if isinstance(v, type)
        }
        self.api_version = '1.0.0'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    def post_check(self,
                   body,
                   custom_headers=None,
                   raw=False,
                   **operation_config):
        """Check text not previously tagged; can provide better suggestions
        (CloudSuggest).

        :param body: Check API request V1
        :type body:
         ~microsoft.swagger.codegen.editorservice.models.CheckRequestV1
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: CheckResponseV1 or ClientRawResponse if raw=true
        :rtype:
         ~microsoft.swagger.codegen.editorservice.models.CheckResponseV1 or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.post_check.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.x_correlation_id is not None:
            header_parameters['X-CorrelationId'] = self._serialize.header(
                "self.config.x_correlation_id", self.config.x_correlation_id,
                'str')
        if self.config.x_user_session_id is not None:
            header_parameters['X-UserSessionId'] = self._serialize.header(
                "self.config.x_user_session_id", self.config.x_user_session_id,
                'str')
        if self.config.x_user_id is not None:
            header_parameters['X-UserId'] = self._serialize.header(
                "self.config.x_user_id", self.config.x_user_id, 'str')

        # Construct body
        body_content = self._serialize.body(body, 'CheckRequestV1')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request,
                                     header_parameters,
                                     body_content,
                                     stream=False,
                                     **operation_config)

        if response.status_code not in [200, 400, 500]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None
        header_dict = {}

        if response.status_code == 200:
            deserialized = self._deserialize('CheckResponseV1', response)
            header_dict = {
                'X-CorrelationId': 'str',
            }

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            client_raw_response.add_headers(header_dict)
            return client_raw_response

        return deserialized

    post_check.metadata = {'url': '/Check/V1'}

    def get_check(self,
                  app_id,
                  text,
                  language_id,
                  app_version=None,
                  descriptors0_name=None,
                  descriptors0_value=None,
                  descriptors1_name=None,
                  descriptors1_value=None,
                  language_ux_id=None,
                  run_on_profile_id=None,
                  length=None,
                  start=None,
                  request_id=None,
                  text_unit=None,
                  custom_headers=None,
                  raw=False,
                  **operation_config):
        """Check text not previously tagged; can provide better suggestions
        (CloudSuggest).

        Documented for the sake of completeness. Using the GET method is not
        recommended as it is very cumbersome to describe arrays of complex
        objects such as Descriptors or CliengSuggestions in the query string.
        .

        :param app_id: Id of the calling app, the supported ones are the
         following:
         * LinkedIn
         * NLServiceTestAutomation - Id used by automated tests
         * OAM - Id used by the probes
         * OneNote_Online, PowerPoint_Online, Word_Online - WAC
         * Testing_Client - Use for testing and prototyping
         . Possible values include: 'LinkedIn', 'NLServiceTestAutomation',
         'OAM', 'OneNote_Online', 'Testing_Client', 'PowerPoint_Online',
         'Word_Online'
        :type app_id: str
        :param text: Text to be checked.
        :type text: str
        :param language_id:
        :type language_id: str
        :param app_version: Version of the calling application.
        :type app_version: str
        :param descriptors0_name: Name of descriptor at index 0.
        :type descriptors0_name: str
        :param descriptors0_value: Value of descriptor at index 0.
        :type descriptors0_value: str
        :param descriptors1_name: Name of descriptor at index 1.
        :type descriptors1_name: str
        :param descriptors1_value: Value of descriptor at index 1.
        :type descriptors1_value: str
        :param language_ux_id: User current UX language ISO ID. Example: fr-fr
         for French (France) Default: the LanguageId (Not supported yet!)."
        :type language_ux_id: str
        :param run_on_profile_id: Profile ID assigned by NLX team. The default
         is the one selected for the specified AppID. Contact NLX team for more
         details.
        :type run_on_profile_id: str
        :param length: Length of the text to be checked. Default: The entire
         content of Text.
        :type length: int
        :param start: Init index for the text to be checked.
        :type start: int
        :param request_id: Unique call identifier generated by the caller.
         Deprecated - use X-CorrelationId instead.
        :type request_id: str
        :param text_unit: Unit(s) of text flags:
         * Default = 0x0000, // Default value
         * Word = 0x0001, // Unigram
         * Phrase = 0x0002, // 7-gram
         * Sentence = 0x0004, // Linguistically accurate sentence
         * Paragraph = 0x0008, // Text terminated by paragraph marker(s)
         * Page = 0x0010, // A visible page, slide, equivalent unit.
         * Section = 0x0020, // Section of document/presentation
         * Chapter = 0x0040, // Chapter if such a concept exists in model
         * Document = 0x0100, // Full document contents.
         * RawChars = 0x4000, // Special purpose for scenarios that need raw
         content access
         . Possible values include: 'Default', 'Word', 'Phrase', 'Sentence',
         'Paragraph', 'Page', 'Section', 'Chapter', 'Document', 'RawChars'
        :type text_unit: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: CheckResponseV1 or ClientRawResponse if raw=true
        :rtype:
         ~microsoft.swagger.codegen.editorservice.models.CheckResponseV1 or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.get_check.metadata['url']

        # Construct parameters
        query_parameters = {}
        query_parameters['AppId'] = self._serialize.query(
            "app_id", app_id, 'str')
        query_parameters['Text'] = self._serialize.query("text", text, 'str')
        query_parameters['LanguageId'] = self._serialize.query(
            "language_id", language_id, 'str')
        if app_version is not None:
            query_parameters['AppVersion'] = self._serialize.query(
                "app_version", app_version, 'str')
        if descriptors0_name is not None:
            query_parameters['Descriptors[0].Name'] = self._serialize.query(
                "descriptors0_name", descriptors0_name, 'str')
        if descriptors0_value is not None:
            query_parameters['Descriptors[0].Value'] = self._serialize.query(
                "descriptors0_value", descriptors0_value, 'str')
        if descriptors1_name is not None:
            query_parameters['Descriptors[1].Name'] = self._serialize.query(
                "descriptors1_name", descriptors1_name, 'str')
        if descriptors1_value is not None:
            query_parameters['Descriptors[1].Value'] = self._serialize.query(
                "descriptors1_value", descriptors1_value, 'str')
        if language_ux_id is not None:
            query_parameters['LanguageUXId'] = self._serialize.query(
                "language_ux_id", language_ux_id, 'str')
        if run_on_profile_id is not None:
            query_parameters['RunOnProfileId'] = self._serialize.query(
                "run_on_profile_id", run_on_profile_id, 'str')
        if length is not None:
            query_parameters['Length'] = self._serialize.query(
                "length", length, 'int')
        if start is not None:
            query_parameters['Start'] = self._serialize.query(
                "start", start, 'int')
        if request_id is not None:
            query_parameters['RequestId'] = self._serialize.query(
                "request_id", request_id, 'str')
        if text_unit is not None:
            query_parameters['TextUnit'] = self._serialize.query(
                "text_unit", text_unit, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.x_correlation_id is not None:
            header_parameters['X-CorrelationId'] = self._serialize.header(
                "self.config.x_correlation_id", self.config.x_correlation_id,
                'str')
        if self.config.x_user_session_id is not None:
            header_parameters['X-UserSessionId'] = self._serialize.header(
                "self.config.x_user_session_id", self.config.x_user_session_id,
                'str')
        if self.config.x_user_id is not None:
            header_parameters['X-UserId'] = self._serialize.header(
                "self.config.x_user_id", self.config.x_user_id, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request,
                                     header_parameters,
                                     stream=False,
                                     **operation_config)

        if response.status_code not in [200, 400, 500]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None
        header_dict = {}

        if response.status_code == 200:
            deserialized = self._deserialize('CheckResponseV1', response)
            header_dict = {
                'X-CorrelationId': 'str',
            }

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            client_raw_response.add_headers(header_dict)
            return client_raw_response

        return deserialized

    get_check.metadata = {'url': '/Check/V1'}

    def post_tile_check(self,
                        body,
                        custom_headers=None,
                        raw=False,
                        **operation_config):
        """Checks a part of document represented as list of tiles.

        "Can provide additional analyses on higher than paragraph level in
        comparison with Check api; In the same way as check api it can provide
        better suggestions (CloudSuggest)"
        .

        :param body: TileCheck API request V1
        :type body:
         ~microsoft.swagger.codegen.editorservice.models.TileCheckRequestV1
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: TileCheckResponseV1 or ClientRawResponse if raw=true
        :rtype:
         ~microsoft.swagger.codegen.editorservice.models.TileCheckResponseV1 or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.post_tile_check.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.x_correlation_id is not None:
            header_parameters['X-CorrelationId'] = self._serialize.header(
                "self.config.x_correlation_id", self.config.x_correlation_id,
                'str')
        if self.config.x_user_session_id is not None:
            header_parameters['X-UserSessionId'] = self._serialize.header(
                "self.config.x_user_session_id", self.config.x_user_session_id,
                'str')
        if self.config.x_user_id is not None:
            header_parameters['X-UserId'] = self._serialize.header(
                "self.config.x_user_id", self.config.x_user_id, 'str')

        # Construct body
        body_content = self._serialize.body(body, 'TileCheckRequestV1')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request,
                                     header_parameters,
                                     body_content,
                                     stream=False,
                                     **operation_config)

        if response.status_code not in [200, 400, 500]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None
        header_dict = {}

        if response.status_code == 200:
            deserialized = self._deserialize('TileCheckResponseV1', response)
            header_dict = {
                'X-CorrelationId': 'str',
            }

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            client_raw_response.add_headers(header_dict)
            return client_raw_response

        return deserialized

    post_tile_check.metadata = {'url': '/TileCheck/V1'}

    def config_v1(self,
                  body,
                  custom_headers=None,
                  raw=False,
                  **operation_config):
        """Fetch all the available profiles and critique categories and types for
        a particular language.

        This API is designed to fetch all the available profiles and critique
        categories types for a particular language and some factors defined in
        the Descriptors (i.e. haveSubscriptionLicense, audience).
        * The Config API only supports fetching the information for only one
        language at a time. If it is required to pre-fetch critique type
        information for multiple languages, it is recommended to send multiple
        calls in parallel.
        * All Available critique type values are inherited from Win32
        Grammar&More writing styles. Please contact us to modify the default
        behaviors.
        ### Scenarios
        * Whenever the client wants to draw the proofing option dialog with a
        drop down menu with the supported profiles, where the customer can turn
        on/off critique types, the Config API would be called to fetch all the
        required info to draw the dialog.
        * Once the customer changes the proofing language from one to another,
        another Config API would be required for the new language, if it is not
        pre-fetched and cached.
        .

        :param body: Config API request V1
        :type body:
         ~microsoft.swagger.codegen.editorservice.models.ConfigRequestV1
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ConfigResponseV1 or ClientRawResponse if raw=true
        :rtype:
         ~microsoft.swagger.codegen.editorservice.models.ConfigResponseV1 or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.config_v1.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.x_correlation_id is not None:
            header_parameters['X-CorrelationId'] = self._serialize.header(
                "self.config.x_correlation_id", self.config.x_correlation_id,
                'str')
        if self.config.x_user_session_id is not None:
            header_parameters['X-UserSessionId'] = self._serialize.header(
                "self.config.x_user_session_id", self.config.x_user_session_id,
                'str')
        if self.config.x_user_id is not None:
            header_parameters['X-UserId'] = self._serialize.header(
                "self.config.x_user_id", self.config.x_user_id, 'str')

        # Construct body
        body_content = self._serialize.body(body, 'ConfigRequestV1')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request,
                                     header_parameters,
                                     body_content,
                                     stream=False,
                                     **operation_config)

        if response.status_code not in [200, 400, 500]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None
        header_dict = {}

        if response.status_code == 200:
            deserialized = self._deserialize('ConfigResponseV1', response)
            header_dict = {
                'X-CorrelationId': 'str',
            }

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            client_raw_response.add_headers(header_dict)
            return client_raw_response

        return deserialized

    config_v1.metadata = {'url': '/Config/V1'}

    def config_v2(self,
                  body,
                  custom_headers=None,
                  raw=False,
                  **operation_config):
        """Fetch all the available critique types for a particular language and
        Profile ID.

        This API is designed to fetch all the available critique types for a
        particular language and Profile ID and some factors defined in the
        Descriptors (i.e. haveSubscriptionLicense, audience).
        * The Config API only supports fetching the information for only one
        language at a time. If it is required to pre-fetch critique type
        information for multiple languages, it is recommended to send multiple
        calls in parallel.
        * All Available critique type values are inherited from Win32
        Grammar&More writing styles. Please contact us to modify the default
        behaviors.
        ### Scenarios
        * Whenever the client wants to draw the proofing option dialog, where
        the customer can turn on/off critique types, the Config API would be
        called to fetch all the required info to draw the dialog.
        * Once the customer changes the proofing language from one to another,
        another Config API would be required for the new language, if it is not
        pre-fetched and cached.
        .

        :param body: Config API request V2
        :type body:
         ~microsoft.swagger.codegen.editorservice.models.ConfigRequestV2
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ConfigResponseV2 or ClientRawResponse if raw=true
        :rtype:
         ~microsoft.swagger.codegen.editorservice.models.ConfigResponseV2 or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.config_v2.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.x_correlation_id is not None:
            header_parameters['X-CorrelationId'] = self._serialize.header(
                "self.config.x_correlation_id", self.config.x_correlation_id,
                'str')
        if self.config.x_user_session_id is not None:
            header_parameters['X-UserSessionId'] = self._serialize.header(
                "self.config.x_user_session_id", self.config.x_user_session_id,
                'str')
        if self.config.x_user_id is not None:
            header_parameters['X-UserId'] = self._serialize.header(
                "self.config.x_user_id", self.config.x_user_id, 'str')

        # Construct body
        body_content = self._serialize.body(body, 'ConfigRequestV2')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request,
                                     header_parameters,
                                     body_content,
                                     stream=False,
                                     **operation_config)

        if response.status_code not in [200, 400, 500]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None
        header_dict = {}

        if response.status_code == 200:
            deserialized = self._deserialize('ConfigResponseV2', response)
            header_dict = {
                'X-CorrelationId': 'str',
            }

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            client_raw_response.add_headers(header_dict)
            return client_raw_response

        return deserialized

    config_v2.metadata = {'url': '/Config/V2'}

    def languageinfo(self,
                     body,
                     custom_headers=None,
                     raw=False,
                     **operation_config):
        """Load the language support for the client given the UX language.

        Load the language support for the client given the UX language. This
        API will pass all the info on the language list including the localized
        strings to render in the UI Example:
        * French (France) - Post reform
        * French (France) - Pre reform
        * French (France) - Both reforms
        ### Scenarios
        When initialized/launched, the app makes a service call requesting the
        list of available language for the current UX language ID, the selected
        editing language (if only one language is required). Service replies
        with the info on the supported languages or on the specific language.
        .

        :param body: Language Info API request V1
        :type body:
         ~microsoft.swagger.codegen.editorservice.models.LanguageInfoRequestV1
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: LanguageInfoResponseV1 or ClientRawResponse if raw=true
        :rtype:
         ~microsoft.swagger.codegen.editorservice.models.LanguageInfoResponseV1
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.languageinfo.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.x_correlation_id is not None:
            header_parameters['X-CorrelationId'] = self._serialize.header(
                "self.config.x_correlation_id", self.config.x_correlation_id,
                'str')
        if self.config.x_user_session_id is not None:
            header_parameters['X-UserSessionId'] = self._serialize.header(
                "self.config.x_user_session_id", self.config.x_user_session_id,
                'str')
        if self.config.x_user_id is not None:
            header_parameters['X-UserId'] = self._serialize.header(
                "self.config.x_user_id", self.config.x_user_id, 'str')

        # Construct body
        body_content = self._serialize.body(body, 'LanguageInfoRequestV1')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request,
                                     header_parameters,
                                     body_content,
                                     stream=False,
                                     **operation_config)

        if response.status_code not in [200, 400, 500]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None
        header_dict = {}

        if response.status_code == 200:
            deserialized = self._deserialize('LanguageInfoResponseV1',
                                             response)
            header_dict = {
                'X-CorrelationId': 'str',
            }

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            client_raw_response.add_headers(header_dict)
            return client_raw_response

        return deserialized

    languageinfo.metadata = {'url': '/LanguageInfo/V1'}

    def instrumentation(self,
                        body,
                        custom_headers=None,
                        raw=False,
                        **operation_config):
        """Report the user action on a critique.

        ### Scenarios
        * User ignores the critique
        * User accepts the critique suggestion
        .

        :param body: Instrumentation API request V1
        :type body:
         ~microsoft.swagger.codegen.editorservice.models.InstrumentationRequestV1
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.instrumentation.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.x_correlation_id is not None:
            header_parameters['X-CorrelationId'] = self._serialize.header(
                "self.config.x_correlation_id", self.config.x_correlation_id,
                'str')
        if self.config.x_user_session_id is not None:
            header_parameters['X-UserSessionId'] = self._serialize.header(
                "self.config.x_user_session_id", self.config.x_user_session_id,
                'str')
        if self.config.x_user_id is not None:
            header_parameters['X-UserId'] = self._serialize.header(
                "self.config.x_user_id", self.config.x_user_id, 'str')

        # Construct body
        body_content = self._serialize.body(body, 'InstrumentationRequestV1')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request,
                                     header_parameters,
                                     body_content,
                                     stream=False,
                                     **operation_config)

        if response.status_code not in [200, 400, 500]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            client_raw_response.add_headers({
                'X-CorrelationId': 'str',
            })
            return client_raw_response

    instrumentation.metadata = {'url': '/Instrumentation/V1'}
Ejemplo n.º 9
0
class NpmClient(VssClient):
    """Npm
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """

    def __init__(self, base_url=None, creds=None):
        super(NpmClient, self).__init__(base_url, creds)
        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = '4c83cfc1-f33a-477e-a789-29d38ffca52e'

    def get_content_scoped_package(self, feed_id, package_scope, unscoped_package_name, package_version):
        """GetContentScopedPackage.
        [Preview API]
        :param str feed_id:
        :param str package_scope:
        :param str unscoped_package_name:
        :param str package_version:
        :rtype: object
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_scope is not None:
            route_values['packageScope'] = self._serialize.url('package_scope', package_scope, 'str')
        if unscoped_package_name is not None:
            route_values['unscopedPackageName'] = self._serialize.url('unscoped_package_name', unscoped_package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        response = self._send(http_method='GET',
                              location_id='09a4eafd-123a-495c-979c-0eda7bdb9a14',
                              version='4.1-preview.1',
                              route_values=route_values)
        return self._deserialize('object', response)

    def get_content_unscoped_package(self, feed_id, package_name, package_version):
        """GetContentUnscopedPackage.
        [Preview API]
        :param str feed_id:
        :param str package_name:
        :param str package_version:
        :rtype: object
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_name is not None:
            route_values['packageName'] = self._serialize.url('package_name', package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        response = self._send(http_method='GET',
                              location_id='75caa482-cb1e-47cd-9f2c-c048a4b7a43e',
                              version='4.1-preview.1',
                              route_values=route_values)
        return self._deserialize('object', response)

    def update_packages(self, batch_request, feed_id):
        """UpdatePackages.
        [Preview API] Update several packages from a single feed in a single request. The updates to the packages do not happen atomically.
        :param :class:`<NpmPackagesBatchRequest> <npm.v4_1.models.NpmPackagesBatchRequest>` batch_request: Information about the packages to update, the operation to perform, and its associated data.
        :param str feed_id: Feed which contains the packages to update.
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        content = self._serialize.body(batch_request, 'NpmPackagesBatchRequest')
        self._send(http_method='POST',
                   location_id='06f34005-bbb2-41f4-88f5-23e03a99bb12',
                   version='4.1-preview.1',
                   route_values=route_values,
                   content=content)

    def get_readme_scoped_package(self, feed_id, package_scope, unscoped_package_name, package_version):
        """GetReadmeScopedPackage.
        [Preview API]
        :param str feed_id:
        :param str package_scope:
        :param str unscoped_package_name:
        :param str package_version:
        :rtype: object
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_scope is not None:
            route_values['packageScope'] = self._serialize.url('package_scope', package_scope, 'str')
        if unscoped_package_name is not None:
            route_values['unscopedPackageName'] = self._serialize.url('unscoped_package_name', unscoped_package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        response = self._send(http_method='GET',
                              location_id='6d4db777-7e4a-43b2-afad-779a1d197301',
                              version='4.1-preview.1',
                              route_values=route_values)
        return self._deserialize('object', response)

    def get_readme_unscoped_package(self, feed_id, package_name, package_version):
        """GetReadmeUnscopedPackage.
        [Preview API]
        :param str feed_id:
        :param str package_name:
        :param str package_version:
        :rtype: object
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_name is not None:
            route_values['packageName'] = self._serialize.url('package_name', package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        response = self._send(http_method='GET',
                              location_id='1099a396-b310-41d4-a4b6-33d134ce3fcf',
                              version='4.1-preview.1',
                              route_values=route_values)
        return self._deserialize('object', response)

    def delete_scoped_package_version_from_recycle_bin(self, feed_id, package_scope, unscoped_package_name, package_version):
        """DeleteScopedPackageVersionFromRecycleBin.
        [Preview API]
        :param str feed_id:
        :param str package_scope:
        :param str unscoped_package_name:
        :param str package_version:
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_scope is not None:
            route_values['packageScope'] = self._serialize.url('package_scope', package_scope, 'str')
        if unscoped_package_name is not None:
            route_values['unscopedPackageName'] = self._serialize.url('unscoped_package_name', unscoped_package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        self._send(http_method='DELETE',
                   location_id='220f45eb-94a5-432c-902a-5b8c6372e415',
                   version='4.1-preview.1',
                   route_values=route_values)

    def get_scoped_package_version_metadata_from_recycle_bin(self, feed_id, package_scope, unscoped_package_name, package_version):
        """GetScopedPackageVersionMetadataFromRecycleBin.
        [Preview API]
        :param str feed_id:
        :param str package_scope:
        :param str unscoped_package_name:
        :param str package_version:
        :rtype: :class:`<NpmPackageVersionDeletionState> <npm.v4_1.models.NpmPackageVersionDeletionState>`
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_scope is not None:
            route_values['packageScope'] = self._serialize.url('package_scope', package_scope, 'str')
        if unscoped_package_name is not None:
            route_values['unscopedPackageName'] = self._serialize.url('unscoped_package_name', unscoped_package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        response = self._send(http_method='GET',
                              location_id='220f45eb-94a5-432c-902a-5b8c6372e415',
                              version='4.1-preview.1',
                              route_values=route_values)
        return self._deserialize('NpmPackageVersionDeletionState', response)

    def restore_scoped_package_version_from_recycle_bin(self, package_version_details, feed_id, package_scope, unscoped_package_name, package_version):
        """RestoreScopedPackageVersionFromRecycleBin.
        [Preview API]
        :param :class:`<NpmRecycleBinPackageVersionDetails> <npm.v4_1.models.NpmRecycleBinPackageVersionDetails>` package_version_details:
        :param str feed_id:
        :param str package_scope:
        :param str unscoped_package_name:
        :param str package_version:
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_scope is not None:
            route_values['packageScope'] = self._serialize.url('package_scope', package_scope, 'str')
        if unscoped_package_name is not None:
            route_values['unscopedPackageName'] = self._serialize.url('unscoped_package_name', unscoped_package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        content = self._serialize.body(package_version_details, 'NpmRecycleBinPackageVersionDetails')
        self._send(http_method='PATCH',
                   location_id='220f45eb-94a5-432c-902a-5b8c6372e415',
                   version='4.1-preview.1',
                   route_values=route_values,
                   content=content)

    def delete_package_version_from_recycle_bin(self, feed_id, package_name, package_version):
        """DeletePackageVersionFromRecycleBin.
        [Preview API]
        :param str feed_id:
        :param str package_name:
        :param str package_version:
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_name is not None:
            route_values['packageName'] = self._serialize.url('package_name', package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        self._send(http_method='DELETE',
                   location_id='63a4f31f-e92b-4ee4-bf92-22d485e73bef',
                   version='4.1-preview.1',
                   route_values=route_values)

    def get_package_version_metadata_from_recycle_bin(self, feed_id, package_name, package_version):
        """GetPackageVersionMetadataFromRecycleBin.
        [Preview API]
        :param str feed_id:
        :param str package_name:
        :param str package_version:
        :rtype: :class:`<NpmPackageVersionDeletionState> <npm.v4_1.models.NpmPackageVersionDeletionState>`
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_name is not None:
            route_values['packageName'] = self._serialize.url('package_name', package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        response = self._send(http_method='GET',
                              location_id='63a4f31f-e92b-4ee4-bf92-22d485e73bef',
                              version='4.1-preview.1',
                              route_values=route_values)
        return self._deserialize('NpmPackageVersionDeletionState', response)

    def restore_package_version_from_recycle_bin(self, package_version_details, feed_id, package_name, package_version):
        """RestorePackageVersionFromRecycleBin.
        [Preview API]
        :param :class:`<NpmRecycleBinPackageVersionDetails> <npm.v4_1.models.NpmRecycleBinPackageVersionDetails>` package_version_details:
        :param str feed_id:
        :param str package_name:
        :param str package_version:
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_name is not None:
            route_values['packageName'] = self._serialize.url('package_name', package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        content = self._serialize.body(package_version_details, 'NpmRecycleBinPackageVersionDetails')
        self._send(http_method='PATCH',
                   location_id='63a4f31f-e92b-4ee4-bf92-22d485e73bef',
                   version='4.1-preview.1',
                   route_values=route_values,
                   content=content)

    def get_scoped_package_info(self, feed_id, package_scope, unscoped_package_name, package_version):
        """GetScopedPackageInfo.
        [Preview API]
        :param str feed_id:
        :param str package_scope:
        :param str unscoped_package_name:
        :param str package_version:
        :rtype: :class:`<Package> <npm.v4_1.models.Package>`
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_scope is not None:
            route_values['packageScope'] = self._serialize.url('package_scope', package_scope, 'str')
        if unscoped_package_name is not None:
            route_values['unscopedPackageName'] = self._serialize.url('unscoped_package_name', unscoped_package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        response = self._send(http_method='GET',
                              location_id='e93d9ec3-4022-401e-96b0-83ea5d911e09',
                              version='4.1-preview.1',
                              route_values=route_values)
        return self._deserialize('Package', response)

    def unpublish_scoped_package(self, feed_id, package_scope, unscoped_package_name, package_version):
        """UnpublishScopedPackage.
        [Preview API]
        :param str feed_id:
        :param str package_scope:
        :param str unscoped_package_name:
        :param str package_version:
        :rtype: :class:`<Package> <npm.v4_1.models.Package>`
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_scope is not None:
            route_values['packageScope'] = self._serialize.url('package_scope', package_scope, 'str')
        if unscoped_package_name is not None:
            route_values['unscopedPackageName'] = self._serialize.url('unscoped_package_name', unscoped_package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        response = self._send(http_method='DELETE',
                              location_id='e93d9ec3-4022-401e-96b0-83ea5d911e09',
                              version='4.1-preview.1',
                              route_values=route_values)
        return self._deserialize('Package', response)

    def update_scoped_package(self, package_version_details, feed_id, package_scope, unscoped_package_name, package_version):
        """UpdateScopedPackage.
        [Preview API]
        :param :class:`<PackageVersionDetails> <npm.v4_1.models.PackageVersionDetails>` package_version_details:
        :param str feed_id:
        :param str package_scope:
        :param str unscoped_package_name:
        :param str package_version:
        :rtype: :class:`<Package> <npm.v4_1.models.Package>`
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_scope is not None:
            route_values['packageScope'] = self._serialize.url('package_scope', package_scope, 'str')
        if unscoped_package_name is not None:
            route_values['unscopedPackageName'] = self._serialize.url('unscoped_package_name', unscoped_package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        content = self._serialize.body(package_version_details, 'PackageVersionDetails')
        response = self._send(http_method='PATCH',
                              location_id='e93d9ec3-4022-401e-96b0-83ea5d911e09',
                              version='4.1-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('Package', response)

    def get_package_info(self, feed_id, package_name, package_version):
        """GetPackageInfo.
        [Preview API]
        :param str feed_id:
        :param str package_name:
        :param str package_version:
        :rtype: :class:`<Package> <npm.v4_1.models.Package>`
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_name is not None:
            route_values['packageName'] = self._serialize.url('package_name', package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        response = self._send(http_method='GET',
                              location_id='ed579d62-67c9-4271-be66-9b029af5bcf9',
                              version='4.1-preview.1',
                              route_values=route_values)
        return self._deserialize('Package', response)

    def unpublish_package(self, feed_id, package_name, package_version):
        """UnpublishPackage.
        [Preview API]
        :param str feed_id:
        :param str package_name:
        :param str package_version:
        :rtype: :class:`<Package> <npm.v4_1.models.Package>`
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_name is not None:
            route_values['packageName'] = self._serialize.url('package_name', package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        response = self._send(http_method='DELETE',
                              location_id='ed579d62-67c9-4271-be66-9b029af5bcf9',
                              version='4.1-preview.1',
                              route_values=route_values)
        return self._deserialize('Package', response)

    def update_package(self, package_version_details, feed_id, package_name, package_version):
        """UpdatePackage.
        [Preview API]
        :param :class:`<PackageVersionDetails> <npm.v4_1.models.PackageVersionDetails>` package_version_details:
        :param str feed_id:
        :param str package_name:
        :param str package_version:
        :rtype: :class:`<Package> <npm.v4_1.models.Package>`
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
        if package_name is not None:
            route_values['packageName'] = self._serialize.url('package_name', package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
        content = self._serialize.body(package_version_details, 'PackageVersionDetails')
        response = self._send(http_method='PATCH',
                              location_id='ed579d62-67c9-4271-be66-9b029af5bcf9',
                              version='4.1-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('Package', response)
Ejemplo n.º 10
0
class TestRuntimeSerialized(unittest.TestCase):
    class TestObj(Model):

        _validation = {}
        _attribute_map = {
            'attr_a': {
                'key': 'id',
                'type': 'str'
            },
            'attr_b': {
                'key': 'AttrB',
                'type': 'int'
            },
            'attr_c': {
                'key': 'Key_C',
                'type': 'bool'
            },
            'attr_d': {
                'key': 'AttrD',
                'type': '[int]'
            },
            'attr_e': {
                'key': 'AttrE',
                'type': '{float}'
            }
        }

        def __init__(self):

            self.attr_a = None
            self.attr_b = None
            self.attr_c = None
            self.attr_d = None
            self.attr_e = None

        def __str__(self):
            return "Test_Object"

    def setUp(self):
        self.s = Serializer()
        return super(TestRuntimeSerialized, self).setUp()

    def test_validate(self):
        # Assert not necessary, should not raise exception
        self.s.validate("simplestring", "StringForLog", pattern="^[a-z]+$")
        self.s.validate(u"UTF8ééééé", "StringForLog", pattern=r"^[\w]+$")

    def test_obj_serialize_none(self):
        """Test that serialize None in object is still None.
        """
        obj = self.s.serialize_object({'test': None})
        self.assertIsNone(obj['test'])

    def test_obj_without_attr_map(self):
        """
        Test serializing an object with no attribute_map.
        """
        test_obj = type("BadTestObj", (), {})

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

    def test_obj_with_malformed_map(self):
        """
        Test serializing an object with a malformed attribute_map.
        """
        test_obj = type("BadTestObj", (Model, ), {"_attribute_map": None})

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

        test_obj._attribute_map = {"attr": "val"}

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

        test_obj._attribute_map = {"attr": {"val": 1}}

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

    def test_obj_with_mismatched_map(self):
        """
        Test serializing an object with mismatching attributes and map.
        """
        test_obj = type("BadTestObj", (Model, ), {"_attribute_map": None})
        test_obj._attribute_map = {"abc": {"key": "ABC", "type": "str"}}

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

    def test_attr_none(self):
        """
        Test serializing an object with None attributes.
        """
        test_obj = self.TestObj()
        message = self.s._serialize(test_obj)

        self.assertIsInstance(message, dict)
        self.assertFalse('id' in message)

    def test_attr_int(self):
        """
        Test serializing an object with Int attributes.
        """
        test_obj = self.TestObj()
        self.TestObj._validation = {
            'attr_b': {
                'required': True
            },
        }
        test_obj.attr_b = None

        with self.assertRaises(ValidationError):
            self.s._serialize(test_obj)

        test_obj.attr_b = 25

        message = self.s._serialize(test_obj)
        self.assertEqual(message['AttrB'], int(test_obj.attr_b))

        test_obj.attr_b = "34534"

        message = self.s._serialize(test_obj)
        self.assertEqual(message['AttrB'], int(test_obj.attr_b))

        test_obj.attr_b = "NotANumber"

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

        self.TestObj._validation = {}

    def test_attr_str(self):
        """
        Test serializing an object with Str attributes.
        """
        test_obj = self.TestObj()
        self.TestObj._validation = {
            'attr_a': {
                'required': True
            },
        }
        test_obj.attr_a = None

        with self.assertRaises(ValidationError):
            self.s._serialize(test_obj)

        self.TestObj._validation = {}
        test_obj.attr_a = "TestString"

        message = self.s._serialize(test_obj)
        self.assertEqual(message['id'], str(test_obj.attr_a))

        test_obj.attr_a = 1234

        message = self.s._serialize(test_obj)
        self.assertEqual(message['id'], str(test_obj.attr_a))

        test_obj.attr_a = list()

        message = self.s._serialize(test_obj)
        self.assertEqual(message['id'], str(test_obj.attr_a))

        test_obj.attr_a = [1]

        message = self.s._serialize(test_obj)
        self.assertEqual(message['id'], str(test_obj.attr_a))

    def test_attr_bool(self):
        """
        Test serializing an object with bool attributes.
        """
        test_obj = self.TestObj()
        test_obj.attr_c = True

        message = self.s._serialize(test_obj)
        self.assertEqual(message['Key_C'], True)

        test_obj.attr_c = ""

        message = self.s._serialize(test_obj)
        self.assertTrue('Key_C' in message)

        test_obj.attr_c = None

        message = self.s._serialize(test_obj)
        self.assertFalse('Key_C' in message)

        test_obj.attr_c = "NotEmpty"

        message = self.s._serialize(test_obj)
        self.assertEqual(message['Key_C'], True)

    def test_attr_sequence(self):
        """
        Test serializing a sequence.
        """

        test_obj = ["A", "B", "C"]
        output = self.s._serialize(test_obj, '[str]', div='|')
        self.assertEqual(output, "|".join(test_obj))

        test_obj = [1, 2, 3]
        output = self.s._serialize(test_obj, '[str]', div=',')
        self.assertEqual(output, ",".join([str(i) for i in test_obj]))

    def test_attr_list_simple(self):
        """
        Test serializing an object with simple-typed list attributes
        """
        test_obj = self.TestObj()
        test_obj.attr_d = []

        message = self.s._serialize(test_obj)
        self.assertEqual(message['AttrD'], test_obj.attr_d)

        test_obj.attr_d = [1, 2, 3]

        message = self.s._serialize(test_obj)
        self.assertEqual(message['AttrD'], test_obj.attr_d)

        test_obj.attr_d = ["1", "2", "3"]

        message = self.s._serialize(test_obj)
        self.assertEqual(message['AttrD'], [int(i) for i in test_obj.attr_d])

        test_obj.attr_d = ["test", "test2", "test3"]

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

        test_obj.attr_d = "NotAList"

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

    def test_empty_list(self):

        input = []
        output = self.s._serialize(input, '[str]')
        self.assertEqual(output, input)

    def test_attr_list_complex(self):
        """
        Test serializing an object with a list of complex objects as an attribute.
        """
        list_obj = type("ListObj", (Model, ), {
            "_attribute_map": None,
            "_validation": {},
            "abc": None
        })
        list_obj._attribute_map = {"abc": {"key": "ABC", "type": "int"}}
        list_obj.abc = "123"

        test_obj = type("CmplxTestObj", (Model, ), {
            "_attribute_map": None,
            "_validation": {},
            "test_list": None
        })

        test_obj._attribute_map = {
            "test_list": {
                "key": "_list",
                "type": "[ListObj]"
            }
        }
        test_obj.test_list = [list_obj]

        message = self.s._serialize(test_obj)
        self.assertEqual(message, {'_list': [{'ABC': 123}]})

        list_obj = type("BadListObj", (Model, ), {"map": None})
        test_obj._attribute_map = {
            "test_list": {
                "key": "_list",
                "type": "[BadListObj]"
            }
        }
        test_obj.test_list = [list_obj]

        s = self.s._serialize(test_obj)
        self.assertEqual(s, {'_list': [{}]})

    def test_attr_dict_simple(self):
        """
        Test serializing an object with a simple dictionary attribute.
        """

        test_obj = self.TestObj()
        test_obj.attr_e = {"value": 3.14}

        message = self.s._serialize(test_obj)
        self.assertEqual(message['AttrE']['value'],
                         float(test_obj.attr_e["value"]))

        test_obj.attr_e = {1: "3.14"}

        message = self.s._serialize(test_obj)
        self.assertEqual(message['AttrE']['1'], float(test_obj.attr_e[1]))

        test_obj.attr_e = "NotADict"

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

        test_obj.attr_e = {"value": "NotAFloat"}

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

    def test_serialize_datetime(self):

        date_obj = isodate.parse_datetime('2015-01-01T00:00:00')
        date_str = Serializer.serialize_iso(date_obj)

        self.assertEqual(date_str, '2015-01-01T00:00:00.000Z')

        date_obj = isodate.parse_datetime('1999-12-31T23:59:59-12:00')
        date_str = Serializer.serialize_iso(date_obj)

        self.assertEqual(date_str, '2000-01-01T11:59:59.000Z')

        with self.assertRaises(SerializationError):
            date_obj = isodate.parse_datetime('9999-12-31T23:59:59-12:00')
            date_str = Serializer.serialize_iso(date_obj)

        with self.assertRaises(SerializationError):
            date_obj = isodate.parse_datetime('0001-01-01T00:00:00+23:59')
            date_str = Serializer.serialize_iso(date_obj)

        date_obj = isodate.parse_datetime("2015-06-01T16:10:08.0121-07:00")
        date_str = Serializer.serialize_iso(date_obj)

        self.assertEqual(date_str, '2015-06-01T23:10:08.0121Z')

        date_obj = datetime.min
        date_str = Serializer.serialize_iso(date_obj)
        self.assertEqual(date_str, '0001-01-01T00:00:00.000Z')

        date_obj = datetime.max
        date_str = Serializer.serialize_iso(date_obj)
        self.assertEqual(date_str, '9999-12-31T23:59:59.999999Z')

    def test_serialize_primitive_types(self):

        a = self.s.serialize_data(1, 'int')
        self.assertEqual(a, 1)

        b = self.s.serialize_data(True, 'bool')
        self.assertEqual(b, True)

        c = self.s.serialize_data('True', 'str')
        self.assertEqual(c, 'True')

        d = self.s.serialize_data(100.0123, 'float')
        self.assertEqual(d, 100.0123)

    def test_serialize_object(self):

        a = self.s.body(1, 'object')
        self.assertEqual(a, 1)

        b = self.s.body(True, 'object')
        self.assertEqual(b, True)

        c = self.s.serialize_data('True', 'object')
        self.assertEqual(c, 'True')

        d = self.s.serialize_data(100.0123, 'object')
        self.assertEqual(d, 100.0123)

        e = self.s.serialize_data({}, 'object')
        self.assertEqual(e, {})

        f = self.s.body({"test": "data"}, 'object')
        self.assertEqual(f, {"test": "data"})

        g = self.s.body({"test": {"value": "data"}}, 'object')
        self.assertEqual(g, {"test": {"value": "data"}})

        h = self.s.serialize_data({"test": self.TestObj()}, 'object')
        self.assertEqual(h, {"test": "Test_Object"})

        i = self.s.serialize_data({"test": [1, 2, 3, 4, 5]}, 'object')
        self.assertEqual(i, {"test": [1, 2, 3, 4, 5]})

    def test_serialize_empty_iter(self):

        a = self.s.serialize_dict({}, 'int')
        self.assertEqual(a, {})

        b = self.s.serialize_iter([], 'int')
        self.assertEqual(b, [])

    def test_serialize_json_obj(self):
        class ComplexId(Model):

            _validation = {}
            _attribute_map = {
                'id': {
                    'key': 'id',
                    'type': 'int'
                },
                'name': {
                    'key': 'name',
                    'type': 'str'
                },
                'age': {
                    'key': 'age',
                    'type': 'float'
                },
                'male': {
                    'key': 'male',
                    'type': 'bool'
                },
                'birthday': {
                    'key': 'birthday',
                    'type': 'iso-8601'
                },
                'anniversary': {
                    'key': 'anniversary',
                    'type': 'iso-8601'
                }
            }

            id = 1
            name = "Joey"
            age = 23.36
            male = True
            birthday = '1992-01-01T00:00:00.000Z'
            anniversary = isodate.parse_datetime('2013-12-08T00:00:00')

        class ComplexJson(Model):

            _validation = {}
            _attribute_map = {
                'p1': {
                    'key': 'p1',
                    'type': 'str'
                },
                'p2': {
                    'key': 'p2',
                    'type': 'str'
                },
                'top_date': {
                    'key': 'top_date',
                    'type': 'iso-8601'
                },
                'top_dates': {
                    'key': 'top_dates',
                    'type': '[iso-8601]'
                },
                'insider': {
                    'key': 'insider',
                    'type': '{iso-8601}'
                },
                'top_complex': {
                    'key': 'top_complex',
                    'type': 'ComplexId'
                }
            }

            p1 = 'value1'
            p2 = 'value2'
            top_date = isodate.parse_datetime('2014-01-01T00:00:00')
            top_dates = [
                isodate.parse_datetime('1900-01-01T00:00:00'),
                isodate.parse_datetime('1901-01-01T00:00:00')
            ]
            insider = {
                'k1': isodate.parse_datetime('2015-01-01T00:00:00'),
                'k2': isodate.parse_datetime('2016-01-01T00:00:00'),
                'k3': isodate.parse_datetime('2017-01-01T00:00:00')
            }
            top_complex = ComplexId()

        message = self.s._serialize(ComplexJson())

        output = {
            'p1': 'value1',
            'p2': 'value2',
            'top_date': '2014-01-01T00:00:00.000Z',
            'top_dates':
            ['1900-01-01T00:00:00.000Z', '1901-01-01T00:00:00.000Z'],
            'insider': {
                'k1': '2015-01-01T00:00:00.000Z',
                'k2': '2016-01-01T00:00:00.000Z',
                'k3': '2017-01-01T00:00:00.000Z'
            },
            'top_complex': {
                'id': 1,
                'name': 'Joey',
                'age': 23.36,
                'male': True,
                'birthday': '1992-01-01T00:00:00.000Z',
                'anniversary': '2013-12-08T00:00:00.000Z',
            }
        }
        self.maxDiff = None
        self.assertEqual(message, output)

    def test_polymorphic_serialization(self):

        self.maxDiff = None

        class Zoo(Model):

            _attribute_map = {
                "animals": {
                    "key": "Animals",
                    "type": "[Animal]"
                },
            }

            def __init__(self, animals=None):
                self.animals = animals

        class Animal(Model):

            _attribute_map = {
                "name": {
                    "key": "Name",
                    "type": "str"
                },
                "d_type": {
                    "key": "dType",
                    "type": "str"
                }
            }

            _subtype_map = {'d_type': {"cat": "Cat", "dog": "Dog"}}

            def __init__(self, name=None):
                self.name = name

        class Dog(Animal):

            _attribute_map = {
                "name": {
                    "key": "Name",
                    "type": "str"
                },
                "likes_dog_food": {
                    "key": "likesDogFood",
                    "type": "bool"
                },
                "d_type": {
                    "key": "dType",
                    "type": "str"
                }
            }

            def __init__(self, name=None, likes_dog_food=None):
                self.likes_dog_food = likes_dog_food
                super(Dog, self).__init__(name)
                self.d_type = 'dog'

        class Cat(Animal):

            _attribute_map = {
                "name": {
                    "key": "Name",
                    "type": "str"
                },
                "likes_mice": {
                    "key": "likesMice",
                    "type": "bool"
                },
                "dislikes": {
                    "key": "dislikes",
                    "type": "Animal"
                },
                "d_type": {
                    "key": "dType",
                    "type": "str"
                }
            }

            _subtype_map = {"d_type": {"siamese": "Siamese"}}

            def __init__(self, name=None, likes_mice=None, dislikes=None):
                self.likes_mice = likes_mice
                self.dislikes = dislikes
                super(Cat, self).__init__(name)
                self.d_type = 'cat'

        class Siamese(Cat):

            _attribute_map = {
                "name": {
                    "key": "Name",
                    "type": "str"
                },
                "likes_mice": {
                    "key": "likesMice",
                    "type": "bool"
                },
                "dislikes": {
                    "key": "dislikes",
                    "type": "Animal"
                },
                "color": {
                    "key": "Color",
                    "type": "str"
                },
                "d_type": {
                    "key": "dType",
                    "type": "str"
                }
            }

            def __init__(self,
                         name=None,
                         likes_mice=None,
                         dislikes=None,
                         color=None):
                self.color = color
                super(Siamese, self).__init__(name, likes_mice, dislikes)
                self.d_type = 'siamese'

        message = {
            "Animals": [{
                "dType": "dog",
                "likesDogFood": True,
                "Name": "Fido"
            }, {
                "dType": "cat",
                "likesMice": False,
                "dislikes": {
                    "dType": "dog",
                    "likesDogFood": True,
                    "Name": "Angry"
                },
                "Name": "Felix"
            }, {
                "dType": "siamese",
                "Color": "grey",
                "likesMice": True,
                "Name": "Finch"
            }]
        }

        zoo = Zoo()
        angry = Dog()
        angry.name = "Angry"
        angry.likes_dog_food = True

        fido = Dog()
        fido.name = "Fido"
        fido.likes_dog_food = True

        felix = Cat()
        felix.name = "Felix"
        felix.likes_mice = False
        felix.dislikes = angry

        finch = Siamese()
        finch.name = "Finch"
        finch.color = "grey"
        finch.likes_mice = True

        zoo.animals = [fido, felix, finch]

        serialized = self.s._serialize(zoo)
        self.assertEqual(serialized, message)

        old_dependencies = self.s.dependencies
        self.s.dependencies = {
            'Zoo': Zoo,
            'Animal': Animal,
            'Dog': Dog,
            'Cat': Cat,
            'Siamese': Siamese
        }

        serialized = self.s.body(
            {
                "animals": [{
                    "dType": "dog",
                    "likes_dog_food": True,
                    "name": "Fido"
                }, {
                    "dType": "cat",
                    "likes_mice": False,
                    "dislikes": {
                        "dType": "dog",
                        "likes_dog_food": True,
                        "name": "Angry"
                    },
                    "name": "Felix"
                }, {
                    "dType": "siamese",
                    "color": "grey",
                    "likes_mice": True,
                    "name": "Finch"
                }]
            }, "Zoo")
        self.assertEqual(serialized, message)

        self.s.dependencies = old_dependencies
Ejemplo n.º 11
0
class TestClient(Client):
    """Test
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """
    def __init__(self, base_url=None, creds=None):
        super(TestClient, self).__init__(base_url, creds)
        client_models = {
            k: v
            for k, v in models.__dict__.items() if isinstance(v, type)
        }
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = 'c2aa639c-3ccc-4740-b3b6-ce2a1e1d984e'

    def get_action_results(self,
                           project,
                           run_id,
                           test_case_result_id,
                           iteration_id,
                           action_path=None):
        """GetActionResults.
        Gets the action results for an iteration in a test result.
        :param str project: Project ID or project name
        :param int run_id: ID of the test run that contains the result.
        :param int test_case_result_id: ID of the test result that contains the iterations.
        :param int iteration_id: ID of the iteration that contains the actions.
        :param str action_path: Path of a specific action, used to get just that action.
        :rtype: [TestActionResultModel]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if run_id is not None:
            route_values['runId'] = self._serialize.url(
                'run_id', run_id, 'int')
        if test_case_result_id is not None:
            route_values['testCaseResultId'] = self._serialize.url(
                'test_case_result_id', test_case_result_id, 'int')
        if iteration_id is not None:
            route_values['iterationId'] = self._serialize.url(
                'iteration_id', iteration_id, 'int')
        if action_path is not None:
            route_values['actionPath'] = self._serialize.url(
                'action_path', action_path, 'str')
        response = self._send(
            http_method='GET',
            location_id='eaf40c31-ff84-4062-aafd-d5664be11a37',
            version='5.1',
            route_values=route_values)
        return self._deserialize('[TestActionResultModel]',
                                 self._unwrap_collection(response))

    def get_test_iteration(self,
                           project,
                           run_id,
                           test_case_result_id,
                           iteration_id,
                           include_action_results=None):
        """GetTestIteration.
        Get iteration for a result
        :param str project: Project ID or project name
        :param int run_id: ID of the test run that contains the result.
        :param int test_case_result_id: ID of the test result that contains the iterations.
        :param int iteration_id: Id of the test results Iteration.
        :param bool include_action_results: Include result details for each action performed in the test iteration. ActionResults refer to outcome (pass/fail) of test steps that are executed as part of a running a manual test. Including the ActionResults flag gets the outcome of test steps in the actionResults section and test parameters in the parameters section for each test iteration.
        :rtype: :class:`<TestIterationDetailsModel> <azure.devops.v5_1.test.models.TestIterationDetailsModel>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if run_id is not None:
            route_values['runId'] = self._serialize.url(
                'run_id', run_id, 'int')
        if test_case_result_id is not None:
            route_values['testCaseResultId'] = self._serialize.url(
                'test_case_result_id', test_case_result_id, 'int')
        if iteration_id is not None:
            route_values['iterationId'] = self._serialize.url(
                'iteration_id', iteration_id, 'int')
        query_parameters = {}
        if include_action_results is not None:
            query_parameters['includeActionResults'] = self._serialize.query(
                'include_action_results', include_action_results, 'bool')
        response = self._send(
            http_method='GET',
            location_id='73eb9074-3446-4c44-8296-2f811950ff8d',
            version='5.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('TestIterationDetailsModel', response)

    def get_test_iterations(self,
                            project,
                            run_id,
                            test_case_result_id,
                            include_action_results=None):
        """GetTestIterations.
        Get iterations for a result
        :param str project: Project ID or project name
        :param int run_id: ID of the test run that contains the result.
        :param int test_case_result_id: ID of the test result that contains the iterations.
        :param bool include_action_results: Include result details for each action performed in the test iteration. ActionResults refer to outcome (pass/fail) of test steps that are executed as part of a running a manual test. Including the ActionResults flag gets the outcome of test steps in the actionResults section and test parameters in the parameters section for each test iteration.
        :rtype: [TestIterationDetailsModel]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if run_id is not None:
            route_values['runId'] = self._serialize.url(
                'run_id', run_id, 'int')
        if test_case_result_id is not None:
            route_values['testCaseResultId'] = self._serialize.url(
                'test_case_result_id', test_case_result_id, 'int')
        query_parameters = {}
        if include_action_results is not None:
            query_parameters['includeActionResults'] = self._serialize.query(
                'include_action_results', include_action_results, 'bool')
        response = self._send(
            http_method='GET',
            location_id='73eb9074-3446-4c44-8296-2f811950ff8d',
            version='5.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[TestIterationDetailsModel]',
                                 self._unwrap_collection(response))

    def get_result_parameters(self,
                              project,
                              run_id,
                              test_case_result_id,
                              iteration_id,
                              param_name=None):
        """GetResultParameters.
        Get a list of parameterized results
        :param str project: Project ID or project name
        :param int run_id: ID of the test run that contains the result.
        :param int test_case_result_id: ID of the test result that contains the iterations.
        :param int iteration_id: ID of the iteration that contains the parameterized results.
        :param str param_name: Name of the parameter.
        :rtype: [TestResultParameterModel]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if run_id is not None:
            route_values['runId'] = self._serialize.url(
                'run_id', run_id, 'int')
        if test_case_result_id is not None:
            route_values['testCaseResultId'] = self._serialize.url(
                'test_case_result_id', test_case_result_id, 'int')
        if iteration_id is not None:
            route_values['iterationId'] = self._serialize.url(
                'iteration_id', iteration_id, 'int')
        query_parameters = {}
        if param_name is not None:
            query_parameters['paramName'] = self._serialize.query(
                'param_name', param_name, 'str')
        response = self._send(
            http_method='GET',
            location_id='7c69810d-3354-4af3-844a-180bd25db08a',
            version='5.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[TestResultParameterModel]',
                                 self._unwrap_collection(response))

    def get_point(self,
                  project,
                  plan_id,
                  suite_id,
                  point_ids,
                  wit_fields=None):
        """GetPoint.
        Get a test point.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan.
        :param int suite_id: ID of the suite that contains the point.
        :param int point_ids: ID of the test point to get.
        :param str wit_fields: Comma-separated list of work item field names.
        :rtype: :class:`<TestPoint> <azure.devops.v5_1.test.models.TestPoint>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url(
                'plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url(
                'suite_id', suite_id, 'int')
        if point_ids is not None:
            route_values['pointIds'] = self._serialize.url(
                'point_ids', point_ids, 'int')
        query_parameters = {}
        if wit_fields is not None:
            query_parameters['witFields'] = self._serialize.query(
                'wit_fields', wit_fields, 'str')
        response = self._send(
            http_method='GET',
            location_id='3bcfd5c8-be62-488e-b1da-b8289ce9299c',
            version='5.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('TestPoint', response)

    def get_points(self,
                   project,
                   plan_id,
                   suite_id,
                   wit_fields=None,
                   configuration_id=None,
                   test_case_id=None,
                   test_point_ids=None,
                   include_point_details=None,
                   skip=None,
                   top=None):
        """GetPoints.
        Get a list of test points.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan.
        :param int suite_id: ID of the suite that contains the points.
        :param str wit_fields: Comma-separated list of work item field names.
        :param str configuration_id: Get test points for specific configuration.
        :param str test_case_id: Get test points for a specific test case, valid when configurationId is not set.
        :param str test_point_ids: Get test points for comma-separated list of test point IDs, valid only when configurationId and testCaseId are not set.
        :param bool include_point_details: Include all properties for the test point.
        :param int skip: Number of test points to skip..
        :param int top: Number of test points to return.
        :rtype: [TestPoint]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url(
                'plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url(
                'suite_id', suite_id, 'int')
        query_parameters = {}
        if wit_fields is not None:
            query_parameters['witFields'] = self._serialize.query(
                'wit_fields', wit_fields, 'str')
        if configuration_id is not None:
            query_parameters['configurationId'] = self._serialize.query(
                'configuration_id', configuration_id, 'str')
        if test_case_id is not None:
            query_parameters['testCaseId'] = self._serialize.query(
                'test_case_id', test_case_id, 'str')
        if test_point_ids is not None:
            query_parameters['testPointIds'] = self._serialize.query(
                'test_point_ids', test_point_ids, 'str')
        if include_point_details is not None:
            query_parameters['includePointDetails'] = self._serialize.query(
                'include_point_details', include_point_details, 'bool')
        if skip is not None:
            query_parameters['$skip'] = self._serialize.query(
                'skip', skip, 'int')
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        response = self._send(
            http_method='GET',
            location_id='3bcfd5c8-be62-488e-b1da-b8289ce9299c',
            version='5.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[TestPoint]',
                                 self._unwrap_collection(response))

    def update_test_points(self, point_update_model, project, plan_id,
                           suite_id, point_ids):
        """UpdateTestPoints.
        Update test points.
        :param :class:`<PointUpdateModel> <azure.devops.v5_1.test.models.PointUpdateModel>` point_update_model: Data to update.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan.
        :param int suite_id: ID of the suite that contains the points.
        :param str point_ids: ID of the test point to get. Use a comma-separated list of IDs to update multiple test points.
        :rtype: [TestPoint]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url(
                'plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url(
                'suite_id', suite_id, 'int')
        if point_ids is not None:
            route_values['pointIds'] = self._serialize.url(
                'point_ids', point_ids, 'str')
        content = self._serialize.body(point_update_model, 'PointUpdateModel')
        response = self._send(
            http_method='PATCH',
            location_id='3bcfd5c8-be62-488e-b1da-b8289ce9299c',
            version='5.1',
            route_values=route_values,
            content=content)
        return self._deserialize('[TestPoint]',
                                 self._unwrap_collection(response))

    def add_test_results_to_test_run(self, results, project, run_id):
        """AddTestResultsToTestRun.
        Add test results to a test run.
        :param [TestCaseResult] results: List of test results to add.
        :param str project: Project ID or project name
        :param int run_id: Test run ID into which test results to add.
        :rtype: [TestCaseResult]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if run_id is not None:
            route_values['runId'] = self._serialize.url(
                'run_id', run_id, 'int')
        content = self._serialize.body(results, '[TestCaseResult]')
        response = self._send(
            http_method='POST',
            location_id='4637d869-3a76-4468-8057-0bb02aa385cf',
            version='5.1',
            route_values=route_values,
            content=content)
        return self._deserialize('[TestCaseResult]',
                                 self._unwrap_collection(response))

    def get_test_result_by_id(self,
                              project,
                              run_id,
                              test_case_result_id,
                              details_to_include=None):
        """GetTestResultById.
        Get a test result for a test run.
        :param str project: Project ID or project name
        :param int run_id: Test run ID of a test result to fetch.
        :param int test_case_result_id: Test result ID.
        :param str details_to_include: Details to include with test results. Default is None. Other values are Iterations, WorkItems and SubResults.
        :rtype: :class:`<TestCaseResult> <azure.devops.v5_1.test.models.TestCaseResult>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if run_id is not None:
            route_values['runId'] = self._serialize.url(
                'run_id', run_id, 'int')
        if test_case_result_id is not None:
            route_values['testCaseResultId'] = self._serialize.url(
                'test_case_result_id', test_case_result_id, 'int')
        query_parameters = {}
        if details_to_include is not None:
            query_parameters['detailsToInclude'] = self._serialize.query(
                'details_to_include', details_to_include, 'str')
        response = self._send(
            http_method='GET',
            location_id='4637d869-3a76-4468-8057-0bb02aa385cf',
            version='5.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('TestCaseResult', response)

    def get_test_results(self,
                         project,
                         run_id,
                         details_to_include=None,
                         skip=None,
                         top=None,
                         outcomes=None):
        """GetTestResults.
        Get test results for a test run.
        :param str project: Project ID or project name
        :param int run_id: Test run ID of test results to fetch.
        :param str details_to_include: Details to include with test results. Default is None. Other values are Iterations and WorkItems.
        :param int skip: Number of test results to skip from beginning.
        :param int top: Number of test results to return. Maximum is 1000 when detailsToInclude is None and 200 otherwise.
        :param [TestOutcome] outcomes: Comma separated list of test outcomes to filter test results.
        :rtype: [TestCaseResult]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if run_id is not None:
            route_values['runId'] = self._serialize.url(
                'run_id', run_id, 'int')
        query_parameters = {}
        if details_to_include is not None:
            query_parameters['detailsToInclude'] = self._serialize.query(
                'details_to_include', details_to_include, 'str')
        if skip is not None:
            query_parameters['$skip'] = self._serialize.query(
                'skip', skip, 'int')
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        if outcomes is not None:
            outcomes = ",".join(map(str, outcomes))
            query_parameters['outcomes'] = self._serialize.query(
                'outcomes', outcomes, 'str')
        response = self._send(
            http_method='GET',
            location_id='4637d869-3a76-4468-8057-0bb02aa385cf',
            version='5.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[TestCaseResult]',
                                 self._unwrap_collection(response))

    def update_test_results(self, results, project, run_id):
        """UpdateTestResults.
        Update test results in a test run.
        :param [TestCaseResult] results: List of test results to update.
        :param str project: Project ID or project name
        :param int run_id: Test run ID whose test results to update.
        :rtype: [TestCaseResult]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if run_id is not None:
            route_values['runId'] = self._serialize.url(
                'run_id', run_id, 'int')
        content = self._serialize.body(results, '[TestCaseResult]')
        response = self._send(
            http_method='PATCH',
            location_id='4637d869-3a76-4468-8057-0bb02aa385cf',
            version='5.1',
            route_values=route_values,
            content=content)
        return self._deserialize('[TestCaseResult]',
                                 self._unwrap_collection(response))

    def get_test_run_statistics(self, project, run_id):
        """GetTestRunStatistics.
        Get test run statistics , used when we want to get summary of a run by outcome.
        :param str project: Project ID or project name
        :param int run_id: ID of the run to get.
        :rtype: :class:`<TestRunStatistic> <azure.devops.v5_1.test.models.TestRunStatistic>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if run_id is not None:
            route_values['runId'] = self._serialize.url(
                'run_id', run_id, 'int')
        response = self._send(
            http_method='GET',
            location_id='0a42c424-d764-4a16-a2d5-5c85f87d0ae8',
            version='5.1',
            route_values=route_values)
        return self._deserialize('TestRunStatistic', response)

    def create_test_run(self, test_run, project):
        """CreateTestRun.
        Create new test run.
        :param :class:`<RunCreateModel> <azure.devops.v5_1.test.models.RunCreateModel>` test_run: Run details RunCreateModel
        :param str project: Project ID or project name
        :rtype: :class:`<TestRun> <azure.devops.v5_1.test.models.TestRun>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        content = self._serialize.body(test_run, 'RunCreateModel')
        response = self._send(
            http_method='POST',
            location_id='cadb3810-d47d-4a3c-a234-fe5f3be50138',
            version='5.1',
            route_values=route_values,
            content=content)
        return self._deserialize('TestRun', response)

    def delete_test_run(self, project, run_id):
        """DeleteTestRun.
        Delete a test run by its ID.
        :param str project: Project ID or project name
        :param int run_id: ID of the run to delete.
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if run_id is not None:
            route_values['runId'] = self._serialize.url(
                'run_id', run_id, 'int')
        self._send(http_method='DELETE',
                   location_id='cadb3810-d47d-4a3c-a234-fe5f3be50138',
                   version='5.1',
                   route_values=route_values)

    def get_test_run_by_id(self, project, run_id, include_details=None):
        """GetTestRunById.
        Get a test run by its ID.
        :param str project: Project ID or project name
        :param int run_id: ID of the run to get.
        :param bool include_details: Defualt value is true. It includes details like run statistics,release,build,Test enviornment,Post process state and more
        :rtype: :class:`<TestRun> <azure.devops.v5_1.test.models.TestRun>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if run_id is not None:
            route_values['runId'] = self._serialize.url(
                'run_id', run_id, 'int')
        query_parameters = {}
        if include_details is not None:
            query_parameters['includeDetails'] = self._serialize.query(
                'include_details', include_details, 'bool')
        response = self._send(
            http_method='GET',
            location_id='cadb3810-d47d-4a3c-a234-fe5f3be50138',
            version='5.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('TestRun', response)

    def get_test_runs(self,
                      project,
                      build_uri=None,
                      owner=None,
                      tmi_run_id=None,
                      plan_id=None,
                      include_run_details=None,
                      automated=None,
                      skip=None,
                      top=None):
        """GetTestRuns.
        Get a list of test runs.
        :param str project: Project ID or project name
        :param str build_uri: URI of the build that the runs used.
        :param str owner: Team foundation ID of the owner of the runs.
        :param str tmi_run_id:
        :param int plan_id: ID of the test plan that the runs are a part of.
        :param bool include_run_details: If true, include all the properties of the runs.
        :param bool automated: If true, only returns automated runs.
        :param int skip: Number of test runs to skip.
        :param int top: Number of test runs to return.
        :rtype: [TestRun]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        query_parameters = {}
        if build_uri is not None:
            query_parameters['buildUri'] = self._serialize.query(
                'build_uri', build_uri, 'str')
        if owner is not None:
            query_parameters['owner'] = self._serialize.query(
                'owner', owner, 'str')
        if tmi_run_id is not None:
            query_parameters['tmiRunId'] = self._serialize.query(
                'tmi_run_id', tmi_run_id, 'str')
        if plan_id is not None:
            query_parameters['planId'] = self._serialize.query(
                'plan_id', plan_id, 'int')
        if include_run_details is not None:
            query_parameters['includeRunDetails'] = self._serialize.query(
                'include_run_details', include_run_details, 'bool')
        if automated is not None:
            query_parameters['automated'] = self._serialize.query(
                'automated', automated, 'bool')
        if skip is not None:
            query_parameters['$skip'] = self._serialize.query(
                'skip', skip, 'int')
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        response = self._send(
            http_method='GET',
            location_id='cadb3810-d47d-4a3c-a234-fe5f3be50138',
            version='5.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[TestRun]',
                                 self._unwrap_collection(response))

    def query_test_runs(self,
                        project,
                        min_last_updated_date,
                        max_last_updated_date,
                        state=None,
                        plan_ids=None,
                        is_automated=None,
                        publish_context=None,
                        build_ids=None,
                        build_def_ids=None,
                        branch_name=None,
                        release_ids=None,
                        release_def_ids=None,
                        release_env_ids=None,
                        release_env_def_ids=None,
                        run_title=None,
                        top=None,
                        continuation_token=None):
        """QueryTestRuns.
        Query Test Runs based on filters. Mandatory fields are minLastUpdatedDate and maxLastUpdatedDate.
        :param str project: Project ID or project name
        :param datetime min_last_updated_date: Minimum Last Modified Date of run to be queried (Mandatory).
        :param datetime max_last_updated_date: Maximum Last Modified Date of run to be queried (Mandatory, difference between min and max date can be atmost 7 days).
        :param str state: Current state of the Runs to be queried.
        :param [int] plan_ids: Plan Ids of the Runs to be queried, comma seperated list of valid ids (limit no. of ids 10).
        :param bool is_automated: Automation type of the Runs to be queried.
        :param str publish_context: PublishContext of the Runs to be queried.
        :param [int] build_ids: Build Ids of the Runs to be queried, comma seperated list of valid ids (limit no. of ids 10).
        :param [int] build_def_ids: Build Definition Ids of the Runs to be queried, comma seperated list of valid ids (limit no. of ids 10).
        :param str branch_name: Source Branch name of the Runs to be queried.
        :param [int] release_ids: Release Ids of the Runs to be queried, comma seperated list of valid ids (limit no. of ids 10).
        :param [int] release_def_ids: Release Definition Ids of the Runs to be queried, comma seperated list of valid ids (limit no. of ids 10).
        :param [int] release_env_ids: Release Environment Ids of the Runs to be queried, comma seperated list of valid ids (limit no. of ids 10).
        :param [int] release_env_def_ids: Release Environment Definition Ids of the Runs to be queried, comma seperated list of valid ids (limit no. of ids 10).
        :param str run_title: Run Title of the Runs to be queried.
        :param int top: Number of runs to be queried. Limit is 100
        :param str continuation_token: continuationToken received from previous batch or null for first batch. It is not supposed to be created (or altered, if received from last batch) by user.
        :rtype: [TestRun]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        query_parameters = {}
        if min_last_updated_date is not None:
            query_parameters['minLastUpdatedDate'] = self._serialize.query(
                'min_last_updated_date', min_last_updated_date, 'iso-8601')
        if max_last_updated_date is not None:
            query_parameters['maxLastUpdatedDate'] = self._serialize.query(
                'max_last_updated_date', max_last_updated_date, 'iso-8601')
        if state is not None:
            query_parameters['state'] = self._serialize.query(
                'state', state, 'str')
        if plan_ids is not None:
            plan_ids = ",".join(map(str, plan_ids))
            query_parameters['planIds'] = self._serialize.query(
                'plan_ids', plan_ids, 'str')
        if is_automated is not None:
            query_parameters['isAutomated'] = self._serialize.query(
                'is_automated', is_automated, 'bool')
        if publish_context is not None:
            query_parameters['publishContext'] = self._serialize.query(
                'publish_context', publish_context, 'str')
        if build_ids is not None:
            build_ids = ",".join(map(str, build_ids))
            query_parameters['buildIds'] = self._serialize.query(
                'build_ids', build_ids, 'str')
        if build_def_ids is not None:
            build_def_ids = ",".join(map(str, build_def_ids))
            query_parameters['buildDefIds'] = self._serialize.query(
                'build_def_ids', build_def_ids, 'str')
        if branch_name is not None:
            query_parameters['branchName'] = self._serialize.query(
                'branch_name', branch_name, 'str')
        if release_ids is not None:
            release_ids = ",".join(map(str, release_ids))
            query_parameters['releaseIds'] = self._serialize.query(
                'release_ids', release_ids, 'str')
        if release_def_ids is not None:
            release_def_ids = ",".join(map(str, release_def_ids))
            query_parameters['releaseDefIds'] = self._serialize.query(
                'release_def_ids', release_def_ids, 'str')
        if release_env_ids is not None:
            release_env_ids = ",".join(map(str, release_env_ids))
            query_parameters['releaseEnvIds'] = self._serialize.query(
                'release_env_ids', release_env_ids, 'str')
        if release_env_def_ids is not None:
            release_env_def_ids = ",".join(map(str, release_env_def_ids))
            query_parameters['releaseEnvDefIds'] = self._serialize.query(
                'release_env_def_ids', release_env_def_ids, 'str')
        if run_title is not None:
            query_parameters['runTitle'] = self._serialize.query(
                'run_title', run_title, 'str')
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        if continuation_token is not None:
            query_parameters['continuationToken'] = self._serialize.query(
                'continuation_token', continuation_token, 'str')
        response = self._send(
            http_method='GET',
            location_id='cadb3810-d47d-4a3c-a234-fe5f3be50138',
            version='5.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[TestRun]',
                                 self._unwrap_collection(response))

    def update_test_run(self, run_update_model, project, run_id):
        """UpdateTestRun.
        Update test run by its ID.
        :param :class:`<RunUpdateModel> <azure.devops.v5_1.test.models.RunUpdateModel>` run_update_model: Run details RunUpdateModel
        :param str project: Project ID or project name
        :param int run_id: ID of the run to update.
        :rtype: :class:`<TestRun> <azure.devops.v5_1.test.models.TestRun>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if run_id is not None:
            route_values['runId'] = self._serialize.url(
                'run_id', run_id, 'int')
        content = self._serialize.body(run_update_model, 'RunUpdateModel')
        response = self._send(
            http_method='PATCH',
            location_id='cadb3810-d47d-4a3c-a234-fe5f3be50138',
            version='5.1',
            route_values=route_values,
            content=content)
        return self._deserialize('TestRun', response)

    def add_test_cases_to_suite(self, project, plan_id, suite_id,
                                test_case_ids):
        """AddTestCasesToSuite.
        Add test cases to suite.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan that contains the suite.
        :param int suite_id: ID of the test suite to which the test cases must be added.
        :param str test_case_ids: IDs of the test cases to add to the suite. Ids are specified in comma separated format.
        :rtype: [SuiteTestCase]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url(
                'plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url(
                'suite_id', suite_id, 'int')
        if test_case_ids is not None:
            route_values['testCaseIds'] = self._serialize.url(
                'test_case_ids', test_case_ids, 'str')
        route_values['action'] = 'TestCases'
        response = self._send(
            http_method='POST',
            location_id='a4a1ec1c-b03f-41ca-8857-704594ecf58e',
            version='5.1',
            route_values=route_values)
        return self._deserialize('[SuiteTestCase]',
                                 self._unwrap_collection(response))

    def get_test_case_by_id(self, project, plan_id, suite_id, test_case_ids):
        """GetTestCaseById.
        Get a specific test case in a test suite with test case id.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan that contains the suites.
        :param int suite_id: ID of the suite that contains the test case.
        :param int test_case_ids: ID of the test case to get.
        :rtype: :class:`<SuiteTestCase> <azure.devops.v5_1.test.models.SuiteTestCase>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url(
                'plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url(
                'suite_id', suite_id, 'int')
        if test_case_ids is not None:
            route_values['testCaseIds'] = self._serialize.url(
                'test_case_ids', test_case_ids, 'int')
        route_values['action'] = 'TestCases'
        response = self._send(
            http_method='GET',
            location_id='a4a1ec1c-b03f-41ca-8857-704594ecf58e',
            version='5.1',
            route_values=route_values)
        return self._deserialize('SuiteTestCase', response)

    def get_test_cases(self, project, plan_id, suite_id):
        """GetTestCases.
        Get all test cases in a suite.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan that contains the suites.
        :param int suite_id: ID of the suite to get.
        :rtype: [SuiteTestCase]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url(
                'plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url(
                'suite_id', suite_id, 'int')
        route_values['action'] = 'TestCases'
        response = self._send(
            http_method='GET',
            location_id='a4a1ec1c-b03f-41ca-8857-704594ecf58e',
            version='5.1',
            route_values=route_values)
        return self._deserialize('[SuiteTestCase]',
                                 self._unwrap_collection(response))

    def remove_test_cases_from_suite_url(self, project, plan_id, suite_id,
                                         test_case_ids):
        """RemoveTestCasesFromSuiteUrl.
        The test points associated with the test cases are removed from the test suite. The test case work item is not deleted from the system. See test cases resource to delete a test case permanently.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan that contains the suite.
        :param int suite_id: ID of the suite to get.
        :param str test_case_ids: IDs of the test cases to remove from the suite.
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url(
                'plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url(
                'suite_id', suite_id, 'int')
        if test_case_ids is not None:
            route_values['testCaseIds'] = self._serialize.url(
                'test_case_ids', test_case_ids, 'str')
        route_values['action'] = 'TestCases'
        self._send(http_method='DELETE',
                   location_id='a4a1ec1c-b03f-41ca-8857-704594ecf58e',
                   version='5.1',
                   route_values=route_values)

    def update_suite_test_cases(self, suite_test_case_update_model, project,
                                plan_id, suite_id, test_case_ids):
        """UpdateSuiteTestCases.
        Updates the properties of the test case association in a suite.
        :param :class:`<SuiteTestCaseUpdateModel> <azure.devops.v5_1.test.models.SuiteTestCaseUpdateModel>` suite_test_case_update_model: Model for updation of the properties of test case suite association.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan that contains the suite.
        :param int suite_id: ID of the test suite to which the test cases must be added.
        :param str test_case_ids: IDs of the test cases to add to the suite. Ids are specified in comma separated format.
        :rtype: [SuiteTestCase]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url(
                'plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url(
                'suite_id', suite_id, 'int')
        if test_case_ids is not None:
            route_values['testCaseIds'] = self._serialize.url(
                'test_case_ids', test_case_ids, 'str')
        route_values['action'] = 'TestCases'
        content = self._serialize.body(suite_test_case_update_model,
                                       'SuiteTestCaseUpdateModel')
        response = self._send(
            http_method='PATCH',
            location_id='a4a1ec1c-b03f-41ca-8857-704594ecf58e',
            version='5.1',
            route_values=route_values,
            content=content)
        return self._deserialize('[SuiteTestCase]',
                                 self._unwrap_collection(response))
Ejemplo n.º 12
0
class InventoryModule(BaseInventoryPlugin, Constructable):

    NAME = 'azure_rm'

    def __init__(self):
        super(InventoryModule, self).__init__()

        self._serializer = Serializer()
        self._deserializer = Deserializer()
        self._hosts = []
        self._filters = None

        # FUTURE: use API profiles with defaults
        self._compute_api_version = '2017-03-30'
        self._network_api_version = '2015-06-15'

        self._default_header_parameters = {
            'Content-Type': 'application/json; charset=utf-8'
        }

        self._request_queue = Queue()

        self.azure_auth = None

        self._batch_fetch = False

    def verify_file(self, path):
        '''
            :param loader: an ansible.parsing.dataloader.DataLoader object
            :param path: the path to the inventory config file
            :return the contents of the config file
        '''
        if super(InventoryModule, self).verify_file(path):
            if re.match(r'.{0,}azure_rm\.y(a)?ml$', path):
                return True
        # display.debug("azure_rm inventory filename must end with 'azure_rm.yml' or 'azure_rm.yaml'")
        return False

    def parse(self, inventory, loader, path, cache=True):
        super(InventoryModule, self).parse(inventory, loader, path)

        self._read_config_data(path)

        if self.get_option('use_contrib_script_compatible_sanitization'):
            self._sanitize_group_name = self._legacy_script_compatible_group_sanitization

        self._batch_fetch = self.get_option('batch_fetch')

        self._legacy_hostnames = self.get_option('plain_host_names')

        self._filters = self.get_option(
            'exclude_host_filters') + self.get_option('default_host_filters')

        try:
            self._credential_setup()
            self._get_hosts()
        except Exception:
            raise

    def _credential_setup(self):
        auth_options = dict(
            auth_source=self.get_option('auth_source'),
            profile=self.get_option('profile'),
            subscription_id=self.get_option('subscription_id'),
            client_id=self.get_option('client_id'),
            secret=self.get_option('secret'),
            tenant=self.get_option('tenant'),
            ad_user=self.get_option('ad_user'),
            password=self.get_option('password'),
            cloud_environment=self.get_option('cloud_environment'),
            cert_validation_mode=self.get_option('cert_validation_mode'),
            api_profile=self.get_option('api_profile'),
            adfs_authority_url=self.get_option('adfs_authority_url'))

        self.azure_auth = AzureRMAuth(**auth_options)

        self._clientconfig = AzureRMRestConfiguration(
            self.azure_auth.azure_credentials, self.azure_auth.subscription_id,
            self.azure_auth._cloud_environment.endpoints.resource_manager)
        self._client = ServiceClient(self._clientconfig.credentials,
                                     self._clientconfig)

    def _enqueue_get(self, url, api_version, handler, handler_args=None):
        if not handler_args:
            handler_args = {}
        self._request_queue.put_nowait(
            UrlAction(url=url,
                      api_version=api_version,
                      handler=handler,
                      handler_args=handler_args))

    def _enqueue_vm_list(self, rg='*'):
        if not rg or rg == '*':
            url = '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachines'
        else:
            url = '/subscriptions/{subscriptionId}/resourceGroups/{rg}/providers/Microsoft.Compute/virtualMachines'

        url = url.format(subscriptionId=self._clientconfig.subscription_id,
                         rg=rg)
        self._enqueue_get(url=url,
                          api_version=self._compute_api_version,
                          handler=self._on_vm_page_response)

    def _enqueue_vmss_list(self, rg=None):
        if not rg or rg == '*':
            url = '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachineScaleSets'
        else:
            url = '/subscriptions/{subscriptionId}/resourceGroups/{rg}/providers/Microsoft.Compute/virtualMachineScaleSets'

        url = url.format(subscriptionId=self._clientconfig.subscription_id,
                         rg=rg)
        self._enqueue_get(url=url,
                          api_version=self._compute_api_version,
                          handler=self._on_vmss_page_response)

    def _get_hosts(self):
        for vm_rg in self.get_option('include_vm_resource_groups'):
            self._enqueue_vm_list(vm_rg)

        for vmss_rg in self.get_option('include_vmss_resource_groups'):
            self._enqueue_vmss_list(vmss_rg)

        if self._batch_fetch:
            self._process_queue_batch()
        else:
            self._process_queue_serial()

        constructable_config_strict = boolean(
            self.get_option('fail_on_template_errors'))
        constructable_config_compose = self.get_option('hostvar_expressions')
        constructable_config_groups = self.get_option('conditional_groups')
        constructable_config_keyed_groups = self.get_option('keyed_groups')

        for h in self._hosts:
            inventory_hostname = self._get_hostname(h)
            if self._filter_host(inventory_hostname, h.hostvars):
                continue
            self.inventory.add_host(inventory_hostname)
            # FUTURE: configurable default IP list? can already do this via hostvar_expressions
            self.inventory.set_variable(
                inventory_hostname, "ansible_host",
                next(
                    chain(h.hostvars['public_ipv4_addresses'],
                          h.hostvars['private_ipv4_addresses']), None))
            for k, v in iteritems(h.hostvars):
                # FUTURE: configurable hostvar prefix? Makes docs harder...
                self.inventory.set_variable(inventory_hostname, k, v)

            # constructable delegation
            self._set_composite_vars(constructable_config_compose,
                                     h.hostvars,
                                     inventory_hostname,
                                     strict=constructable_config_strict)
            self._add_host_to_composed_groups(
                constructable_config_groups,
                h.hostvars,
                inventory_hostname,
                strict=constructable_config_strict)
            self._add_host_to_keyed_groups(constructable_config_keyed_groups,
                                           h.hostvars,
                                           inventory_hostname,
                                           strict=constructable_config_strict)

    # FUTURE: fix underlying inventory stuff to allow us to quickly access known groupvars from reconciled host
    def _filter_host(self, inventory_hostname, hostvars):
        self.templar.available_variables = hostvars

        for condition in self._filters:
            # FUTURE: should warn/fail if conditional doesn't return True or False
            conditional = "{{% if {0} %}} True {{% else %}} False {{% endif %}}".format(
                condition)
            try:
                if boolean(self.templar.template(conditional)):
                    return True
            except Exception as e:
                if boolean(self.get_option('fail_on_template_errors')):
                    raise AnsibleParserError(
                        "Error evaluating filter condition '{0}' for host {1}: {2}"
                        .format(condition, inventory_hostname, to_native(e)))
                continue

        return False

    def _get_hostname(self, host):
        # FUTURE: configurable hostname sources
        return host.default_inventory_hostname

    def _process_queue_serial(self):
        try:
            while True:
                item = self._request_queue.get_nowait()
                resp = self.send_request(item.url, item.api_version)
                item.handler(resp, **item.handler_args)
        except Empty:
            pass

    def _on_vm_page_response(self, response, vmss=None):
        next_link = response.get('nextLink')

        if next_link:
            self._enqueue_get(url=next_link,
                              api_version=self._compute_api_version,
                              handler=self._on_vm_page_response)

        if 'value' in response:
            for h in response['value']:
                # FUTURE: add direct VM filtering by tag here (performance optimization)?
                self._hosts.append(
                    AzureHost(h,
                              self,
                              vmss=vmss,
                              legacy_name=self._legacy_hostnames))

    def _on_vmss_page_response(self, response):
        next_link = response.get('nextLink')

        if next_link:
            self._enqueue_get(url=next_link,
                              api_version=self._compute_api_version,
                              handler=self._on_vmss_page_response)

        # FUTURE: add direct VMSS filtering by tag here (performance optimization)?
        for vmss in response['value']:
            url = '{0}/virtualMachines'.format(vmss['id'])
            # VMSS instances look close enough to regular VMs that we can share the handler impl...
            self._enqueue_get(url=url,
                              api_version=self._compute_api_version,
                              handler=self._on_vm_page_response,
                              handler_args=dict(vmss=vmss))

    # use the undocumented /batch endpoint to bulk-send up to 500 requests in a single round-trip
    #
    def _process_queue_batch(self):
        while True:
            batch_requests = []
            batch_item_index = 0
            batch_response_handlers = dict()
            try:
                while batch_item_index < 100:
                    item = self._request_queue.get_nowait()

                    name = str(uuid.uuid4())
                    query_parameters = {'api-version': item.api_version}
                    req = self._client.get(item.url, query_parameters)
                    batch_requests.append(
                        dict(httpMethod="GET", url=req.url, name=name))
                    batch_response_handlers[name] = item
                    batch_item_index += 1
            except Empty:
                pass

            if not batch_requests:
                break

            batch_resp = self._send_batch(batch_requests)

            key_name = None
            if 'responses' in batch_resp:
                key_name = 'responses'
            elif 'value' in batch_resp:
                key_name = 'value'
            else:
                raise AnsibleError(
                    "didn't find expected key responses/value in batch response"
                )

            for idx, r in enumerate(batch_resp[key_name]):
                status_code = r.get('httpStatusCode')
                returned_name = r['name']
                result = batch_response_handlers[returned_name]
                if status_code != 200:
                    # FUTURE: error-tolerant operation mode (eg, permissions)
                    raise AnsibleError(
                        "a batched request failed with status code {0}, url {1}"
                        .format(status_code, result.url))
                # FUTURE: store/handle errors from individual handlers
                result.handler(r['content'], **result.handler_args)

    def _send_batch(self, batched_requests):
        url = '/batch'
        query_parameters = {'api-version': '2015-11-01'}

        body_obj = dict(requests=batched_requests)

        body_content = self._serializer.body(body_obj, 'object')

        header = {'x-ms-client-request-id': str(uuid.uuid4())}
        header.update(self._default_header_parameters)

        request = self._client.post(url, query_parameters)
        initial_response = self._client.send(request, header, body_content)

        # FUTURE: configurable timeout?
        poller = ARMPolling(timeout=2)
        poller.initialize(
            client=self._client,
            initial_response=initial_response,
            deserialization_callback=lambda r: self._deserializer('object', r))

        poller.run()

        return poller.resource()

    def send_request(self, url, api_version):
        query_parameters = {'api-version': api_version}
        req = self._client.get(url, query_parameters)
        resp = self._client.send(req,
                                 self._default_header_parameters,
                                 stream=False)

        resp.raise_for_status()
        content = resp.content

        return json.loads(content)

    @staticmethod
    def _legacy_script_compatible_group_sanitization(name):

        # note that while this mirrors what the script used to do, it has many issues with unicode and usability in python
        regex = re.compile(r"[^A-Za-z0-9\_\-]")

        return regex.sub('_', name)
class AnomalyDetectorClient(SDKClient):
    """The Anomaly Detector API detects anomalies automatically in time series data. It supports two functionalities, one is for detecting the whole series with model trained by the timeseries, another is detecting last point with model trained by points before. By using this service, business customers can discover incidents and establish a logic flow for root cause analysis.

    :ivar config: Configuration for client.
    :vartype config: AnomalyDetectorClientConfiguration

    :param endpoint: Supported Cognitive Services endpoints (protocol and
     hostname, for example: https://westus2.api.cognitive.microsoft.com).
    :type endpoint: str
    :param credentials: Subscription credentials which uniquely identify
     client subscription.
    :type credentials: None
    """

    def __init__(
            self, endpoint, credentials):

        self.config = AnomalyDetectorClientConfiguration(endpoint, credentials)
        super(AnomalyDetectorClient, self).__init__(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self.api_version = '1.0'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)


    def entire_detect(
            self, body, custom_headers=None, raw=False, **operation_config):
        """Detect anomalies for the entire series in batch.

        This operation generates a model using an entire series, each point is
        detected with the same model. With this method, points before and after
        a certain point are used to determine whether it is an anomaly. The
        entire detection can give user an overall status of the time series.

        :param body: Time series points and period if needed. Advanced model
         parameters can also be set in the request.
        :type body: ~azure.cognitiveservices.anomalydetector.models.Request
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: EntireDetectResponse or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.anomalydetector.models.EntireDetectResponse
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`APIErrorException<azure.cognitiveservices.anomalydetector.models.APIErrorException>`
        """
        # Construct URL
        url = self.entire_detect.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, 'Request')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.APIErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('EntireDetectResponse', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    entire_detect.metadata = {'url': '/timeseries/entire/detect'}

    def last_detect(
            self, body, custom_headers=None, raw=False, **operation_config):
        """Detect anomaly status of the latest point in time series.

        This operation generates a model using points before the latest one.
        With this method, only historical points are used to determine whether
        the target point is an anomaly. The latest point detecting operation
        matches the scenario of real-time monitoring of business metrics.

        :param body: Time series points and period if needed. Advanced model
         parameters can also be set in the request.
        :type body: ~azure.cognitiveservices.anomalydetector.models.Request
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: LastDetectResponse or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.anomalydetector.models.LastDetectResponse or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`APIErrorException<azure.cognitiveservices.anomalydetector.models.APIErrorException>`
        """
        # Construct URL
        url = self.last_detect.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, 'Request')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.APIErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('LastDetectResponse', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    last_detect.metadata = {'url': '/timeseries/last/detect'}
Ejemplo n.º 14
0
class TestPlanClient(Client):
    """TestPlan
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """

    def __init__(self, base_url=None, creds=None):
        super(TestPlanClient, self).__init__(base_url, creds)
        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = None

    def create_test_configuration(self, test_configuration_create_update_parameters, project):
        """CreateTestConfiguration.
        [Preview API] Create a test configuration.
        :param :class:`<TestConfigurationCreateUpdateParameters> <azure.devops.v5_1.test_plan.models.TestConfigurationCreateUpdateParameters>` test_configuration_create_update_parameters: TestConfigurationCreateUpdateParameters
        :param str project: Project ID or project name
        :rtype: :class:`<TestConfiguration> <azure.devops.v5_1.test_plan.models.TestConfiguration>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        content = self._serialize.body(test_configuration_create_update_parameters, 'TestConfigurationCreateUpdateParameters')
        response = self._send(http_method='POST',
                              location_id='8369318e-38fa-4e84-9043-4b2a75d2c256',
                              version='5.1-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('TestConfiguration', response)

    def delete_test_confguration(self, project, test_configuartion_id):
        """DeleteTestConfguration.
        [Preview API] Delete a test configuration by its ID.
        :param str project: Project ID or project name
        :param int test_configuartion_id: ID of the test configuration to delete.
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        query_parameters = {}
        if test_configuartion_id is not None:
            query_parameters['testConfiguartionId'] = self._serialize.query('test_configuartion_id', test_configuartion_id, 'int')
        self._send(http_method='DELETE',
                   location_id='8369318e-38fa-4e84-9043-4b2a75d2c256',
                   version='5.1-preview.1',
                   route_values=route_values,
                   query_parameters=query_parameters)

    def get_test_configuration_by_id(self, project, test_configuration_id):
        """GetTestConfigurationById.
        [Preview API] Get a test configuration
        :param str project: Project ID or project name
        :param int test_configuration_id: ID of the test configuration to get.
        :rtype: :class:`<TestConfiguration> <azure.devops.v5_1.test_plan.models.TestConfiguration>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if test_configuration_id is not None:
            route_values['testConfigurationId'] = self._serialize.url('test_configuration_id', test_configuration_id, 'int')
        response = self._send(http_method='GET',
                              location_id='8369318e-38fa-4e84-9043-4b2a75d2c256',
                              version='5.1-preview.1',
                              route_values=route_values)
        return self._deserialize('TestConfiguration', response)

    def get_test_configurations(self, project, continuation_token=None):
        """GetTestConfigurations.
        [Preview API] Get a list of test configurations.
        :param str project: Project ID or project name
        :param str continuation_token: If the list of configurations returned is not complete, a continuation token to query next batch of configurations is included in the response header as "x-ms-continuationtoken". Omit this parameter to get the first batch of test configurations.
        :rtype: [TestConfiguration]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        query_parameters = {}
        if continuation_token is not None:
            query_parameters['continuationToken'] = self._serialize.query('continuation_token', continuation_token, 'str')
        response = self._send(http_method='GET',
                              location_id='8369318e-38fa-4e84-9043-4b2a75d2c256',
                              version='5.1-preview.1',
                              route_values=route_values,
                              query_parameters=query_parameters)
        return self._deserialize('[TestConfiguration]', self._unwrap_collection(response))

    def update_test_configuration(self, test_configuration_create_update_parameters, project, test_configuartion_id):
        """UpdateTestConfiguration.
        [Preview API] Update a test configuration by its ID.
        :param :class:`<TestConfigurationCreateUpdateParameters> <azure.devops.v5_1.test_plan.models.TestConfigurationCreateUpdateParameters>` test_configuration_create_update_parameters: TestConfigurationCreateUpdateParameters
        :param str project: Project ID or project name
        :param int test_configuartion_id: ID of the test configuration to update.
        :rtype: :class:`<TestConfiguration> <azure.devops.v5_1.test_plan.models.TestConfiguration>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        query_parameters = {}
        if test_configuartion_id is not None:
            query_parameters['testConfiguartionId'] = self._serialize.query('test_configuartion_id', test_configuartion_id, 'int')
        content = self._serialize.body(test_configuration_create_update_parameters, 'TestConfigurationCreateUpdateParameters')
        response = self._send(http_method='PATCH',
                              location_id='8369318e-38fa-4e84-9043-4b2a75d2c256',
                              version='5.1-preview.1',
                              route_values=route_values,
                              query_parameters=query_parameters,
                              content=content)
        return self._deserialize('TestConfiguration', response)

    def create_test_plan(self, test_plan_create_params, project):
        """CreateTestPlan.
        [Preview API] Create a test plan.
        :param :class:`<TestPlanCreateParams> <azure.devops.v5_1.test_plan.models.TestPlanCreateParams>` test_plan_create_params: A testPlanCreateParams object.TestPlanCreateParams
        :param str project: Project ID or project name
        :rtype: :class:`<TestPlan> <azure.devops.v5_1.test_plan.models.TestPlan>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        content = self._serialize.body(test_plan_create_params, 'TestPlanCreateParams')
        response = self._send(http_method='POST',
                              location_id='0e292477-a0c2-47f3-a9b6-34f153d627f4',
                              version='5.1-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('TestPlan', response)

    def delete_test_plan(self, project, plan_id):
        """DeleteTestPlan.
        [Preview API] Delete a test plan.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan to be deleted.
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        self._send(http_method='DELETE',
                   location_id='0e292477-a0c2-47f3-a9b6-34f153d627f4',
                   version='5.1-preview.1',
                   route_values=route_values)

    def get_test_plan_by_id(self, project, plan_id):
        """GetTestPlanById.
        [Preview API] Get a test plan by Id.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan to get.
        :rtype: :class:`<TestPlan> <azure.devops.v5_1.test_plan.models.TestPlan>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        response = self._send(http_method='GET',
                              location_id='0e292477-a0c2-47f3-a9b6-34f153d627f4',
                              version='5.1-preview.1',
                              route_values=route_values)
        return self._deserialize('TestPlan', response)

    def get_test_plans(self, project, owner=None, continuation_token=None, include_plan_details=None, filter_active_plans=None):
        """GetTestPlans.
        [Preview API] Get a list of test plans
        :param str project: Project ID or project name
        :param str owner: Filter for test plan by owner ID or name
        :param str continuation_token: If the list of plans returned is not complete, a continuation token to query next batch of plans is included in the response header as "x-ms-continuationtoken". Omit this parameter to get the first batch of test plans.
        :param bool include_plan_details: Get all properties of the test plan
        :param bool filter_active_plans: Get just the active plans
        :rtype: [TestPlan]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        query_parameters = {}
        if owner is not None:
            query_parameters['owner'] = self._serialize.query('owner', owner, 'str')
        if continuation_token is not None:
            query_parameters['continuationToken'] = self._serialize.query('continuation_token', continuation_token, 'str')
        if include_plan_details is not None:
            query_parameters['includePlanDetails'] = self._serialize.query('include_plan_details', include_plan_details, 'bool')
        if filter_active_plans is not None:
            query_parameters['filterActivePlans'] = self._serialize.query('filter_active_plans', filter_active_plans, 'bool')
        response = self._send(http_method='GET',
                              location_id='0e292477-a0c2-47f3-a9b6-34f153d627f4',
                              version='5.1-preview.1',
                              route_values=route_values,
                              query_parameters=query_parameters)
        return self._deserialize('[TestPlan]', self._unwrap_collection(response))

    def update_test_plan(self, test_plan_update_params, project, plan_id):
        """UpdateTestPlan.
        [Preview API] Update a test plan.
        :param :class:`<TestPlanUpdateParams> <azure.devops.v5_1.test_plan.models.TestPlanUpdateParams>` test_plan_update_params: A testPlanUpdateParams object.TestPlanUpdateParams
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan to be updated.
        :rtype: :class:`<TestPlan> <azure.devops.v5_1.test_plan.models.TestPlan>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        content = self._serialize.body(test_plan_update_params, 'TestPlanUpdateParams')
        response = self._send(http_method='PATCH',
                              location_id='0e292477-a0c2-47f3-a9b6-34f153d627f4',
                              version='5.1-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('TestPlan', response)

    def get_suite_entries(self, project, suite_id, suite_entry_type=None):
        """GetSuiteEntries.
        [Preview API] Get a list of test suite entries in the test suite.
        :param str project: Project ID or project name
        :param int suite_id: Id of the parent suite.
        :param str suite_entry_type:
        :rtype: [SuiteEntry]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url('suite_id', suite_id, 'int')
        query_parameters = {}
        if suite_entry_type is not None:
            query_parameters['suiteEntryType'] = self._serialize.query('suite_entry_type', suite_entry_type, 'str')
        response = self._send(http_method='GET',
                              location_id='d6733edf-72f1-4252-925b-c560dfe9b75a',
                              version='5.1-preview.1',
                              route_values=route_values,
                              query_parameters=query_parameters)
        return self._deserialize('[SuiteEntry]', self._unwrap_collection(response))

    def reorder_suite_entries(self, suite_entries, project, suite_id):
        """ReorderSuiteEntries.
        [Preview API] Reorder test suite entries in the test suite.
        :param [SuiteEntryUpdateParams] suite_entries: List of SuiteEntry to reorder.
        :param str project: Project ID or project name
        :param int suite_id: Id of the parent test suite.
        :rtype: [SuiteEntry]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url('suite_id', suite_id, 'int')
        content = self._serialize.body(suite_entries, '[SuiteEntryUpdateParams]')
        response = self._send(http_method='PATCH',
                              location_id='d6733edf-72f1-4252-925b-c560dfe9b75a',
                              version='5.1-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('[SuiteEntry]', self._unwrap_collection(response))

    def create_test_suite(self, test_suite_create_params, project, plan_id):
        """CreateTestSuite.
        [Preview API] Create test suite.
        :param :class:`<TestSuiteCreateParams> <azure.devops.v5_1.test_plan.models.TestSuiteCreateParams>` test_suite_create_params: Parameters for suite creation
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan that contains the suites.
        :rtype: :class:`<TestSuite> <azure.devops.v5_1.test_plan.models.TestSuite>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        content = self._serialize.body(test_suite_create_params, 'TestSuiteCreateParams')
        response = self._send(http_method='POST',
                              location_id='1046d5d3-ab61-4ca7-a65a-36118a978256',
                              version='5.1-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('TestSuite', response)

    def delete_test_suite(self, project, plan_id, suite_id):
        """DeleteTestSuite.
        [Preview API] Delete test suite.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan that contains the suite.
        :param int suite_id: ID of the test suite to delete.
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url('suite_id', suite_id, 'int')
        self._send(http_method='DELETE',
                   location_id='1046d5d3-ab61-4ca7-a65a-36118a978256',
                   version='5.1-preview.1',
                   route_values=route_values)

    def get_test_suite_by_id(self, project, plan_id, suite_id, expand=None):
        """GetTestSuiteById.
        [Preview API] Get test suite by suite id.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan that contains the suites.
        :param int suite_id: ID of the suite to get.
        :param str expand: Include the children suites and testers details
        :rtype: :class:`<TestSuite> <azure.devops.v5_1.test_plan.models.TestSuite>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url('suite_id', suite_id, 'int')
        query_parameters = {}
        if expand is not None:
            query_parameters['expand'] = self._serialize.query('expand', expand, 'str')
        response = self._send(http_method='GET',
                              location_id='1046d5d3-ab61-4ca7-a65a-36118a978256',
                              version='5.1-preview.1',
                              route_values=route_values,
                              query_parameters=query_parameters)
        return self._deserialize('TestSuite', response)

    def get_test_suites_for_plan(self, project, plan_id, expand=None, continuation_token=None, as_tree_view=None):
        """GetTestSuitesForPlan.
        [Preview API] Get test suites for plan.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan for which suites are requested.
        :param str expand: Include the children suites and testers details.
        :param str continuation_token: If the list of suites returned is not complete, a continuation token to query next batch of suites is included in the response header as "x-ms-continuationtoken". Omit this parameter to get the first batch of test suites.
        :param bool as_tree_view: If the suites returned should be in a tree structure.
        :rtype: [TestSuite]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        query_parameters = {}
        if expand is not None:
            query_parameters['expand'] = self._serialize.query('expand', expand, 'str')
        if continuation_token is not None:
            query_parameters['continuationToken'] = self._serialize.query('continuation_token', continuation_token, 'str')
        if as_tree_view is not None:
            query_parameters['asTreeView'] = self._serialize.query('as_tree_view', as_tree_view, 'bool')
        response = self._send(http_method='GET',
                              location_id='1046d5d3-ab61-4ca7-a65a-36118a978256',
                              version='5.1-preview.1',
                              route_values=route_values,
                              query_parameters=query_parameters)
        return self._deserialize('[TestSuite]', self._unwrap_collection(response))

    def update_test_suite(self, test_suite_update_params, project, plan_id, suite_id):
        """UpdateTestSuite.
        [Preview API] Update test suite.
        :param :class:`<TestSuiteUpdateParams> <azure.devops.v5_1.test_plan.models.TestSuiteUpdateParams>` test_suite_update_params: Parameters for suite updation
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan that contains the suites.
        :param int suite_id: ID of the parent suite.
        :rtype: :class:`<TestSuite> <azure.devops.v5_1.test_plan.models.TestSuite>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url('suite_id', suite_id, 'int')
        content = self._serialize.body(test_suite_update_params, 'TestSuiteUpdateParams')
        response = self._send(http_method='PATCH',
                              location_id='1046d5d3-ab61-4ca7-a65a-36118a978256',
                              version='5.1-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('TestSuite', response)

    def get_suites_by_test_case_id(self, test_case_id):
        """GetSuitesByTestCaseId.
        [Preview API] Find the list of all test suites in which a given test case is present. This is helpful if you need to find out which test suites are using a test case, when you need to make changes to a test case.
        :param int test_case_id: ID of the test case for which suites need to be fetched.
        :rtype: [TestSuite]
        """
        query_parameters = {}
        if test_case_id is not None:
            query_parameters['testCaseId'] = self._serialize.query('test_case_id', test_case_id, 'int')
        response = self._send(http_method='GET',
                              location_id='a4080e84-f17b-4fad-84f1-7960b6525bf2',
                              version='5.1-preview.1',
                              query_parameters=query_parameters)
        return self._deserialize('[TestSuite]', self._unwrap_collection(response))

    def add_test_cases_to_suite(self, suite_test_case_create_update_parameters, project, plan_id, suite_id):
        """AddTestCasesToSuite.
        [Preview API] Add test cases to a suite with specified configurations
        :param [SuiteTestCaseCreateUpdateParameters] suite_test_case_create_update_parameters: SuiteTestCaseCreateUpdateParameters object.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan to which test cases are to be added.
        :param int suite_id: ID of the test suite to which test cases are to be added.
        :rtype: [TestCase]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url('suite_id', suite_id, 'int')
        content = self._serialize.body(suite_test_case_create_update_parameters, '[SuiteTestCaseCreateUpdateParameters]')
        response = self._send(http_method='POST',
                              location_id='a9bd61ac-45cf-4d13-9441-43dcd01edf8d',
                              version='5.1-preview.2',
                              route_values=route_values,
                              content=content)
        return self._deserialize('[TestCase]', self._unwrap_collection(response))

    def get_test_case(self, project, plan_id, suite_id, test_case_ids, wit_fields=None, return_identity_ref=None):
        """GetTestCase.
        [Preview API] Get Test Cases For a Suite.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan for which test cases are requested.
        :param int suite_id: ID of the test suite for which test cases are requested.
        :param str test_case_ids: Test Case Ids to be fetched.
        :param str wit_fields: Get the list of witFields.
        :param bool return_identity_ref: If set to true, returns all identity fields, like AssignedTo, ActivatedBy etc., as IdentityRef objects. If set to false, these fields are returned as unique names in string format. This is false by default.
        :rtype: [TestCase]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url('suite_id', suite_id, 'int')
        if test_case_ids is not None:
            route_values['testCaseIds'] = self._serialize.url('test_case_ids', test_case_ids, 'str')
        query_parameters = {}
        if wit_fields is not None:
            query_parameters['witFields'] = self._serialize.query('wit_fields', wit_fields, 'str')
        if return_identity_ref is not None:
            query_parameters['returnIdentityRef'] = self._serialize.query('return_identity_ref', return_identity_ref, 'bool')
        response = self._send(http_method='GET',
                              location_id='a9bd61ac-45cf-4d13-9441-43dcd01edf8d',
                              version='5.1-preview.2',
                              route_values=route_values,
                              query_parameters=query_parameters)
        return self._deserialize('[TestCase]', self._unwrap_collection(response))

    def get_test_case_list(self, project, plan_id, suite_id, test_ids=None, configuration_ids=None, wit_fields=None, continuation_token=None, return_identity_ref=None, expand=None):
        """GetTestCaseList.
        [Preview API] Get Test Case List return those test cases which have all the configuration Ids as mentioned in the optional paramter. If configuration Ids is null, it return all the test cases
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan for which test cases are requested.
        :param int suite_id: ID of the test suite for which test cases are requested.
        :param str test_ids: Test Case Ids to be fetched.
        :param str configuration_ids: Fetch Test Cases which contains all the configuration Ids specified.
        :param str wit_fields: Get the list of witFields.
        :param str continuation_token: If the list of test cases returned is not complete, a continuation token to query next batch of test cases is included in the response header as "x-ms-continuationtoken". Omit this parameter to get the first batch of test cases.
        :param bool return_identity_ref: If set to true, returns all identity fields, like AssignedTo, ActivatedBy etc., as IdentityRef objects. If set to false, these fields are returned as unique names in string format. This is false by default.
        :param bool expand: If set to false, will get a smaller payload containing only basic details about the suite test case object
        :rtype: [TestCase]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url('suite_id', suite_id, 'int')
        query_parameters = {}
        if test_ids is not None:
            query_parameters['testIds'] = self._serialize.query('test_ids', test_ids, 'str')
        if configuration_ids is not None:
            query_parameters['configurationIds'] = self._serialize.query('configuration_ids', configuration_ids, 'str')
        if wit_fields is not None:
            query_parameters['witFields'] = self._serialize.query('wit_fields', wit_fields, 'str')
        if continuation_token is not None:
            query_parameters['continuationToken'] = self._serialize.query('continuation_token', continuation_token, 'str')
        if return_identity_ref is not None:
            query_parameters['returnIdentityRef'] = self._serialize.query('return_identity_ref', return_identity_ref, 'bool')
        if expand is not None:
            query_parameters['expand'] = self._serialize.query('expand', expand, 'bool')
        response = self._send(http_method='GET',
                              location_id='a9bd61ac-45cf-4d13-9441-43dcd01edf8d',
                              version='5.1-preview.2',
                              route_values=route_values,
                              query_parameters=query_parameters)
        return self._deserialize('[TestCase]', self._unwrap_collection(response))

    def remove_test_cases_from_suite(self, project, plan_id, suite_id, test_case_ids):
        """RemoveTestCasesFromSuite.
        [Preview API] Removes test cases from a suite based on the list of test case Ids provided.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan from which test cases are to be removed.
        :param int suite_id: ID of the test suite from which test cases are to be removed.
        :param str test_case_ids: Test Case Ids to be removed.
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url('suite_id', suite_id, 'int')
        if test_case_ids is not None:
            route_values['testCaseIds'] = self._serialize.url('test_case_ids', test_case_ids, 'str')
        self._send(http_method='DELETE',
                   location_id='a9bd61ac-45cf-4d13-9441-43dcd01edf8d',
                   version='5.1-preview.2',
                   route_values=route_values)

    def update_suite_test_cases(self, suite_test_case_create_update_parameters, project, plan_id, suite_id):
        """UpdateSuiteTestCases.
        [Preview API] Update the configurations for test cases
        :param [SuiteTestCaseCreateUpdateParameters] suite_test_case_create_update_parameters: A SuiteTestCaseCreateUpdateParameters object.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan to which test cases are to be updated.
        :param int suite_id: ID of the test suite to which test cases are to be updated.
        :rtype: [TestCase]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url('suite_id', suite_id, 'int')
        content = self._serialize.body(suite_test_case_create_update_parameters, '[SuiteTestCaseCreateUpdateParameters]')
        response = self._send(http_method='PATCH',
                              location_id='a9bd61ac-45cf-4d13-9441-43dcd01edf8d',
                              version='5.1-preview.2',
                              route_values=route_values,
                              content=content)
        return self._deserialize('[TestCase]', self._unwrap_collection(response))

    def delete_test_case(self, project, test_case_id):
        """DeleteTestCase.
        [Preview API] Delete a test case.
        :param str project: Project ID or project name
        :param int test_case_id: Id of test case to be deleted.
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if test_case_id is not None:
            route_values['testCaseId'] = self._serialize.url('test_case_id', test_case_id, 'int')
        self._send(http_method='DELETE',
                   location_id='29006fb5-816b-4ff7-a329-599943569229',
                   version='5.1-preview.1',
                   route_values=route_values)

    def clone_test_plan(self, clone_request_body, project, deep_clone=None):
        """CloneTestPlan.
        [Preview API] Clone test plan
        :param :class:`<CloneTestPlanParams> <azure.devops.v5_1.test_plan.models.CloneTestPlanParams>` clone_request_body: Plan Clone Request Body detail TestPlanCloneRequest
        :param str project: Project ID or project name
        :param bool deep_clone: Clones all the associated test cases as well
        :rtype: :class:`<CloneTestPlanOperationInformation> <azure.devops.v5_1.test_plan.models.CloneTestPlanOperationInformation>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        query_parameters = {}
        if deep_clone is not None:
            query_parameters['deepClone'] = self._serialize.query('deep_clone', deep_clone, 'bool')
        content = self._serialize.body(clone_request_body, 'CloneTestPlanParams')
        response = self._send(http_method='POST',
                              location_id='e65df662-d8a3-46c7-ae1c-14e2d4df57e1',
                              version='5.1-preview.2',
                              route_values=route_values,
                              query_parameters=query_parameters,
                              content=content)
        return self._deserialize('CloneTestPlanOperationInformation', response)

    def get_clone_information(self, project, clone_operation_id):
        """GetCloneInformation.
        [Preview API] Get clone information.
        :param str project: Project ID or project name
        :param int clone_operation_id: Operation ID returned when we queue a clone operation
        :rtype: :class:`<CloneTestPlanOperationInformation> <azure.devops.v5_1.test_plan.models.CloneTestPlanOperationInformation>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if clone_operation_id is not None:
            route_values['cloneOperationId'] = self._serialize.url('clone_operation_id', clone_operation_id, 'int')
        response = self._send(http_method='GET',
                              location_id='e65df662-d8a3-46c7-ae1c-14e2d4df57e1',
                              version='5.1-preview.2',
                              route_values=route_values)
        return self._deserialize('CloneTestPlanOperationInformation', response)

    def get_points(self, project, plan_id, suite_id, point_ids, return_identity_ref=None):
        """GetPoints.
        [Preview API] Get a list of points based on point Ids provided.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan for which test points are requested.
        :param int suite_id: ID of the test suite for which test points are requested.
        :param str point_ids: ID of test points to be fetched.
        :param bool return_identity_ref: If set to true, returns the AssignedTo field in TestCaseReference as IdentityRef object.
        :rtype: [TestPoint]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url('suite_id', suite_id, 'int')
        if point_ids is not None:
            route_values['pointIds'] = self._serialize.url('point_ids', point_ids, 'str')
        query_parameters = {}
        if return_identity_ref is not None:
            query_parameters['returnIdentityRef'] = self._serialize.query('return_identity_ref', return_identity_ref, 'bool')
        response = self._send(http_method='GET',
                              location_id='52df686e-bae4-4334-b0ee-b6cf4e6f6b73',
                              version='5.1-preview.2',
                              route_values=route_values,
                              query_parameters=query_parameters)
        return self._deserialize('[TestPoint]', self._unwrap_collection(response))

    def get_points_list(self, project, plan_id, suite_id, test_point_ids=None, test_case_id=None, continuation_token=None, return_identity_ref=None, include_point_details=None):
        """GetPointsList.
        [Preview API] Get all the points inside a suite based on some filters
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan for which test points are requested.
        :param int suite_id: ID of the test suite for which test points are requested
        :param str test_point_ids: ID of test points to fetch.
        :param str test_case_id: Get Test Points for specific test case Ids.
        :param str continuation_token: If the list of test point returned is not complete, a continuation token to query next batch of test points is included in the response header as "x-ms-continuationtoken". Omit this parameter to get the first batch of test points.
        :param bool return_identity_ref: If set to true, returns the AssignedTo field in TestCaseReference as IdentityRef object.
        :param bool include_point_details: If set to false, returns only necessary information
        :rtype: [TestPoint]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url('suite_id', suite_id, 'int')
        query_parameters = {}
        if test_point_ids is not None:
            query_parameters['testPointIds'] = self._serialize.query('test_point_ids', test_point_ids, 'str')
        if test_case_id is not None:
            query_parameters['testCaseId'] = self._serialize.query('test_case_id', test_case_id, 'str')
        if continuation_token is not None:
            query_parameters['continuationToken'] = self._serialize.query('continuation_token', continuation_token, 'str')
        if return_identity_ref is not None:
            query_parameters['returnIdentityRef'] = self._serialize.query('return_identity_ref', return_identity_ref, 'bool')
        if include_point_details is not None:
            query_parameters['includePointDetails'] = self._serialize.query('include_point_details', include_point_details, 'bool')
        response = self._send(http_method='GET',
                              location_id='52df686e-bae4-4334-b0ee-b6cf4e6f6b73',
                              version='5.1-preview.2',
                              route_values=route_values,
                              query_parameters=query_parameters)
        return self._deserialize('[TestPoint]', self._unwrap_collection(response))

    def update_test_points(self, test_point_update_params, project, plan_id, suite_id):
        """UpdateTestPoints.
        [Preview API] Update Test Points. This is used to Reset test point to active, update the outcome of a test point or update the tester of a test point
        :param [TestPointUpdateParams] test_point_update_params: A TestPointUpdateParams Object.
        :param str project: Project ID or project name
        :param int plan_id: ID of the test plan for which test points are requested.
        :param int suite_id: ID of the test suite for which test points are requested.
        :rtype: [TestPoint]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if plan_id is not None:
            route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int')
        if suite_id is not None:
            route_values['suiteId'] = self._serialize.url('suite_id', suite_id, 'int')
        content = self._serialize.body(test_point_update_params, '[TestPointUpdateParams]')
        response = self._send(http_method='PATCH',
                              location_id='52df686e-bae4-4334-b0ee-b6cf4e6f6b73',
                              version='5.1-preview.2',
                              route_values=route_values,
                              content=content)
        return self._deserialize('[TestPoint]', self._unwrap_collection(response))

    def clone_test_suite(self, clone_request_body, project, deep_clone=None):
        """CloneTestSuite.
        [Preview API] Clone test suite
        :param :class:`<CloneTestSuiteParams> <azure.devops.v5_1.test_plan.models.CloneTestSuiteParams>` clone_request_body: Suite Clone Request Body detail TestSuiteCloneRequest
        :param str project: Project ID or project name
        :param bool deep_clone: Clones all the associated test cases as well
        :rtype: :class:`<CloneTestSuiteOperationInformation> <azure.devops.v5_1.test_plan.models.CloneTestSuiteOperationInformation>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        query_parameters = {}
        if deep_clone is not None:
            query_parameters['deepClone'] = self._serialize.query('deep_clone', deep_clone, 'bool')
        content = self._serialize.body(clone_request_body, 'CloneTestSuiteParams')
        response = self._send(http_method='POST',
                              location_id='181d4c97-0e98-4ee2-ad6a-4cada675e555',
                              version='5.1-preview.2',
                              route_values=route_values,
                              query_parameters=query_parameters,
                              content=content)
        return self._deserialize('CloneTestSuiteOperationInformation', response)

    def get_suite_clone_information(self, project, clone_operation_id):
        """GetSuiteCloneInformation.
        [Preview API] Get clone information.
        :param str project: Project ID or project name
        :param int clone_operation_id: Operation ID returned when we queue a clone operation
        :rtype: :class:`<CloneTestSuiteOperationInformation> <azure.devops.v5_1.test_plan.models.CloneTestSuiteOperationInformation>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if clone_operation_id is not None:
            route_values['cloneOperationId'] = self._serialize.url('clone_operation_id', clone_operation_id, 'int')
        response = self._send(http_method='GET',
                              location_id='181d4c97-0e98-4ee2-ad6a-4cada675e555',
                              version='5.1-preview.2',
                              route_values=route_values)
        return self._deserialize('CloneTestSuiteOperationInformation', response)

    def create_test_variable(self, test_variable_create_update_parameters, project):
        """CreateTestVariable.
        [Preview API] Create a test variable.
        :param :class:`<TestVariableCreateUpdateParameters> <azure.devops.v5_1.test_plan.models.TestVariableCreateUpdateParameters>` test_variable_create_update_parameters: TestVariableCreateUpdateParameters
        :param str project: Project ID or project name
        :rtype: :class:`<TestVariable> <azure.devops.v5_1.test_plan.models.TestVariable>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        content = self._serialize.body(test_variable_create_update_parameters, 'TestVariableCreateUpdateParameters')
        response = self._send(http_method='POST',
                              location_id='2c61fac6-ac4e-45a5-8c38-1c2b8fd8ea6c',
                              version='5.1-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('TestVariable', response)

    def delete_test_variable(self, project, test_variable_id):
        """DeleteTestVariable.
        [Preview API] Delete a test variable by its ID.
        :param str project: Project ID or project name
        :param int test_variable_id: ID of the test variable to delete.
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if test_variable_id is not None:
            route_values['testVariableId'] = self._serialize.url('test_variable_id', test_variable_id, 'int')
        self._send(http_method='DELETE',
                   location_id='2c61fac6-ac4e-45a5-8c38-1c2b8fd8ea6c',
                   version='5.1-preview.1',
                   route_values=route_values)

    def get_test_variable_by_id(self, project, test_variable_id):
        """GetTestVariableById.
        [Preview API] Get a test variable by its ID.
        :param str project: Project ID or project name
        :param int test_variable_id: ID of the test variable to get.
        :rtype: :class:`<TestVariable> <azure.devops.v5_1.test_plan.models.TestVariable>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if test_variable_id is not None:
            route_values['testVariableId'] = self._serialize.url('test_variable_id', test_variable_id, 'int')
        response = self._send(http_method='GET',
                              location_id='2c61fac6-ac4e-45a5-8c38-1c2b8fd8ea6c',
                              version='5.1-preview.1',
                              route_values=route_values)
        return self._deserialize('TestVariable', response)

    def get_test_variables(self, project, continuation_token=None):
        """GetTestVariables.
        [Preview API] Get a list of test variables.
        :param str project: Project ID or project name
        :param str continuation_token: If the list of variables returned is not complete, a continuation token to query next batch of variables is included in the response header as "x-ms-continuationtoken". Omit this parameter to get the first batch of test variables.
        :rtype: [TestVariable]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        query_parameters = {}
        if continuation_token is not None:
            query_parameters['continuationToken'] = self._serialize.query('continuation_token', continuation_token, 'str')
        response = self._send(http_method='GET',
                              location_id='2c61fac6-ac4e-45a5-8c38-1c2b8fd8ea6c',
                              version='5.1-preview.1',
                              route_values=route_values,
                              query_parameters=query_parameters)
        return self._deserialize('[TestVariable]', self._unwrap_collection(response))

    def update_test_variable(self, test_variable_create_update_parameters, project, test_variable_id):
        """UpdateTestVariable.
        [Preview API] Update a test variable by its ID.
        :param :class:`<TestVariableCreateUpdateParameters> <azure.devops.v5_1.test_plan.models.TestVariableCreateUpdateParameters>` test_variable_create_update_parameters: TestVariableCreateUpdateParameters
        :param str project: Project ID or project name
        :param int test_variable_id: ID of the test variable to update.
        :rtype: :class:`<TestVariable> <azure.devops.v5_1.test_plan.models.TestVariable>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if test_variable_id is not None:
            route_values['testVariableId'] = self._serialize.url('test_variable_id', test_variable_id, 'int')
        content = self._serialize.body(test_variable_create_update_parameters, 'TestVariableCreateUpdateParameters')
        response = self._send(http_method='PATCH',
                              location_id='2c61fac6-ac4e-45a5-8c38-1c2b8fd8ea6c',
                              version='5.1-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('TestVariable', response)
class PredictionEndpoint(object):
    """PredictionEndpoint

    :ivar config: Configuration for client.
    :vartype config: PredictionEndpointConfiguration

    :param api_key:
    :type api_key: str
    :param str base_url: Service URL
    """

    def __init__(
            self, api_key, base_url=None):

        self.config = PredictionEndpointConfiguration(api_key, base_url)
        self._client = ServiceClient(None, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self.api_version = '1.1'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)


    def predict_image_url(
            self, project_id, iteration_id=None, application=None, url=None, custom_headers=None, raw=False, **operation_config):
        """Predict an image url and saves the result.

        :param project_id: The project id
        :type project_id: str
        :param iteration_id: Optional. Specifies the id of a particular
         iteration to evaluate against.
         The default iteration for the project will be used when not specified
        :type iteration_id: str
        :param application: Optional. Specifies the name of application using
         the endpoint
        :type application: str
        :param url:
        :type url: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ImagePredictionResultModel or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.vision.customvision.prediction.models.ImagePredictionResultModel
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        image_url = models.ImageUrl(url=url)

        # Construct URL
        url = '/{projectId}/url'
        path_format_arguments = {
            'projectId': self._serialize.url("project_id", project_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if iteration_id is not None:
            query_parameters['iterationId'] = self._serialize.query("iteration_id", iteration_id, 'str')
        if application is not None:
            query_parameters['application'] = self._serialize.query("application", application, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['Prediction-Key'] = self._serialize.header("self.config.api_key", self.config.api_key, 'str')

        # Construct body
        body_content = self._serialize.body(image_url, 'ImageUrl')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ImagePredictionResultModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def predict_image(
            self, project_id, image_data, iteration_id=None, application=None, custom_headers=None, raw=False, **operation_config):
        """Predict an image and saves the result.

        :param project_id: The project id
        :type project_id: str
        :param image_data:
        :type image_data: Generator
        :param iteration_id: Optional. Specifies the id of a particular
         iteration to evaluate against.
         The default iteration for the project will be used when not specified
        :type iteration_id: str
        :param application: Optional. Specifies the name of application using
         the endpoint
        :type application: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ImagePredictionResultModel or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.vision.customvision.prediction.models.ImagePredictionResultModel
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/{projectId}/image'
        path_format_arguments = {
            'projectId': self._serialize.url("project_id", project_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if iteration_id is not None:
            query_parameters['iterationId'] = self._serialize.query("iteration_id", iteration_id, 'str')
        if application is not None:
            query_parameters['application'] = self._serialize.query("application", application, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'multipart/form-data'
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['Prediction-Key'] = self._serialize.header("self.config.api_key", self.config.api_key, 'str')

        # Construct form data
        form_data_content = {
            'imageData': image_data,
        }

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send_formdata(
            request, header_parameters, form_data_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ImagePredictionResultModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def predict_image_url_with_no_store(
            self, project_id, iteration_id=None, application=None, url=None, custom_headers=None, raw=False, **operation_config):
        """Predict an image url without saving the result.

        :param project_id: The project id
        :type project_id: str
        :param iteration_id: Optional. Specifies the id of a particular
         iteration to evaluate against.
         The default iteration for the project will be used when not specified
        :type iteration_id: str
        :param application: Optional. Specifies the name of application using
         the endpoint
        :type application: str
        :param url:
        :type url: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ImagePredictionResultModel or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.vision.customvision.prediction.models.ImagePredictionResultModel
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        image_url = models.ImageUrl(url=url)

        # Construct URL
        url = '/{projectId}/url/nostore'
        path_format_arguments = {
            'projectId': self._serialize.url("project_id", project_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if iteration_id is not None:
            query_parameters['iterationId'] = self._serialize.query("iteration_id", iteration_id, 'str')
        if application is not None:
            query_parameters['application'] = self._serialize.query("application", application, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['Prediction-Key'] = self._serialize.header("self.config.api_key", self.config.api_key, 'str')

        # Construct body
        body_content = self._serialize.body(image_url, 'ImageUrl')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ImagePredictionResultModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def predict_image_with_no_store(
            self, project_id, image_data, iteration_id=None, application=None, custom_headers=None, raw=False, **operation_config):
        """Predict an image without saving the result.

        :param project_id: The project id
        :type project_id: str
        :param image_data:
        :type image_data: Generator
        :param iteration_id: Optional. Specifies the id of a particular
         iteration to evaluate against.
         The default iteration for the project will be used when not specified
        :type iteration_id: str
        :param application: Optional. Specifies the name of application using
         the endpoint
        :type application: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ImagePredictionResultModel or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.vision.customvision.prediction.models.ImagePredictionResultModel
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/{projectId}/image/nostore'
        path_format_arguments = {
            'projectId': self._serialize.url("project_id", project_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if iteration_id is not None:
            query_parameters['iterationId'] = self._serialize.query("iteration_id", iteration_id, 'str')
        if application is not None:
            query_parameters['application'] = self._serialize.query("application", application, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'multipart/form-data'
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['Prediction-Key'] = self._serialize.header("self.config.api_key", self.config.api_key, 'str')

        # Construct form data
        form_data_content = {
            'imageData': image_data,
        }

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send_formdata(
            request, header_parameters, form_data_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ImagePredictionResultModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
class EventGridClient(object):
    """EventGrid Client

    :ivar config: Configuration for client.
    :vartype config: EventGridClientConfiguration

    :param credentials: Subscription credentials which uniquely identify
     client subscription.
    :type credentials: None
    """

    def __init__(
            self, credentials):

        self.config = EventGridClientConfiguration(credentials)
        self._client = ServiceClient(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self.api_version = '2018-01-01'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)


    def publish_events(
            self, topic_hostname, events, custom_headers=None, raw=False, **operation_config):
        """Publishes a batch of events to an Azure Event Grid topic.

        :param topic_hostname: The host name of the topic, e.g.
         topic1.westus2-1.eventgrid.azure.net
        :type topic_hostname: str
        :param events: An array of events to be published to Event Grid.
        :type events: list[~azure.eventgrid.models.EventGridEvent]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/api/events'
        path_format_arguments = {
            'topicHostname': self._serialize.url("topic_hostname", topic_hostname, 'str', skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(events, '[EventGridEvent]')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response
class MixedRealityClient(SDKClient):
    """Mixed Reality Client

    :ivar config: Configuration for client.
    :vartype config: MixedRealityClientConfiguration

    :ivar operations: Operations operations
    :vartype operations: azure.mgmt.mixedreality.operations.Operations
    :ivar spatial_anchors_accounts: SpatialAnchorsAccounts operations
    :vartype spatial_anchors_accounts: azure.mgmt.mixedreality.operations.SpatialAnchorsAccountsOperations

    :param credentials: Credentials needed for the client to connect to Azure.
    :type credentials: :mod:`A msrestazure Credentials
     object<msrestazure.azure_active_directory>`
    :param subscription_id: Azure subscription ID.
    :type subscription_id: str
    :param str base_url: Service URL
    """

    def __init__(
            self, credentials, subscription_id, base_url=None):

        self.config = MixedRealityClientConfiguration(credentials, subscription_id, base_url)
        super(MixedRealityClient, self).__init__(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self.api_version = '2019-02-28-preview'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

        self.operations = Operations(
            self._client, self.config, self._serialize, self._deserialize)
        self.spatial_anchors_accounts = SpatialAnchorsAccountsOperations(
            self._client, self.config, self._serialize, self._deserialize)

    def check_name_availability_local(
            self, location, name, type, custom_headers=None, raw=False, **operation_config):
        """Check Name Availability for global uniqueness.

        :param location: The location in which uniqueness will be verified.
        :type location: str
        :param name: Resource Name To Verify
        :type name: str
        :param type: Fully qualified resource type which includes provider
         namespace
        :type type: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: CheckNameAvailabilityResponse or ClientRawResponse if
         raw=true
        :rtype: ~azure.mgmt.mixedreality.models.CheckNameAvailabilityResponse
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.mixedreality.models.ErrorResponseException>`
        """
        check_name_availability = models.CheckNameAvailabilityRequest(name=name, type=type)

        # Construct URL
        url = self.check_name_availability_local.metadata['url']
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
            'location': self._serialize.url("location", location, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(check_name_availability, 'CheckNameAvailabilityRequest')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('CheckNameAvailabilityResponse', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    check_name_availability_local.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.MixedReality/locations/{location}/checkNameAvailability'}
class CdnManagementClient(object):
    """Use these APIs to manage Azure CDN resources through the Azure Resource Manager. You must make sure that requests made to these resources are secure.

    :ivar config: Configuration for client.
    :vartype config: CdnManagementClientConfiguration

    :ivar profiles: Profiles operations
    :vartype profiles: .operations.ProfilesOperations
    :ivar endpoints: Endpoints operations
    :vartype endpoints: .operations.EndpointsOperations
    :ivar origins: Origins operations
    :vartype origins: .operations.OriginsOperations
    :ivar custom_domains: CustomDomains operations
    :vartype custom_domains: .operations.CustomDomainsOperations
    :ivar edge_nodes: EdgeNodes operations
    :vartype edge_nodes: .operations.EdgeNodesOperations

    :param credentials: Credentials needed for the client to connect to Azure.
    :type credentials: :mod:`A msrestazure Credentials
     object<msrestazure.azure_active_directory>`
    :param subscription_id: Azure Subscription ID.
    :type subscription_id: str
    :param api_version: Version of the API to be used with the client request.
     Current version is 2016-10-02.
    :type api_version: str
    :param accept_language: Gets or sets the preferred language for the
     response.
    :type accept_language: str
    :param long_running_operation_retry_timeout: Gets or sets the retry
     timeout in seconds for Long Running Operations. Default value is 30.
    :type long_running_operation_retry_timeout: int
    :param generate_client_request_id: When set to true a unique
     x-ms-client-request-id value is generated and included in each request.
     Default is true.
    :type generate_client_request_id: bool
    :param str base_url: Service URL
    :param str filepath: Existing config
    """

    def __init__(
        self,
        credentials,
        subscription_id,
        api_version="2016-10-02",
        accept_language="en-US",
        long_running_operation_retry_timeout=30,
        generate_client_request_id=True,
        base_url=None,
        filepath=None,
    ):

        self.config = CdnManagementClientConfiguration(
            credentials,
            subscription_id,
            api_version,
            accept_language,
            long_running_operation_retry_timeout,
            generate_client_request_id,
            base_url,
            filepath,
        )
        self._client = ServiceClient(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

        self.profiles = ProfilesOperations(self._client, self.config, self._serialize, self._deserialize)
        self.endpoints = EndpointsOperations(self._client, self.config, self._serialize, self._deserialize)
        self.origins = OriginsOperations(self._client, self.config, self._serialize, self._deserialize)
        self.custom_domains = CustomDomainsOperations(self._client, self.config, self._serialize, self._deserialize)
        self.edge_nodes = EdgeNodesOperations(self._client, self.config, self._serialize, self._deserialize)

    def check_name_availability(self, name, custom_headers=None, raw=False, **operation_config):
        """Check the availability of a resource name. This is needed for resources
        where name is globally unique, such as a CDN endpoint.

        :param name: The resource name to validate.
        :type name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`CheckNameAvailabilityOutput
         <azure.mgmt.cdn.models.CheckNameAvailabilityOutput>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`ErrorResponseException<azure.mgmt.cdn.models.ErrorResponseException>`
        """
        check_name_availability_input = models.CheckNameAvailabilityInput(name=name)

        # Construct URL
        url = "/providers/Microsoft.Cdn/checkNameAvailability"

        # Construct parameters
        query_parameters = {}
        query_parameters["api-version"] = self._serialize.query(
            "self.config.api_version", self.config.api_version, "str"
        )

        # Construct headers
        header_parameters = {}
        header_parameters["Content-Type"] = "application/json; charset=utf-8"
        if self.config.generate_client_request_id:
            header_parameters["x-ms-client-request-id"] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters["accept-language"] = self._serialize.header(
                "self.config.accept_language", self.config.accept_language, "str"
            )

        # Construct body
        body_content = self._serialize.body(check_name_availability_input, "CheckNameAvailabilityInput")

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize("CheckNameAvailabilityOutput", response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def check_resource_usage(self, custom_headers=None, raw=False, **operation_config):
        """Check the quota and actual usage of the CDN profiles under the given
        subscription.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`ResourceUsagePaged
         <azure.mgmt.cdn.models.ResourceUsagePaged>`
        :raises:
         :class:`ErrorResponseException<azure.mgmt.cdn.models.ErrorResponseException>`
        """

        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/checkResourceUsage"
                path_format_arguments = {
                    "subscriptionId": self._serialize.url(
                        "self.config.subscription_id", self.config.subscription_id, "str"
                    )
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                query_parameters["api-version"] = self._serialize.query(
                    "self.config.api_version", self.config.api_version, "str"
                )

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters["Content-Type"] = "application/json; charset=utf-8"
            if self.config.generate_client_request_id:
                header_parameters["x-ms-client-request-id"] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters["accept-language"] = self._serialize.header(
                    "self.config.accept_language", self.config.accept_language, "str"
                )

            # Construct and send request
            request = self._client.post(url, query_parameters)
            response = self._client.send(request, header_parameters, **operation_config)

            if response.status_code not in [200]:
                raise models.ErrorResponseException(self._deserialize, response)

            return response

        # Deserialize response
        deserialized = models.ResourceUsagePaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.ResourceUsagePaged(
                internal_paging, self._deserialize.dependencies, header_dict
            )
            return client_raw_response

        return deserialized

    def list_operations(self, custom_headers=None, raw=False, **operation_config):
        """Lists all of the available CDN REST API operations.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`OperationPaged <azure.mgmt.cdn.models.OperationPaged>`
        :raises:
         :class:`ErrorResponseException<azure.mgmt.cdn.models.ErrorResponseException>`
        """

        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = "/providers/Microsoft.Cdn/operations"

                # Construct parameters
                query_parameters = {}
                query_parameters["api-version"] = self._serialize.query(
                    "self.config.api_version", self.config.api_version, "str"
                )

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters["Content-Type"] = "application/json; charset=utf-8"
            if self.config.generate_client_request_id:
                header_parameters["x-ms-client-request-id"] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters["accept-language"] = self._serialize.header(
                    "self.config.accept_language", self.config.accept_language, "str"
                )

            # Construct and send request
            request = self._client.get(url, query_parameters)
            response = self._client.send(request, header_parameters, **operation_config)

            if response.status_code not in [200]:
                raise models.ErrorResponseException(self._deserialize, response)

            return response

        # Deserialize response
        deserialized = models.OperationPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.OperationPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized
Ejemplo n.º 19
0
class AutoRestValidationTest(object):
    """Test Infrastructure for AutoRest. No server backend exists for these tests.

    :ivar config: Configuration for client.
    :vartype config: AutoRestValidationTestConfiguration

    :param subscription_id: Subscription ID.
    :type subscription_id: str
    :param str base_url: Service URL
    """

    def __init__(
            self, subscription_id, base_url=None):

        self.config = AutoRestValidationTestConfiguration(subscription_id, base_url)
        self._client = ServiceClient(None, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self.api_version = '1.0.0'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)


    def validation_of_method_parameters(
            self, resource_group_name, id, custom_headers=None, raw=False, **operation_config):
        """Validates input parameters on the method. See swagger for details.

        :param resource_group_name: Required string between 3 and 10 chars
         with pattern [a-zA-Z0-9]+.
        :type resource_group_name: str
        :param id: Required int multiple of 10 from 100 to 1000.
        :type id: int
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: :class:`Product
         <fixtures.acceptancetestsvalidation.models.Product>` or
         :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if
         raw=true
        :rtype: :class:`Product
         <fixtures.acceptancetestsvalidation.models.Product>` or
         :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
        :raises:
         :class:`ErrorException<fixtures.acceptancetestsvalidation.models.ErrorException>`
        """
        # Construct URL
        url = '/fakepath/{subscriptionId}/{resourceGroupName}/{id}'
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=10, min_length=3, pattern=r'[a-zA-Z0-9]+'),
            'id': self._serialize.url("id", id, 'int', maximum=1000, minimum=100, multiple=10)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['apiVersion'] = self._serialize.query("self.api_version", self.api_version, 'str', pattern=r'\d{2}-\d{2}-\d{4}')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Product', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def validation_of_body(
            self, resource_group_name, id, body=None, custom_headers=None, raw=False, **operation_config):
        """Validates body parameters on the method. See swagger for details.

        :param resource_group_name: Required string between 3 and 10 chars
         with pattern [a-zA-Z0-9]+.
        :type resource_group_name: str
        :param id: Required int multiple of 10 from 100 to 1000.
        :type id: int
        :param body:
        :type body: :class:`Product
         <fixtures.acceptancetestsvalidation.models.Product>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: :class:`Product
         <fixtures.acceptancetestsvalidation.models.Product>` or
         :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if
         raw=true
        :rtype: :class:`Product
         <fixtures.acceptancetestsvalidation.models.Product>` or
         :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
        :raises:
         :class:`ErrorException<fixtures.acceptancetestsvalidation.models.ErrorException>`
        """
        # Construct URL
        url = '/fakepath/{subscriptionId}/{resourceGroupName}/{id}'
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=10, min_length=3, pattern=r'[a-zA-Z0-9]+'),
            'id': self._serialize.url("id", id, 'int', maximum=1000, minimum=100, multiple=10)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['apiVersion'] = self._serialize.query("self.api_version", self.api_version, 'str', pattern=r'\d{2}-\d{2}-\d{4}')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'Product')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Product', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def get_with_constant_in_path(
            self, custom_headers=None, raw=False, **operation_config):
        """

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or
         :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if
         raw=true
        :rtype: None or
         :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        constant_param = "constant"

        # Construct URL
        url = '/validation/constantsInPath/{constantParam}/value'
        path_format_arguments = {
            'constantParam': self._serialize.url("constant_param", constant_param, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def post_with_constant_in_body(
            self, body=None, custom_headers=None, raw=False, **operation_config):
        """

        :param body:
        :type body: :class:`Product
         <fixtures.acceptancetestsvalidation.models.Product>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: :class:`Product
         <fixtures.acceptancetestsvalidation.models.Product>` or
         :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if
         raw=true
        :rtype: :class:`Product
         <fixtures.acceptancetestsvalidation.models.Product>` or
         :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        constant_param = "constant"

        # Construct URL
        url = '/validation/constantsInPath/{constantParam}/value'
        path_format_arguments = {
            'constantParam': self._serialize.url("constant_param", constant_param, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'Product')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Product', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
class LogAnalyticsDataClient(SDKClient):
    """Log Analytics Data Plane Client

    :ivar config: Configuration for client.
    :vartype config: LogAnalyticsDataClientConfiguration

    :param credentials: Subscription credentials which uniquely identify
     client subscription.
    :type credentials: None
    :param str base_url: Service URL
    """

    def __init__(
            self, credentials, base_url=None):

        self.config = LogAnalyticsDataClientConfiguration(credentials, base_url)
        super(LogAnalyticsDataClient, self).__init__(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self.api_version = 'v1'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)


    def query(
            self, workspace_id, body, custom_headers=None, raw=False, **operation_config):
        """Execute an Analytics query.

        Executes an Analytics query for data.
        [Here](https://dev.loganalytics.io/documentation/Using-the-API) is an
        example for using POST with an Analytics query.

        :param workspace_id: ID of the workspace. This is Workspace ID from
         the Properties blade in the Azure portal.
        :type workspace_id: str
        :param body: The Analytics query. Learn more about the [Analytics
         query
         syntax](https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/)
        :type body: ~azure.loganalytics.models.QueryBody
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: QueryResults or ClientRawResponse if raw=true
        :rtype: ~azure.loganalytics.models.QueryResults or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.loganalytics.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.query.metadata['url']
        path_format_arguments = {
            'workspaceId': self._serialize.url("workspace_id", workspace_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, 'QueryBody')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('QueryResults', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    query.metadata = {'url': '/workspaces/{workspaceId}/query'}
Ejemplo n.º 21
0
class FormRecognizerClient(SDKClient):
    """Extracts information from forms and images into structured data based on a model created by a set of representative training forms.

    :ivar config: Configuration for client.
    :vartype config: FormRecognizerClientConfiguration

    :param endpoint: Supported Cognitive Services endpoints (protocol and
     hostname, for example: https://westus2.api.cognitive.microsoft.com).
    :type endpoint: str
    :param credentials: Subscription credentials which uniquely identify
     client subscription.
    :type credentials: None
    """
    def __init__(self, endpoint, credentials):

        self.config = FormRecognizerClientConfiguration(endpoint, credentials)
        super(FormRecognizerClient, self).__init__(self.config.credentials,
                                                   self.config)

        client_models = {
            k: v
            for k, v in models.__dict__.items() if isinstance(v, type)
        }
        self.api_version = '1.0-preview'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    def train_custom_model(self,
                           source,
                           custom_headers=None,
                           raw=False,
                           **operation_config):
        """Train Model.

        The train request must include a source parameter that is either an
        externally accessible Azure Storage blob container Uri (preferably a
        Shared Access Signature Uri) or valid path to a data folder in a
        locally mounted drive. When local paths are specified, they must follow
        the Linux/Unix path format and be an absolute path rooted to the input
        mount configuration
        setting value e.g., if '{Mounts:Input}' configuration setting value is
        '/input' then a valid source path would be '/input/contosodataset'. All
        data to be trained are expected to be under the source. Models are
        trained using documents that are of the following content type -
        'application/pdf', 'image/jpeg' and 'image/png'."
        Other content is ignored when training a model.

        :param source: Get or set source path.
        :type source: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: TrainResult or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.formrecognizer.models.TrainResult or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.formrecognizer.models.ErrorResponseException>`
        """
        train_request = models.TrainRequest(source=source)

        # Construct URL
        url = self.train_custom_model.metadata['url']
        path_format_arguments = {
            'Endpoint':
            self._serialize.url("self.config.endpoint",
                                self.config.endpoint,
                                'str',
                                skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(train_request, 'TrainRequest')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters,
                                    body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('TrainResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    train_custom_model.metadata = {'url': '/custom/train'}

    def get_extracted_keys(self,
                           id,
                           custom_headers=None,
                           raw=False,
                           **operation_config):
        """Get Keys.

        Use the API to retrieve the keys that were
        extracted by the specified model.

        :param id: Model identifier.
        :type id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: KeysResult or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.formrecognizer.models.KeysResult or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.formrecognizer.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.get_extracted_keys.metadata['url']
        path_format_arguments = {
            'Endpoint':
            self._serialize.url("self.config.endpoint",
                                self.config.endpoint,
                                'str',
                                skip_quote=True),
            'id':
            self._serialize.url("id", id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('KeysResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    get_extracted_keys.metadata = {'url': '/custom/models/{id}/keys'}

    def get_custom_models(self,
                          custom_headers=None,
                          raw=False,
                          **operation_config):
        """Get Models.

        Get information about all trained models.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ModelsResult or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.formrecognizer.models.ModelsResult or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.formrecognizer.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.get_custom_models.metadata['url']
        path_format_arguments = {
            'Endpoint':
            self._serialize.url("self.config.endpoint",
                                self.config.endpoint,
                                'str',
                                skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ModelsResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    get_custom_models.metadata = {'url': '/custom/models'}

    def get_custom_model(self,
                         id,
                         custom_headers=None,
                         raw=False,
                         **operation_config):
        """Get Model.

        Get information about a model.

        :param id: Model identifier.
        :type id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ModelResult or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.formrecognizer.models.ModelResult or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.formrecognizer.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.get_custom_model.metadata['url']
        path_format_arguments = {
            'Endpoint':
            self._serialize.url("self.config.endpoint",
                                self.config.endpoint,
                                'str',
                                skip_quote=True),
            'id':
            self._serialize.url("id", id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ModelResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    get_custom_model.metadata = {'url': '/custom/models/{id}'}

    def delete_custom_model(self,
                            id,
                            custom_headers=None,
                            raw=False,
                            **operation_config):
        """Delete Model.

        Delete model artifacts.

        :param id: The identifier of the model to delete.
        :type id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.formrecognizer.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.delete_custom_model.metadata['url']
        path_format_arguments = {
            'Endpoint':
            self._serialize.url("self.config.endpoint",
                                self.config.endpoint,
                                'str',
                                skip_quote=True),
            'id':
            self._serialize.url("id", id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.delete(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [204]:
            raise models.ErrorResponseException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    delete_custom_model.metadata = {'url': '/custom/models/{id}'}

    def analyze_with_custom_model(self,
                                  id,
                                  form_stream,
                                  keys=None,
                                  custom_headers=None,
                                  raw=False,
                                  **operation_config):
        """Analyze Form.

        The document to analyze must be of a supported content type -
        'application/pdf', 'image/jpeg' or 'image/png'. The response contains
        not just the extracted information of the analyzed form but also
        information about content that was not extracted along with a reason.

        :param id: Model Identifier to analyze the document with.
        :type id: str
        :param form_stream: A pdf document or image (jpg,png) file to analyze.
        :type form_stream: Generator
        :param keys: An optional list of known keys to extract the values for.
        :type keys: list[str]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: AnalyzeResult or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.formrecognizer.models.AnalyzeResult
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.formrecognizer.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.analyze_with_custom_model.metadata['url']
        path_format_arguments = {
            'Endpoint':
            self._serialize.url("self.config.endpoint",
                                self.config.endpoint,
                                'str',
                                skip_quote=True),
            'id':
            self._serialize.url("id", id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if keys is not None:
            query_parameters['keys'] = self._serialize.query("keys",
                                                             keys,
                                                             '[str]',
                                                             div=',')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'multipart/form-data'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct form data
        form_data_content = {
            'form_stream': form_stream,
        }

        # Construct and send request
        request = self._client.post(url,
                                    query_parameters,
                                    header_parameters,
                                    form_content=form_data_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('AnalyzeResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    analyze_with_custom_model.metadata = {'url': '/custom/models/{id}/analyze'}
class TextAnalyticsAPI(object):
    """The Text Analytics API is a suite of text analytics web services built with best-in-class Microsoft machine learning algorithms. The API can be used to analyze unstructured text for tasks such as sentiment analysis, key phrase extraction and language detection. No training data is needed to use this API; just bring your text data. This API uses advanced natural language processing techniques to deliver best in class predictions. Further documentation can be found in https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview

    :ivar config: Configuration for client.
    :vartype config: TextAnalyticsAPIConfiguration

    :param azure_region: Supported Azure regions for Cognitive Services
     endpoints. Possible values include: 'westus', 'westeurope',
     'southeastasia', 'eastus2', 'westcentralus', 'westus2', 'eastus',
     'southcentralus', 'northeurope', 'eastasia', 'australiaeast',
     'brazilsouth'
    :type azure_region: str or
     ~azure.cognitiveservices.language.textanalytics.models.AzureRegions
    :param credentials: Subscription credentials which uniquely identify
     client subscription.
    :type credentials: None
    """

    def __init__(
            self, azure_region, credentials):

        self.config = TextAnalyticsAPIConfiguration(azure_region, credentials)
        self._client = ServiceClient(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self.api_version = 'v2.0'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)


    def key_phrases(
            self, documents=None, custom_headers=None, raw=False, **operation_config):
        """The API returns a list of strings denoting the key talking points in
        the input text.

        We employ techniques from Microsoft Office's sophisticated Natural
        Language Processing toolkit. See the <a
        href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
        Analytics Documentation</a> for details about the languages that are
        supported by key phrase extraction.

        :param documents:
        :type documents:
         list[~azure.cognitiveservices.language.textanalytics.models.MultiLanguageInput]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: KeyPhraseBatchResult or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.language.textanalytics.models.KeyPhraseBatchResult
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.language.textanalytics.models.ErrorResponseException>`
        """
        input = models.MultiLanguageBatchInput(documents=documents)

        # Construct URL
        url = '/v2.0/keyPhrases'
        path_format_arguments = {
            'AzureRegion': self._serialize.url("self.config.azure_region", self.config.azure_region, 'AzureRegions', skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(input, 'MultiLanguageBatchInput')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('KeyPhraseBatchResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def detect_language(
            self, documents=None, custom_headers=None, raw=False, **operation_config):
        """The API returns the detected language and a numeric score between 0 and
        1.

        Scores close to 1 indicate 100% certainty that the identified language
        is true. A total of 120 languages are supported.

        :param documents:
        :type documents:
         list[~azure.cognitiveservices.language.textanalytics.models.Input]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: LanguageBatchResult or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.language.textanalytics.models.LanguageBatchResult
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.language.textanalytics.models.ErrorResponseException>`
        """
        input = models.BatchInput(documents=documents)

        # Construct URL
        url = '/v2.0/languages'
        path_format_arguments = {
            'AzureRegion': self._serialize.url("self.config.azure_region", self.config.azure_region, 'AzureRegions', skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(input, 'BatchInput')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('LanguageBatchResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def sentiment(
            self, documents=None, custom_headers=None, raw=False, **operation_config):
        """The API returns a numeric score between 0 and 1.

        Scores close to 1 indicate positive sentiment, while scores close to 0
        indicate negative sentiment. Sentiment score is generated using
        classification techniques. The input features to the classifier include
        n-grams, features generated from part-of-speech tags, and word
        embeddings. See the <a
        href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
        Analytics Documentation</a> for details about the languages that are
        supported by sentiment analysis.

        :param documents:
        :type documents:
         list[~azure.cognitiveservices.language.textanalytics.models.MultiLanguageInput]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: SentimentBatchResult or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.language.textanalytics.models.SentimentBatchResult
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.language.textanalytics.models.ErrorResponseException>`
        """
        input = models.MultiLanguageBatchInput(documents=documents)

        # Construct URL
        url = '/v2.0/sentiment'
        path_format_arguments = {
            'AzureRegion': self._serialize.url("self.config.azure_region", self.config.azure_region, 'AzureRegions', skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(input, 'MultiLanguageBatchInput')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('SentimentBatchResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
Ejemplo n.º 23
0
class TestRuntimeSerialized(unittest.TestCase):

    class TestObj(Model):

        _validation = {}
        _attribute_map = {
            'attr_a': {'key':'id', 'type':'str'},
            'attr_b': {'key':'AttrB', 'type':'int'},
            'attr_c': {'key':'Key_C', 'type': 'bool'},
            'attr_d': {'key':'AttrD', 'type':'[int]'},
            'attr_e': {'key':'AttrE', 'type': '{float}'}
            }

        def __init__(self):

            self.attr_a = None
            self.attr_b = None
            self.attr_c = None
            self.attr_d = None
            self.attr_e = None

        def __str__(self):
            return "Test_Object"

    def setUp(self):
        self.s = Serializer()
        return super(TestRuntimeSerialized, self).setUp()

    def test_obj_without_attr_map(self):
        """
        Test serializing an object with no attribute_map.
        """
        test_obj = type("BadTestObj", (), {})

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

    def test_obj_with_malformed_map(self):
        """
        Test serializing an object with a malformed attribute_map.
        """
        test_obj = type("BadTestObj", (Model,), {"_attribute_map":None})

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

        test_obj._attribute_map = {"attr":"val"}

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

        test_obj._attribute_map = {"attr":{"val":1}}

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

    def test_obj_with_mismatched_map(self):
        """
        Test serializing an object with mismatching attributes and map.
        """
        test_obj = type("BadTestObj", (Model,), {"_attribute_map":None})
        test_obj._attribute_map = {"abc":{"key":"ABC", "type":"str"}}

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

    def test_attr_none(self):
        """
        Test serializing an object with None attributes.
        """
        test_obj = self.TestObj()
        message = self.s._serialize(test_obj)

        self.assertIsInstance(message, dict)
        self.assertFalse('id' in message)

    def test_attr_int(self):
        """
        Test serializing an object with Int attributes.
        """
        test_obj = self.TestObj()
        self.TestObj._validation = {
            'attr_b': {'required': True},
        }
        test_obj.attr_b = None

        with self.assertRaises(ValidationError):
            self.s._serialize(test_obj)

        test_obj.attr_b = 25

        message = self.s._serialize(test_obj)
        self.assertEqual(message['AttrB'], int(test_obj.attr_b))

        test_obj.attr_b = "34534"

        message = self.s._serialize(test_obj)
        self.assertEqual(message['AttrB'], int(test_obj.attr_b))

        test_obj.attr_b = "NotANumber"

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

        self.TestObj._validation = {}

    def test_attr_str(self):
        """
        Test serializing an object with Str attributes.
        """
        test_obj = self.TestObj()
        self.TestObj._validation = {
            'attr_a': {'required': True},
        }
        test_obj.attr_a = None

        with self.assertRaises(ValidationError):
            self.s._serialize(test_obj)

        self.TestObj._validation = {}
        test_obj.attr_a = "TestString"

        message = self.s._serialize(test_obj)
        self.assertEqual(message['id'], str(test_obj.attr_a))

        test_obj.attr_a = 1234

        message = self.s._serialize(test_obj)
        self.assertEqual(message['id'], str(test_obj.attr_a))

        test_obj.attr_a = list()

        message = self.s._serialize(test_obj)
        self.assertEqual(message['id'], str(test_obj.attr_a))

        test_obj.attr_a = [1]

        message = self.s._serialize(test_obj)
        self.assertEqual(message['id'], str(test_obj.attr_a))

    def test_attr_bool(self):
        """
        Test serializing an object with bool attributes.
        """
        test_obj = self.TestObj()
        test_obj.attr_c = True

        message = self.s._serialize(test_obj)
        self.assertEqual(message['Key_C'], True)

        test_obj.attr_c = ""

        message = self.s._serialize(test_obj)
        self.assertTrue('Key_C' in message)

        test_obj.attr_c = None

        message = self.s._serialize(test_obj)
        self.assertFalse('Key_C' in message)

        test_obj.attr_c = "NotEmpty"

        message = self.s._serialize(test_obj)
        self.assertEqual(message['Key_C'], True)

    def test_attr_sequence(self):
        """
        Test serializing a sequence.
        """

        test_obj = ["A", "B", "C"]
        output = self.s._serialize(test_obj, '[str]', div='|')
        self.assertEqual(output, "|".join(test_obj))

        test_obj = [1,2,3]
        output = self.s._serialize(test_obj, '[str]', div=',')
        self.assertEqual(output, ",".join([str(i) for i in test_obj]))

    def test_attr_list_simple(self):
        """
        Test serializing an object with simple-typed list attributes
        """
        test_obj = self.TestObj()
        test_obj.attr_d = []

        message = self.s._serialize(test_obj)
        self.assertEqual(message['AttrD'], test_obj.attr_d)

        test_obj.attr_d = [1,2,3]

        message = self.s._serialize(test_obj)
        self.assertEqual(message['AttrD'], test_obj.attr_d)

        test_obj.attr_d = ["1","2","3"]

        message = self.s._serialize(test_obj)
        self.assertEqual(message['AttrD'], [int(i) for i in test_obj.attr_d])

        test_obj.attr_d = ["test","test2","test3"]

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

        test_obj.attr_d = "NotAList"

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

    def test_empty_list(self):

        input = []
        output = self.s._serialize(input, '[str]')
        self.assertEqual(output, input)

    def test_attr_list_complex(self):
        """
        Test serializing an object with a list of complex objects as an attribute.
        """
        list_obj = type("ListObj", (Model,), {"_attribute_map":None,
                                        "_validation":{},
                                        "abc":None})
        list_obj._attribute_map = {"abc":{"key":"ABC", "type":"int"}}
        list_obj.abc = "123"

        test_obj = type("CmplxTestObj", (Model,), {"_attribute_map":None,
                                             "_validation":{},
                                             "test_list":None})

        test_obj._attribute_map = {"test_list":{"key":"_list", "type":"[ListObj]"}}
        test_obj.test_list = [list_obj]

        message = self.s._serialize(test_obj)
        self.assertEqual(message, {'_list':[{'ABC':123}]})

        list_obj = type("BadListObj", (Model,), {"map":None})
        test_obj._attribute_map = {"test_list":{"key":"_list", "type":"[BadListObj]"}}
        test_obj.test_list = [list_obj]

        s = self.s._serialize(test_obj)
        self.assertEqual(s, {'_list':[{}]})

    def test_attr_dict_simple(self):
        """
        Test serializing an object with a simple dictionary attribute.
        """

        test_obj = self.TestObj()
        test_obj.attr_e = {"value": 3.14}

        message = self.s._serialize(test_obj)
        self.assertEqual(message['AttrE']['value'], float(test_obj.attr_e["value"]))

        test_obj.attr_e = {1: "3.14"}

        message = self.s._serialize(test_obj)
        self.assertEqual(message['AttrE']['1'], float(test_obj.attr_e[1]))

        test_obj.attr_e = "NotADict"

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

        test_obj.attr_e = {"value": "NotAFloat"}

        with self.assertRaises(SerializationError):
            self.s._serialize(test_obj)

    def test_serialize_datetime(self):

        date_obj = isodate.parse_datetime('2015-01-01T00:00:00')
        date_str = Serializer.serialize_iso(date_obj)

        self.assertEqual(date_str, '2015-01-01T00:00:00.000Z')

        date_obj = isodate.parse_datetime('1999-12-31T23:59:59-12:00')
        date_str = Serializer.serialize_iso(date_obj)

        self.assertEqual(date_str, '2000-01-01T11:59:59.000Z')

        with self.assertRaises(SerializationError):
            date_obj = isodate.parse_datetime('9999-12-31T23:59:59-12:00')
            date_str = Serializer.serialize_iso(date_obj)

        with self.assertRaises(SerializationError):
            date_obj = isodate.parse_datetime('0001-01-01T00:00:00+23:59')
            date_str = Serializer.serialize_iso(date_obj)


        date_obj = isodate.parse_datetime("2015-06-01T16:10:08.0121-07:00")
        date_str = Serializer.serialize_iso(date_obj)

        self.assertEqual(date_str, '2015-06-01T23:10:08.0121Z')

        date_obj = datetime.min
        date_str = Serializer.serialize_iso(date_obj)
        self.assertEqual(date_str, '0001-01-01T00:00:00.000Z')

        date_obj = datetime.max
        date_str = Serializer.serialize_iso(date_obj)
        self.assertEqual(date_str, '9999-12-31T23:59:59.999999Z')


    def test_serialize_primitive_types(self):

        a = self.s.serialize_data(1, 'int')
        self.assertEqual(a, 1)

        b = self.s.serialize_data(True, 'bool')
        self.assertEqual(b, True)

        c = self.s.serialize_data('True', 'str')
        self.assertEqual(c, 'True')

        d = self.s.serialize_data(100.0123, 'float')
        self.assertEqual(d, 100.0123)

    def test_serialize_object(self):

        a = self.s.body(1, 'object')
        self.assertEqual(a, 1)

        b = self.s.body(True, 'object')
        self.assertEqual(b, True)

        c = self.s.serialize_data('True', 'object')
        self.assertEqual(c, 'True')

        d = self.s.serialize_data(100.0123, 'object')
        self.assertEqual(d, 100.0123)

        e = self.s.serialize_data({}, 'object')
        self.assertEqual(e, {})

        f = self.s.body({"test":"data"}, 'object')
        self.assertEqual(f, {"test":"data"})

        g = self.s.body({"test":{"value":"data"}}, 'object')
        self.assertEqual(g, {"test":{"value":"data"}})

        h = self.s.serialize_data({"test":self.TestObj()}, 'object')
        self.assertEqual(h, {"test":"Test_Object"})

        i =  self.s.serialize_data({"test":[1,2,3,4,5]}, 'object')
        self.assertEqual(i, {"test":[1,2,3,4,5]})

    def test_serialize_empty_iter(self):

        a = self.s.serialize_dict({}, 'int')
        self.assertEqual(a, {})

        b = self.s.serialize_iter([], 'int')
        self.assertEqual(b, [])

    def test_serialize_json_obj(self):

        class ComplexId(Model):

            _validation = {}
            _attribute_map = {'id':{'key':'id','type':'int'},
                              'name':{'key':'name','type':'str'},
                              'age':{'key':'age','type':'float'},
                              'male':{'key':'male','type':'bool'},
                              'birthday':{'key':'birthday','type':'iso-8601'},
                              'anniversary':{'key':'anniversary', 'type':'iso-8601'}}

            id = 1
            name = "Joey"
            age = 23.36
            male = True
            birthday = '1992-01-01T00:00:00.000Z'
            anniversary = isodate.parse_datetime('2013-12-08T00:00:00')

        class ComplexJson(Model):

            _validation = {}
            _attribute_map = {'p1':{'key':'p1','type':'str'},
                              'p2':{'key':'p2','type':'str'},
                              'top_date':{'key':'top_date', 'type':'iso-8601'},
                              'top_dates':{'key':'top_dates', 'type':'[iso-8601]'},
                              'insider':{'key':'insider','type':'{iso-8601}'},
                              'top_complex':{'key':'top_complex','type':'ComplexId'}}

            p1 = 'value1'
            p2 = 'value2'
            top_date = isodate.parse_datetime('2014-01-01T00:00:00')
            top_dates = [isodate.parse_datetime('1900-01-01T00:00:00'), isodate.parse_datetime('1901-01-01T00:00:00')]
            insider = {
                'k1': isodate.parse_datetime('2015-01-01T00:00:00'),
                'k2': isodate.parse_datetime('2016-01-01T00:00:00'),
                'k3': isodate.parse_datetime('2017-01-01T00:00:00')}
            top_complex = ComplexId()

        message =self.s._serialize(ComplexJson())

        output = { 
            'p1': 'value1', 
            'p2': 'value2', 
            'top_date': '2014-01-01T00:00:00.000Z', 
            'top_dates': [ 
                '1900-01-01T00:00:00.000Z', 
                '1901-01-01T00:00:00.000Z' 
            ], 
            'insider': {
                'k1': '2015-01-01T00:00:00.000Z', 
                'k2': '2016-01-01T00:00:00.000Z', 
                'k3': '2017-01-01T00:00:00.000Z' 
            }, 
            'top_complex': { 
                'id': 1, 
                'name': 'Joey', 
                'age': 23.36, 
                'male': True, 
                'birthday': '1992-01-01T00:00:00.000Z', 
                'anniversary': '2013-12-08T00:00:00.000Z', 
            } 
        }
        self.maxDiff = None
        self.assertEqual(message, output) 

    def test_polymorphic_serialization(self):

        self.maxDiff = None
        class Zoo(Model):

            _attribute_map = {
                "animals":{"key":"Animals", "type":"[Animal]"},
                }

            def __init__(self):
                self.animals = None

        class Animal(Model):

            _attribute_map = {
                "name":{"key":"Name", "type":"str"}
                }

            _subtype_map = {
                'dType': {"cat":"Cat", "dog":"Dog"}
                }

            def __init__(self):
                self.name = None

        class Dog(Animal):

            _attribute_map = {
                "name":{"key":"Name", "type":"str"},
                "likes_dog_food":{"key":"likesDogFood","type":"bool"}
                }

            def __init__(self):
                self.likes_dog_food = None
                super(Dog, self).__init__()

        class Cat(Animal):

            _attribute_map = {
                "name":{"key":"Name", "type":"str"},
                "likes_mice":{"key":"likesMice","type":"bool"},
                "dislikes":{"key":"dislikes","type":"Animal"}
                }

            _subtype_map = {
                "dType":{"siamese":"Siamese"}
                }

            def __init__(self):
                self.likes_mice = None
                self.dislikes = None
                super(Cat, self).__init__()

        class Siamese(Cat):

            _attribute_map = {
                "name":{"key":"Name", "type":"str"},
                "likes_mice":{"key":"likesMice","type":"bool"},
                "dislikes":{"key":"dislikes","type":"Animal"},
                "color":{"key":"Color", "type":"str"}
                }

            def __init__(self):
                self.color = None
                super(Siamese, self).__init__()

        message = {
            "Animals": [ 
            { 
            "dType": "dog", 
            "likesDogFood": True, 
            "Name": "Fido" 
            }, 
            { 
            "dType": "cat", 
            "likesMice": False, 
            "dislikes": { 
            "dType": "dog", 
            "likesDogFood": True, 
            "Name": "Angry" 
            }, 
            "Name": "Felix" 
            }, 
            { 
            "dType": "siamese", 
            "Color": "grey", 
            "likesMice": True, 
            "Name": "Finch" 
            }]}

        zoo = Zoo()
        angry = Dog()
        angry.name = "Angry"
        angry.likes_dog_food = True

        fido = Dog()
        fido.name = "Fido"
        fido.likes_dog_food = True

        felix = Cat()
        felix.name = "Felix"
        felix.likes_mice = False
        felix.dislikes = angry

        finch = Siamese()
        finch.name = "Finch"
        finch.color = "grey"
        finch.likes_mice = True

        zoo.animals = [fido, felix, finch]

        serialized = self.s._serialize(zoo)
        self.assertEqual(serialized, message)
Ejemplo n.º 24
0
class DashboardClient(VssClient):
    """Dashboard
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """

    def __init__(self, base_url=None, creds=None):
        super(DashboardClient, self).__init__(base_url, creds)
        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = '31c84e0a-3ece-48fd-a29d-100849af99ba'

    def create_dashboard(self, dashboard, team_context):
        """CreateDashboard.
        [Preview API]
        :param :class:`<Dashboard> <dashboard.v4_0.models.Dashboard>` dashboard:
        :param :class:`<TeamContext> <dashboard.v4_0.models.TeamContext>` team_context: The team context for the operation
        :rtype: :class:`<Dashboard> <dashboard.v4_0.models.Dashboard>`
        """
        project = None
        team = None
        if team_context is not None:
            if team_context.projectId:
                project = team_context.project_id
            else:
                project = team_context.project
            if team_context.teamId:
                team = team_context.team_id
            else:
                team = team_context.team

        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'string')
        if team is not None:
            route_values['team'] = self._serialize.url('team', team, 'string')
        content = self._serialize.body(dashboard, 'Dashboard')
        response = self._send(http_method='POST',
                              location_id='454b3e51-2e6e-48d4-ad81-978154089351',
                              version='4.0-preview.2',
                              route_values=route_values,
                              content=content)
        return self._deserialize('Dashboard', response)

    def delete_dashboard(self, team_context, dashboard_id):
        """DeleteDashboard.
        [Preview API]
        :param :class:`<TeamContext> <dashboard.v4_0.models.TeamContext>` team_context: The team context for the operation
        :param str dashboard_id:
        """
        project = None
        team = None
        if team_context is not None:
            if team_context.projectId:
                project = team_context.project_id
            else:
                project = team_context.project
            if team_context.teamId:
                team = team_context.team_id
            else:
                team = team_context.team

        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'string')
        if team is not None:
            route_values['team'] = self._serialize.url('team', team, 'string')
        if dashboard_id is not None:
            route_values['dashboardId'] = self._serialize.url('dashboard_id', dashboard_id, 'str')
        self._send(http_method='DELETE',
                   location_id='454b3e51-2e6e-48d4-ad81-978154089351',
                   version='4.0-preview.2',
                   route_values=route_values)

    def get_dashboard(self, team_context, dashboard_id):
        """GetDashboard.
        [Preview API]
        :param :class:`<TeamContext> <dashboard.v4_0.models.TeamContext>` team_context: The team context for the operation
        :param str dashboard_id:
        :rtype: :class:`<Dashboard> <dashboard.v4_0.models.Dashboard>`
        """
        project = None
        team = None
        if team_context is not None:
            if team_context.projectId:
                project = team_context.project_id
            else:
                project = team_context.project
            if team_context.teamId:
                team = team_context.team_id
            else:
                team = team_context.team

        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'string')
        if team is not None:
            route_values['team'] = self._serialize.url('team', team, 'string')
        if dashboard_id is not None:
            route_values['dashboardId'] = self._serialize.url('dashboard_id', dashboard_id, 'str')
        response = self._send(http_method='GET',
                              location_id='454b3e51-2e6e-48d4-ad81-978154089351',
                              version='4.0-preview.2',
                              route_values=route_values)
        return self._deserialize('Dashboard', response)

    def get_dashboards(self, team_context):
        """GetDashboards.
        [Preview API]
        :param :class:`<TeamContext> <dashboard.v4_0.models.TeamContext>` team_context: The team context for the operation
        :rtype: :class:`<DashboardGroup> <dashboard.v4_0.models.DashboardGroup>`
        """
        project = None
        team = None
        if team_context is not None:
            if team_context.projectId:
                project = team_context.project_id
            else:
                project = team_context.project
            if team_context.teamId:
                team = team_context.team_id
            else:
                team = team_context.team

        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'string')
        if team is not None:
            route_values['team'] = self._serialize.url('team', team, 'string')
        response = self._send(http_method='GET',
                              location_id='454b3e51-2e6e-48d4-ad81-978154089351',
                              version='4.0-preview.2',
                              route_values=route_values)
        return self._deserialize('DashboardGroup', response)

    def replace_dashboard(self, dashboard, team_context, dashboard_id):
        """ReplaceDashboard.
        [Preview API]
        :param :class:`<Dashboard> <dashboard.v4_0.models.Dashboard>` dashboard:
        :param :class:`<TeamContext> <dashboard.v4_0.models.TeamContext>` team_context: The team context for the operation
        :param str dashboard_id:
        :rtype: :class:`<Dashboard> <dashboard.v4_0.models.Dashboard>`
        """
        project = None
        team = None
        if team_context is not None:
            if team_context.projectId:
                project = team_context.project_id
            else:
                project = team_context.project
            if team_context.teamId:
                team = team_context.team_id
            else:
                team = team_context.team

        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'string')
        if team is not None:
            route_values['team'] = self._serialize.url('team', team, 'string')
        if dashboard_id is not None:
            route_values['dashboardId'] = self._serialize.url('dashboard_id', dashboard_id, 'str')
        content = self._serialize.body(dashboard, 'Dashboard')
        response = self._send(http_method='PUT',
                              location_id='454b3e51-2e6e-48d4-ad81-978154089351',
                              version='4.0-preview.2',
                              route_values=route_values,
                              content=content)
        return self._deserialize('Dashboard', response)

    def replace_dashboards(self, group, team_context):
        """ReplaceDashboards.
        [Preview API]
        :param :class:`<DashboardGroup> <dashboard.v4_0.models.DashboardGroup>` group:
        :param :class:`<TeamContext> <dashboard.v4_0.models.TeamContext>` team_context: The team context for the operation
        :rtype: :class:`<DashboardGroup> <dashboard.v4_0.models.DashboardGroup>`
        """
        project = None
        team = None
        if team_context is not None:
            if team_context.projectId:
                project = team_context.project_id
            else:
                project = team_context.project
            if team_context.teamId:
                team = team_context.team_id
            else:
                team = team_context.team

        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'string')
        if team is not None:
            route_values['team'] = self._serialize.url('team', team, 'string')
        content = self._serialize.body(group, 'DashboardGroup')
        response = self._send(http_method='PUT',
                              location_id='454b3e51-2e6e-48d4-ad81-978154089351',
                              version='4.0-preview.2',
                              route_values=route_values,
                              content=content)
        return self._deserialize('DashboardGroup', response)

    def create_widget(self, widget, team_context, dashboard_id):
        """CreateWidget.
        [Preview API]
        :param :class:`<Widget> <dashboard.v4_0.models.Widget>` widget:
        :param :class:`<TeamContext> <dashboard.v4_0.models.TeamContext>` team_context: The team context for the operation
        :param str dashboard_id:
        :rtype: :class:`<Widget> <dashboard.v4_0.models.Widget>`
        """
        project = None
        team = None
        if team_context is not None:
            if team_context.projectId:
                project = team_context.project_id
            else:
                project = team_context.project
            if team_context.teamId:
                team = team_context.team_id
            else:
                team = team_context.team

        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'string')
        if team is not None:
            route_values['team'] = self._serialize.url('team', team, 'string')
        if dashboard_id is not None:
            route_values['dashboardId'] = self._serialize.url('dashboard_id', dashboard_id, 'str')
        content = self._serialize.body(widget, 'Widget')
        response = self._send(http_method='POST',
                              location_id='bdcff53a-8355-4172-a00a-40497ea23afc',
                              version='4.0-preview.2',
                              route_values=route_values,
                              content=content)
        return self._deserialize('Widget', response)

    def delete_widget(self, team_context, dashboard_id, widget_id):
        """DeleteWidget.
        [Preview API]
        :param :class:`<TeamContext> <dashboard.v4_0.models.TeamContext>` team_context: The team context for the operation
        :param str dashboard_id:
        :param str widget_id:
        :rtype: :class:`<Dashboard> <dashboard.v4_0.models.Dashboard>`
        """
        project = None
        team = None
        if team_context is not None:
            if team_context.projectId:
                project = team_context.project_id
            else:
                project = team_context.project
            if team_context.teamId:
                team = team_context.team_id
            else:
                team = team_context.team

        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'string')
        if team is not None:
            route_values['team'] = self._serialize.url('team', team, 'string')
        if dashboard_id is not None:
            route_values['dashboardId'] = self._serialize.url('dashboard_id', dashboard_id, 'str')
        if widget_id is not None:
            route_values['widgetId'] = self._serialize.url('widget_id', widget_id, 'str')
        response = self._send(http_method='DELETE',
                              location_id='bdcff53a-8355-4172-a00a-40497ea23afc',
                              version='4.0-preview.2',
                              route_values=route_values)
        return self._deserialize('Dashboard', response)

    def get_widget(self, team_context, dashboard_id, widget_id):
        """GetWidget.
        [Preview API]
        :param :class:`<TeamContext> <dashboard.v4_0.models.TeamContext>` team_context: The team context for the operation
        :param str dashboard_id:
        :param str widget_id:
        :rtype: :class:`<Widget> <dashboard.v4_0.models.Widget>`
        """
        project = None
        team = None
        if team_context is not None:
            if team_context.projectId:
                project = team_context.project_id
            else:
                project = team_context.project
            if team_context.teamId:
                team = team_context.team_id
            else:
                team = team_context.team

        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'string')
        if team is not None:
            route_values['team'] = self._serialize.url('team', team, 'string')
        if dashboard_id is not None:
            route_values['dashboardId'] = self._serialize.url('dashboard_id', dashboard_id, 'str')
        if widget_id is not None:
            route_values['widgetId'] = self._serialize.url('widget_id', widget_id, 'str')
        response = self._send(http_method='GET',
                              location_id='bdcff53a-8355-4172-a00a-40497ea23afc',
                              version='4.0-preview.2',
                              route_values=route_values)
        return self._deserialize('Widget', response)

    def replace_widget(self, widget, team_context, dashboard_id, widget_id):
        """ReplaceWidget.
        [Preview API]
        :param :class:`<Widget> <dashboard.v4_0.models.Widget>` widget:
        :param :class:`<TeamContext> <dashboard.v4_0.models.TeamContext>` team_context: The team context for the operation
        :param str dashboard_id:
        :param str widget_id:
        :rtype: :class:`<Widget> <dashboard.v4_0.models.Widget>`
        """
        project = None
        team = None
        if team_context is not None:
            if team_context.projectId:
                project = team_context.project_id
            else:
                project = team_context.project
            if team_context.teamId:
                team = team_context.team_id
            else:
                team = team_context.team

        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'string')
        if team is not None:
            route_values['team'] = self._serialize.url('team', team, 'string')
        if dashboard_id is not None:
            route_values['dashboardId'] = self._serialize.url('dashboard_id', dashboard_id, 'str')
        if widget_id is not None:
            route_values['widgetId'] = self._serialize.url('widget_id', widget_id, 'str')
        content = self._serialize.body(widget, 'Widget')
        response = self._send(http_method='PUT',
                              location_id='bdcff53a-8355-4172-a00a-40497ea23afc',
                              version='4.0-preview.2',
                              route_values=route_values,
                              content=content)
        return self._deserialize('Widget', response)

    def update_widget(self, widget, team_context, dashboard_id, widget_id):
        """UpdateWidget.
        [Preview API]
        :param :class:`<Widget> <dashboard.v4_0.models.Widget>` widget:
        :param :class:`<TeamContext> <dashboard.v4_0.models.TeamContext>` team_context: The team context for the operation
        :param str dashboard_id:
        :param str widget_id:
        :rtype: :class:`<Widget> <dashboard.v4_0.models.Widget>`
        """
        project = None
        team = None
        if team_context is not None:
            if team_context.projectId:
                project = team_context.project_id
            else:
                project = team_context.project
            if team_context.teamId:
                team = team_context.team_id
            else:
                team = team_context.team

        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'string')
        if team is not None:
            route_values['team'] = self._serialize.url('team', team, 'string')
        if dashboard_id is not None:
            route_values['dashboardId'] = self._serialize.url('dashboard_id', dashboard_id, 'str')
        if widget_id is not None:
            route_values['widgetId'] = self._serialize.url('widget_id', widget_id, 'str')
        content = self._serialize.body(widget, 'Widget')
        response = self._send(http_method='PATCH',
                              location_id='bdcff53a-8355-4172-a00a-40497ea23afc',
                              version='4.0-preview.2',
                              route_values=route_values,
                              content=content)
        return self._deserialize('Widget', response)

    def get_widget_metadata(self, contribution_id):
        """GetWidgetMetadata.
        [Preview API]
        :param str contribution_id:
        :rtype: :class:`<WidgetMetadataResponse> <dashboard.v4_0.models.WidgetMetadataResponse>`
        """
        route_values = {}
        if contribution_id is not None:
            route_values['contributionId'] = self._serialize.url('contribution_id', contribution_id, 'str')
        response = self._send(http_method='GET',
                              location_id='6b3628d3-e96f-4fc7-b176-50240b03b515',
                              version='4.0-preview.1',
                              route_values=route_values)
        return self._deserialize('WidgetMetadataResponse', response)

    def get_widget_types(self, scope):
        """GetWidgetTypes.
        [Preview API] Returns available widgets in alphabetical order.
        :param str scope:
        :rtype: :class:`<WidgetTypesResponse> <dashboard.v4_0.models.WidgetTypesResponse>`
        """
        query_parameters = {}
        if scope is not None:
            query_parameters['$scope'] = self._serialize.query('scope', scope, 'str')
        response = self._send(http_method='GET',
                              location_id='6b3628d3-e96f-4fc7-b176-50240b03b515',
                              version='4.0-preview.1',
                              query_parameters=query_parameters)
        return self._deserialize('WidgetTypesResponse', response)
class AutoRestResourceFlatteningTestService(object):
    """Resource Flattening for AutoRest

    :param config: Configuration for client.
    :type config: AutoRestResourceFlatteningTestServiceConfiguration
    """

    def __init__(self, config):

        self._client = ServiceClient(config.credentials, config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self._serialize = Serializer()
        self._deserialize = Deserializer(client_models)

        self.config = config

    def put_array(
            self, resource_array=None, custom_headers={}, raw=False, **operation_config):
        """
        Put External Resource as an Array

        :param resource_array: External Resource as an Array to put
        :type resource_array: list or None
        :param dict custom_headers: headers that will be added to the request
        :param boolean raw: returns the direct response alongside the
         deserialized response
        :rtype: None or msrest.pipeline.ClientRawResponse
        """
        # Construct URL
        url = '/azure/resource-flatten/array'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        if resource_array is not None:
            body_content = self._serialize.body(resource_array, '[Resource]')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def get_array(
            self, custom_headers={}, raw=False, **operation_config):
        """
        Get External Resource as an Array

        :param dict custom_headers: headers that will be added to the request
        :param boolean raw: returns the direct response alongside the
         deserialized response
        :rtype: list or msrest.pipeline.ClientRawResponse
        """
        # Construct URL
        url = '/azure/resource-flatten/array'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('[FlattenedProduct]', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def put_dictionary(
            self, resource_dictionary=None, custom_headers={}, raw=False, **operation_config):
        """
        Put External Resource as a Dictionary

        :param resource_dictionary: External Resource as a Dictionary to put
        :type resource_dictionary: dict or None
        :param dict custom_headers: headers that will be added to the request
        :param boolean raw: returns the direct response alongside the
         deserialized response
        :rtype: None or msrest.pipeline.ClientRawResponse
        """
        # Construct URL
        url = '/azure/resource-flatten/dictionary'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        if resource_dictionary is not None:
            body_content = self._serialize.body(resource_dictionary, '{FlattenedProduct}')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def get_dictionary(
            self, custom_headers={}, raw=False, **operation_config):
        """
        Get External Resource as a Dictionary

        :param dict custom_headers: headers that will be added to the request
        :param boolean raw: returns the direct response alongside the
         deserialized response
        :rtype: dict or msrest.pipeline.ClientRawResponse
        """
        # Construct URL
        url = '/azure/resource-flatten/dictionary'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('{FlattenedProduct}', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def put_resource_collection(
            self, resource_complex_object=None, custom_headers={}, raw=False, **operation_config):
        """
        Put External Resource as a ResourceCollection

        :param resource_complex_object: External Resource as a
         ResourceCollection to put
        :type resource_complex_object: ResourceCollection or None
        :param dict custom_headers: headers that will be added to the request
        :param boolean raw: returns the direct response alongside the
         deserialized response
        :rtype: None or msrest.pipeline.ClientRawResponse
        """
        # Construct URL
        url = '/azure/resource-flatten/resourcecollection'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        if resource_complex_object is not None:
            body_content = self._serialize.body(resource_complex_object, 'ResourceCollection')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def get_resource_collection(
            self, custom_headers={}, raw=False, **operation_config):
        """
        Get External Resource as a ResourceCollection

        :param dict custom_headers: headers that will be added to the request
        :param boolean raw: returns the direct response alongside the
         deserialized response
        :rtype: ResourceCollection or msrest.pipeline.ClientRawResponse
        """
        # Construct URL
        url = '/azure/resource-flatten/resourcecollection'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ResourceCollection', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
Ejemplo n.º 26
0
class MetadataWrapperClient(SDKClient):
    """Api Documentation

    :ivar config: Configuration for client.
    :vartype config: MetadataWrapperClientConfiguration

    :param str base_url: Service URL
    """
    def __init__(self, base_url=None):

        self.config = MetadataWrapperClientConfiguration(base_url)
        super(MetadataWrapperClient, self).__init__(None, self.config)

        client_models = {}
        self.api_version = '1.0'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    def greeting_using_get(self,
                           custom_headers=None,
                           raw=False,
                           **operation_config):
        """greeting.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: str or ClientRawResponse if raw=true
        :rtype: str or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.greeting_using_get.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 401, 403, 404]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    greeting_using_get.metadata = {'url': '/'}

    def entity_post_using_post(self,
                               input,
                               custom_headers=None,
                               raw=False,
                               **operation_config):
        """Add new entity in atlas.

        :param input: {
         "entities": [
         {
         "typeName": "adls_gen2_resource_set",
         "createdBy": "sg",
         "attributes": {
         "qualifiedName": "/2019/",
         "name": "/2019/"
         }
         }
         ]
         }
        :type input: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: str or ClientRawResponse if raw=true
        :rtype: str or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.entity_post_using_post.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(input, 'str')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters,
                                    body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 201, 401, 403, 404]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    entity_post_using_post.metadata = {'url': '/api/entity'}

    def entity_bulk_get_using_get(self,
                                  input,
                                  custom_headers=None,
                                  raw=False,
                                  **operation_config):
        """entityBulkGet.

        :param input: input
        :type input: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: str or ClientRawResponse if raw=true
        :rtype: str or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.entity_bulk_get_using_get.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(input, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters,
                                   body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 401, 403, 404]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    entity_bulk_get_using_get.metadata = {'url': '/api/entity/bulk'}

    def entity_bulk_post_using_post(self,
                                    ip_json,
                                    custom_headers=None,
                                    raw=False,
                                    **operation_config):
        """entityBulkPost.

        :param ip_json: ipJSON
        :type ip_json: object
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: str or ClientRawResponse if raw=true
        :rtype: str or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.entity_bulk_post_using_post.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(ip_json, 'object')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters,
                                    body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 201, 401, 403, 404]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    entity_bulk_post_using_post.metadata = {'url': '/api/entity/bulk'}

    def entity_bulk_delete_using_delete(self,
                                        ip_json,
                                        custom_headers=None,
                                        raw=False,
                                        **operation_config):
        """entityBulkDelete.

        :param ip_json: ipJSON
        :type ip_json: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: str or ClientRawResponse if raw=true
        :rtype: str or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.entity_bulk_delete_using_delete.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(ip_json, 'str')

        # Construct and send request
        request = self._client.delete(url, query_parameters, header_parameters,
                                      body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 204, 401, 403]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    entity_bulk_delete_using_delete.metadata = {'url': '/api/entity/bulk'}

    def relationship_post_using_post(self,
                                     ip_json,
                                     custom_headers=None,
                                     raw=False,
                                     **operation_config):
        """relationshipPost.

        :param ip_json: ipJSON
        :type ip_json: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: str or ClientRawResponse if raw=true
        :rtype: str or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.relationship_post_using_post.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(ip_json, 'str')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters,
                                    body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 201, 401, 403, 404]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    relationship_post_using_post.metadata = {'url': '/api/relationship'}

    def relationship_bulk_post_using_put(self,
                                         ip_json,
                                         custom_headers=None,
                                         raw=False,
                                         **operation_config):
        """relationshipBulkPost.

        :param ip_json: ipJSON
        :type ip_json: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: str or ClientRawResponse if raw=true
        :rtype: str or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.relationship_bulk_post_using_put.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(ip_json, 'str')

        # Construct and send request
        request = self._client.put(url, query_parameters, header_parameters,
                                   body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 201, 401, 403, 404]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    relationship_bulk_post_using_put.metadata = {'url': '/api/relationship'}

    def relationship_guid_get_using_get(self,
                                        guid,
                                        custom_headers=None,
                                        raw=False,
                                        **operation_config):
        """relationshipGUIDGet.

        :param guid: guid
        :type guid: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: str or ClientRawResponse if raw=true
        :rtype: str or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.relationship_guid_get_using_get.metadata['url']
        path_format_arguments = {
            'guid': self._serialize.url("guid", guid, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 401, 403, 404]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    relationship_guid_get_using_get.metadata = {
        'url': '/api/relationship/guid/{guid}'
    }

    def relationship_guid_delete_using_delete(self,
                                              guid,
                                              custom_headers=None,
                                              raw=False,
                                              **operation_config):
        """relationshipGUIDDelete.

        :param guid: guid
        :type guid: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: str or ClientRawResponse if raw=true
        :rtype: str or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.relationship_guid_delete_using_delete.metadata['url']
        path_format_arguments = {
            'guid': self._serialize.url("guid", guid, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.delete(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 204, 401, 403]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    relationship_guid_delete_using_delete.metadata = {
        'url': '/api/relationship/guid/{guid}'
    }

    def search_basic_get_using_get(self,
                                   query,
                                   custom_headers=None,
                                   raw=False,
                                   **operation_config):
        """searchBasicGet.

        :param query: query
        :type query: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: str or ClientRawResponse if raw=true
        :rtype: str or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.search_basic_get_using_get.metadata['url']

        # Construct parameters
        query_parameters = {}
        query_parameters['query'] = self._serialize.query(
            "query", query, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 401, 403, 404]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    search_basic_get_using_get.metadata = {'url': '/api/search'}

    def typedefs_get_using_get(self,
                               ip_json,
                               custom_headers=None,
                               raw=False,
                               **operation_config):
        """typedefsGet.

        :param ip_json: ipJSON
        :type ip_json: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: str or ClientRawResponse if raw=true
        :rtype: str or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.typedefs_get_using_get.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(ip_json, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters,
                                   body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 401, 403, 404]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    typedefs_get_using_get.metadata = {'url': '/api/typedefs'}

    def typedefs_post_using_post(self,
                                 ip_json,
                                 custom_headers=None,
                                 raw=False,
                                 **operation_config):
        """typedefsPost.

        :param ip_json: ipJSON
        :type ip_json: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: str or ClientRawResponse if raw=true
        :rtype: str or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.typedefs_post_using_post.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(ip_json, 'str')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters,
                                    body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 201, 401, 403, 404]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    typedefs_post_using_post.metadata = {'url': '/api/typedefs'}

    def typedefs_put_using_put(self,
                               ip_json,
                               custom_headers=None,
                               raw=False,
                               **operation_config):
        """typedefsPut.

        :param ip_json: ipJSON
        :type ip_json: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: str or ClientRawResponse if raw=true
        :rtype: str or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.typedefs_put_using_put.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(ip_json, 'str')

        # Construct and send request
        request = self._client.put(url, query_parameters, header_parameters,
                                   body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 201, 401, 403, 404]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    typedefs_put_using_put.metadata = {'url': '/api/typedefs'}

    def typedefs_delete_using_delete(self,
                                     ip_json,
                                     custom_headers=None,
                                     raw=False,
                                     **operation_config):
        """typedefsDelete.

        :param ip_json: ipJSON
        :type ip_json: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: str or ClientRawResponse if raw=true
        :rtype: str or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.typedefs_delete_using_delete.metadata['url']

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(ip_json, 'str')

        # Construct and send request
        request = self._client.delete(url, query_parameters, header_parameters,
                                      body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 204, 401, 403]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    typedefs_delete_using_delete.metadata = {'url': '/api/typedefs'}
class FormRecognizerClient(SDKClient):
    """Extracts information from forms and images into structured data based on a model created by a set of representative training forms.

    :ivar config: Configuration for client.
    :vartype config: FormRecognizerClientConfiguration

    :param endpoint: Supported Cognitive Services endpoints (protocol and
     hostname, for example: https://westus2.api.cognitive.microsoft.com).
    :type endpoint: str
    :param credentials: Subscription credentials which uniquely identify
     client subscription.
    :type credentials: None
    """

    def __init__(
            self, endpoint, credentials):

        self.config = FormRecognizerClientConfiguration(endpoint, credentials)
        super(FormRecognizerClient, self).__init__(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self.api_version = '1.0-preview'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)


    def train_custom_model(
            self, source, custom_headers=None, raw=False, **operation_config):
        """Train Model.

        The train request must include a source parameter that is either an
        externally accessible Azure Storage blob container Uri (preferably a
        Shared Access Signature Uri) or valid path to a data folder in a
        locally mounted drive. When local paths are specified, they must follow
        the Linux/Unix path format and be an absolute path rooted to the input
        mount configuration
        setting value e.g., if '{Mounts:Input}' configuration setting value is
        '/input' then a valid source path would be '/input/contosodataset'. All
        data to be trained are expected to be under the source. Models are
        trained using documents that are of the following content type -
        'application/pdf', 'image/jpeg' and 'image/png'."
        Other content is ignored when training a model.

        :param source: Get or set source path.
        :type source: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: TrainResult or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.formrecognizer.models.TrainResult or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.formrecognizer.models.ErrorResponseException>`
        """
        train_request = models.TrainRequest(source=source)

        # Construct URL
        url = self.train_custom_model.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(train_request, 'TrainRequest')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('TrainResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    train_custom_model.metadata = {'url': '/custom/train'}

    def get_extracted_keys(
            self, id, custom_headers=None, raw=False, **operation_config):
        """Get Keys.

        Use the API to retrieve the keys that were
        extracted by the specified model.

        :param id: Model identifier.
        :type id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: KeysResult or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.formrecognizer.models.KeysResult or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.formrecognizer.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.get_extracted_keys.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'id': self._serialize.url("id", id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('KeysResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get_extracted_keys.metadata = {'url': '/custom/models/{id}/keys'}

    def get_custom_models(
            self, custom_headers=None, raw=False, **operation_config):
        """Get Models.

        Get information about all trained models.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ModelsResult or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.formrecognizer.models.ModelsResult or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.formrecognizer.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.get_custom_models.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ModelsResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get_custom_models.metadata = {'url': '/custom/models'}

    def get_custom_model(
            self, id, custom_headers=None, raw=False, **operation_config):
        """Get Model.

        Get information about a model.

        :param id: Model identifier.
        :type id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ModelResult or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.formrecognizer.models.ModelResult or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.formrecognizer.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.get_custom_model.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'id': self._serialize.url("id", id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ModelResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get_custom_model.metadata = {'url': '/custom/models/{id}'}

    def delete_custom_model(
            self, id, custom_headers=None, raw=False, **operation_config):
        """Delete Model.

        Delete model artifacts.

        :param id: The identifier of the model to delete.
        :type id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.formrecognizer.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.delete_custom_model.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'id': self._serialize.url("id", id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.delete(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [204]:
            raise models.ErrorResponseException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response
    delete_custom_model.metadata = {'url': '/custom/models/{id}'}

    def analyze_with_custom_model(
            self, id, form_stream, keys=None, custom_headers=None, raw=False, **operation_config):
        """Analyze Form.

        The document to analyze must be of a supported content type -
        'application/pdf', 'image/jpeg' or 'image/png'. The response contains
        not just the extracted information of the analyzed form but also
        information about content that was not extracted along with a reason.

        :param id: Model Identifier to analyze the document with.
        :type id: str
        :param form_stream: A pdf document or image (jpg,png) file to analyze.
        :type form_stream: Generator
        :param keys: An optional list of known keys to extract the values for.
        :type keys: list[str]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: AnalyzeResult or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.formrecognizer.models.AnalyzeResult
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.formrecognizer.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.analyze_with_custom_model.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'id': self._serialize.url("id", id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if keys is not None:
            query_parameters['keys'] = self._serialize.query("keys", keys, '[str]', div=',')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'multipart/form-data'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct form data
        form_data_content = {
            'form_stream': form_stream,
        }

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, form_content=form_data_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('AnalyzeResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    analyze_with_custom_model.metadata = {'url': '/custom/models/{id}/analyze'}
Ejemplo n.º 28
0
class TfvcClient(VssClient):
    """Tfvc
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """
    def __init__(self, base_url=None, creds=None):
        super(TfvcClient, self).__init__(base_url, creds)
        client_models = {
            k: v
            for k, v in models.__dict__.items() if isinstance(v, type)
        }
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = '8aa40520-446d-40e6-89f6-9c9f9ce44c48'

    def get_branch(self,
                   path,
                   project=None,
                   include_parent=None,
                   include_children=None):
        """GetBranch.
        Get a single branch hierarchy at the given path with parents or children as specified.
        :param str path: Full path to the branch.  Default: $/ Examples: $/, $/MyProject, $/MyProject/SomeFolder.
        :param str project: Project ID or project name
        :param bool include_parent: Return the parent branch, if there is one. Default: False
        :param bool include_children: Return child branches, if there are any. Default: False
        :rtype: :class:`<TfvcBranch> <tfvc.v4_1.models.TfvcBranch>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        query_parameters = {}
        if path is not None:
            query_parameters['path'] = self._serialize.query(
                'path', path, 'str')
        if include_parent is not None:
            query_parameters['includeParent'] = self._serialize.query(
                'include_parent', include_parent, 'bool')
        if include_children is not None:
            query_parameters['includeChildren'] = self._serialize.query(
                'include_children', include_children, 'bool')
        response = self._send(
            http_method='GET',
            location_id='bc1f417e-239d-42e7-85e1-76e80cb2d6eb',
            version='4.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('TfvcBranch', response)

    def get_branches(self,
                     project=None,
                     include_parent=None,
                     include_children=None,
                     include_deleted=None,
                     include_links=None):
        """GetBranches.
        Get a collection of branch roots -- first-level children, branches with no parents.
        :param str project: Project ID or project name
        :param bool include_parent: Return the parent branch, if there is one. Default: False
        :param bool include_children: Return the child branches for each root branch. Default: False
        :param bool include_deleted: Return deleted branches. Default: False
        :param bool include_links: Return links. Default: False
        :rtype: [TfvcBranch]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        query_parameters = {}
        if include_parent is not None:
            query_parameters['includeParent'] = self._serialize.query(
                'include_parent', include_parent, 'bool')
        if include_children is not None:
            query_parameters['includeChildren'] = self._serialize.query(
                'include_children', include_children, 'bool')
        if include_deleted is not None:
            query_parameters['includeDeleted'] = self._serialize.query(
                'include_deleted', include_deleted, 'bool')
        if include_links is not None:
            query_parameters['includeLinks'] = self._serialize.query(
                'include_links', include_links, 'bool')
        response = self._send(
            http_method='GET',
            location_id='bc1f417e-239d-42e7-85e1-76e80cb2d6eb',
            version='4.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[TfvcBranch]',
                                 self._unwrap_collection(response))

    def get_branch_refs(self,
                        scope_path,
                        project=None,
                        include_deleted=None,
                        include_links=None):
        """GetBranchRefs.
        Get branch hierarchies below the specified scopePath
        :param str scope_path: Full path to the branch.  Default: $/ Examples: $/, $/MyProject, $/MyProject/SomeFolder.
        :param str project: Project ID or project name
        :param bool include_deleted: Return deleted branches. Default: False
        :param bool include_links: Return links. Default: False
        :rtype: [TfvcBranchRef]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        query_parameters = {}
        if scope_path is not None:
            query_parameters['scopePath'] = self._serialize.query(
                'scope_path', scope_path, 'str')
        if include_deleted is not None:
            query_parameters['includeDeleted'] = self._serialize.query(
                'include_deleted', include_deleted, 'bool')
        if include_links is not None:
            query_parameters['includeLinks'] = self._serialize.query(
                'include_links', include_links, 'bool')
        response = self._send(
            http_method='GET',
            location_id='bc1f417e-239d-42e7-85e1-76e80cb2d6eb',
            version='4.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[TfvcBranchRef]',
                                 self._unwrap_collection(response))

    def get_changeset_changes(self, id=None, skip=None, top=None):
        """GetChangesetChanges.
        Retrieve Tfvc changes for a given changeset.
        :param int id: ID of the changeset. Default: null
        :param int skip: Number of results to skip. Default: null
        :param int top: The maximum number of results to return. Default: null
        :rtype: [TfvcChange]
        """
        route_values = {}
        if id is not None:
            route_values['id'] = self._serialize.url('id', id, 'int')
        query_parameters = {}
        if skip is not None:
            query_parameters['$skip'] = self._serialize.query(
                'skip', skip, 'int')
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        response = self._send(
            http_method='GET',
            location_id='f32b86f2-15b9-4fe6-81b1-6f8938617ee5',
            version='4.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[TfvcChange]',
                                 self._unwrap_collection(response))

    def create_changeset(self, changeset, project=None):
        """CreateChangeset.
        Create a new changeset.
        :param :class:`<TfvcChangeset> <tfvc.v4_1.models.TfvcChangeset>` changeset:
        :param str project: Project ID or project name
        :rtype: :class:`<TfvcChangesetRef> <tfvc.v4_1.models.TfvcChangesetRef>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        content = self._serialize.body(changeset, 'TfvcChangeset')
        response = self._send(
            http_method='POST',
            location_id='0bc8f0a4-6bfb-42a9-ba84-139da7b99c49',
            version='4.1',
            route_values=route_values,
            content=content)
        return self._deserialize('TfvcChangesetRef', response)

    def get_changeset(self,
                      id,
                      project=None,
                      max_change_count=None,
                      include_details=None,
                      include_work_items=None,
                      max_comment_length=None,
                      include_source_rename=None,
                      skip=None,
                      top=None,
                      orderby=None,
                      search_criteria=None):
        """GetChangeset.
        Retrieve a Tfvc Changeset
        :param int id: Changeset Id to retrieve.
        :param str project: Project ID or project name
        :param int max_change_count: Number of changes to return (maximum 100 changes) Default: 0
        :param bool include_details: Include policy details and check-in notes in the response. Default: false
        :param bool include_work_items: Include workitems. Default: false
        :param int max_comment_length: Include details about associated work items in the response. Default: null
        :param bool include_source_rename: Include renames.  Default: false
        :param int skip: Number of results to skip. Default: null
        :param int top: The maximum number of results to return. Default: null
        :param str orderby: Results are sorted by ID in descending order by default. Use id asc to sort by ID in ascending order.
        :param :class:`<TfvcChangesetSearchCriteria> <tfvc.v4_1.models.TfvcChangesetSearchCriteria>` search_criteria: Following criteria available (.itemPath, .version, .versionType, .versionOption, .author, .fromId, .toId, .fromDate, .toDate) Default: null
        :rtype: :class:`<TfvcChangeset> <tfvc.v4_1.models.TfvcChangeset>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if id is not None:
            route_values['id'] = self._serialize.url('id', id, 'int')
        query_parameters = {}
        if max_change_count is not None:
            query_parameters['maxChangeCount'] = self._serialize.query(
                'max_change_count', max_change_count, 'int')
        if include_details is not None:
            query_parameters['includeDetails'] = self._serialize.query(
                'include_details', include_details, 'bool')
        if include_work_items is not None:
            query_parameters['includeWorkItems'] = self._serialize.query(
                'include_work_items', include_work_items, 'bool')
        if max_comment_length is not None:
            query_parameters['maxCommentLength'] = self._serialize.query(
                'max_comment_length', max_comment_length, 'int')
        if include_source_rename is not None:
            query_parameters['includeSourceRename'] = self._serialize.query(
                'include_source_rename', include_source_rename, 'bool')
        if skip is not None:
            query_parameters['$skip'] = self._serialize.query(
                'skip', skip, 'int')
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        if orderby is not None:
            query_parameters['$orderby'] = self._serialize.query(
                'orderby', orderby, 'str')
        if search_criteria is not None:
            if search_criteria.item_path is not None:
                query_parameters[
                    'searchCriteria.itemPath'] = search_criteria.item_path
            if search_criteria.author is not None:
                query_parameters[
                    'searchCriteria.author'] = search_criteria.author
            if search_criteria.from_date is not None:
                query_parameters[
                    'searchCriteria.fromDate'] = search_criteria.from_date
            if search_criteria.to_date is not None:
                query_parameters[
                    'searchCriteria.toDate'] = search_criteria.to_date
            if search_criteria.from_id is not None:
                query_parameters[
                    'searchCriteria.fromId'] = search_criteria.from_id
            if search_criteria.to_id is not None:
                query_parameters['searchCriteria.toId'] = search_criteria.to_id
            if search_criteria.follow_renames is not None:
                query_parameters[
                    'searchCriteria.followRenames'] = search_criteria.follow_renames
            if search_criteria.include_links is not None:
                query_parameters[
                    'searchCriteria.includeLinks'] = search_criteria.include_links
        response = self._send(
            http_method='GET',
            location_id='0bc8f0a4-6bfb-42a9-ba84-139da7b99c49',
            version='4.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('TfvcChangeset', response)

    def get_changesets(self,
                       project=None,
                       max_comment_length=None,
                       skip=None,
                       top=None,
                       orderby=None,
                       search_criteria=None):
        """GetChangesets.
        Retrieve Tfvc Changesets
        :param str project: Project ID or project name
        :param int max_comment_length: Include details about associated work items in the response. Default: null
        :param int skip: Number of results to skip. Default: null
        :param int top: The maximum number of results to return. Default: null
        :param str orderby: Results are sorted by ID in descending order by default. Use id asc to sort by ID in ascending order.
        :param :class:`<TfvcChangesetSearchCriteria> <tfvc.v4_1.models.TfvcChangesetSearchCriteria>` search_criteria: Following criteria available (.itemPath, .version, .versionType, .versionOption, .author, .fromId, .toId, .fromDate, .toDate) Default: null
        :rtype: [TfvcChangesetRef]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        query_parameters = {}
        if max_comment_length is not None:
            query_parameters['maxCommentLength'] = self._serialize.query(
                'max_comment_length', max_comment_length, 'int')
        if skip is not None:
            query_parameters['$skip'] = self._serialize.query(
                'skip', skip, 'int')
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        if orderby is not None:
            query_parameters['$orderby'] = self._serialize.query(
                'orderby', orderby, 'str')
        if search_criteria is not None:
            if search_criteria.item_path is not None:
                query_parameters[
                    'searchCriteria.itemPath'] = search_criteria.item_path
            if search_criteria.author is not None:
                query_parameters[
                    'searchCriteria.author'] = search_criteria.author
            if search_criteria.from_date is not None:
                query_parameters[
                    'searchCriteria.fromDate'] = search_criteria.from_date
            if search_criteria.to_date is not None:
                query_parameters[
                    'searchCriteria.toDate'] = search_criteria.to_date
            if search_criteria.from_id is not None:
                query_parameters[
                    'searchCriteria.fromId'] = search_criteria.from_id
            if search_criteria.to_id is not None:
                query_parameters['searchCriteria.toId'] = search_criteria.to_id
            if search_criteria.follow_renames is not None:
                query_parameters[
                    'searchCriteria.followRenames'] = search_criteria.follow_renames
            if search_criteria.include_links is not None:
                query_parameters[
                    'searchCriteria.includeLinks'] = search_criteria.include_links
        response = self._send(
            http_method='GET',
            location_id='0bc8f0a4-6bfb-42a9-ba84-139da7b99c49',
            version='4.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[TfvcChangesetRef]',
                                 self._unwrap_collection(response))

    def get_batched_changesets(self, changesets_request_data):
        """GetBatchedChangesets.
        Returns changesets for a given list of changeset Ids.
        :param :class:`<TfvcChangesetsRequestData> <tfvc.v4_1.models.TfvcChangesetsRequestData>` changesets_request_data: List of changeset IDs.
        :rtype: [TfvcChangesetRef]
        """
        content = self._serialize.body(changesets_request_data,
                                       'TfvcChangesetsRequestData')
        response = self._send(
            http_method='POST',
            location_id='b7e7c173-803c-4fea-9ec8-31ee35c5502a',
            version='4.1',
            content=content)
        return self._deserialize('[TfvcChangesetRef]',
                                 self._unwrap_collection(response))

    def get_changeset_work_items(self, id=None):
        """GetChangesetWorkItems.
        Retrieves the work items associated with a particular changeset.
        :param int id: ID of the changeset. Default: null
        :rtype: [AssociatedWorkItem]
        """
        route_values = {}
        if id is not None:
            route_values['id'] = self._serialize.url('id', id, 'int')
        response = self._send(
            http_method='GET',
            location_id='64ae0bea-1d71-47c9-a9e5-fe73f5ea0ff4',
            version='4.1',
            route_values=route_values)
        return self._deserialize('[AssociatedWorkItem]',
                                 self._unwrap_collection(response))

    def get_items_batch(self, item_request_data, project=None):
        """GetItemsBatch.
        Post for retrieving a set of items given a list of paths or a long path. Allows for specifying the recursionLevel and version descriptors for each path.
        :param :class:`<TfvcItemRequestData> <tfvc.v4_1.models.TfvcItemRequestData>` item_request_data:
        :param str project: Project ID or project name
        :rtype: [[TfvcItem]]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        content = self._serialize.body(item_request_data,
                                       'TfvcItemRequestData')
        response = self._send(
            http_method='POST',
            location_id='fe6f827b-5f64-480f-b8af-1eca3b80e833',
            version='4.1',
            route_values=route_values,
            content=content)
        return self._deserialize('[[TfvcItem]]',
                                 self._unwrap_collection(response))

    def get_items_batch_zip(self, item_request_data, project=None, **kwargs):
        """GetItemsBatchZip.
        Post for retrieving a set of items given a list of paths or a long path. Allows for specifying the recursionLevel and version descriptors for each path.
        :param :class:`<TfvcItemRequestData> <tfvc.v4_1.models.TfvcItemRequestData>` item_request_data:
        :param str project: Project ID or project name
        :rtype: object
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        content = self._serialize.body(item_request_data,
                                       'TfvcItemRequestData')
        response = self._send(
            http_method='POST',
            location_id='fe6f827b-5f64-480f-b8af-1eca3b80e833',
            version='4.1',
            route_values=route_values,
            content=content,
            accept_media_type='application/zip')
        if "callback" in kwargs:
            callback = kwargs["callback"]
        else:
            callback = None
        return self._client.stream_download(response, callback=callback)

    def get_item(self,
                 path,
                 project=None,
                 file_name=None,
                 download=None,
                 scope_path=None,
                 recursion_level=None,
                 version_descriptor=None,
                 include_content=None):
        """GetItem.
        Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download.
        :param str path: Version control path of an individual item to return.
        :param str project: Project ID or project name
        :param str file_name: file name of item returned.
        :param bool download: If true, create a downloadable attachment.
        :param str scope_path: Version control path of a folder to return multiple items.
        :param str recursion_level: None (just the item), or OneLevel (contents of a folder).
        :param :class:`<TfvcVersionDescriptor> <tfvc.v4_1.models.TfvcVersionDescriptor>` version_descriptor: Version descriptor.  Default is null.
        :param bool include_content: Set to true to include item content when requesting json.  Default is false.
        :rtype: :class:`<TfvcItem> <tfvc.v4_1.models.TfvcItem>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        query_parameters = {}
        if path is not None:
            query_parameters['path'] = self._serialize.query(
                'path', path, 'str')
        if file_name is not None:
            query_parameters['fileName'] = self._serialize.query(
                'file_name', file_name, 'str')
        if download is not None:
            query_parameters['download'] = self._serialize.query(
                'download', download, 'bool')
        if scope_path is not None:
            query_parameters['scopePath'] = self._serialize.query(
                'scope_path', scope_path, 'str')
        if recursion_level is not None:
            query_parameters['recursionLevel'] = self._serialize.query(
                'recursion_level', recursion_level, 'str')
        if version_descriptor is not None:
            if version_descriptor.version_option is not None:
                query_parameters[
                    'versionDescriptor.versionOption'] = version_descriptor.version_option
            if version_descriptor.version_type is not None:
                query_parameters[
                    'versionDescriptor.versionType'] = version_descriptor.version_type
            if version_descriptor.version is not None:
                query_parameters[
                    'versionDescriptor.version'] = version_descriptor.version
        if include_content is not None:
            query_parameters['includeContent'] = self._serialize.query(
                'include_content', include_content, 'bool')
        response = self._send(
            http_method='GET',
            location_id='ba9fc436-9a38-4578-89d6-e4f3241f5040',
            version='4.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('TfvcItem', response)

    def get_item_content(self,
                         path,
                         project=None,
                         file_name=None,
                         download=None,
                         scope_path=None,
                         recursion_level=None,
                         version_descriptor=None,
                         include_content=None,
                         **kwargs):
        """GetItemContent.
        Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download.
        :param str path: Version control path of an individual item to return.
        :param str project: Project ID or project name
        :param str file_name: file name of item returned.
        :param bool download: If true, create a downloadable attachment.
        :param str scope_path: Version control path of a folder to return multiple items.
        :param str recursion_level: None (just the item), or OneLevel (contents of a folder).
        :param :class:`<TfvcVersionDescriptor> <tfvc.v4_1.models.TfvcVersionDescriptor>` version_descriptor: Version descriptor.  Default is null.
        :param bool include_content: Set to true to include item content when requesting json.  Default is false.
        :rtype: object
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        query_parameters = {}
        if path is not None:
            query_parameters['path'] = self._serialize.query(
                'path', path, 'str')
        if file_name is not None:
            query_parameters['fileName'] = self._serialize.query(
                'file_name', file_name, 'str')
        if download is not None:
            query_parameters['download'] = self._serialize.query(
                'download', download, 'bool')
        if scope_path is not None:
            query_parameters['scopePath'] = self._serialize.query(
                'scope_path', scope_path, 'str')
        if recursion_level is not None:
            query_parameters['recursionLevel'] = self._serialize.query(
                'recursion_level', recursion_level, 'str')
        if version_descriptor is not None:
            if version_descriptor.version_option is not None:
                query_parameters[
                    'versionDescriptor.versionOption'] = version_descriptor.version_option
            if version_descriptor.version_type is not None:
                query_parameters[
                    'versionDescriptor.versionType'] = version_descriptor.version_type
            if version_descriptor.version is not None:
                query_parameters[
                    'versionDescriptor.version'] = version_descriptor.version
        if include_content is not None:
            query_parameters['includeContent'] = self._serialize.query(
                'include_content', include_content, 'bool')
        response = self._send(
            http_method='GET',
            location_id='ba9fc436-9a38-4578-89d6-e4f3241f5040',
            version='4.1',
            route_values=route_values,
            query_parameters=query_parameters,
            accept_media_type='application/octet-stream')
        if "callback" in kwargs:
            callback = kwargs["callback"]
        else:
            callback = None
        return self._client.stream_download(response, callback=callback)

    def get_items(self,
                  project=None,
                  scope_path=None,
                  recursion_level=None,
                  include_links=None,
                  version_descriptor=None):
        """GetItems.
        Get a list of Tfvc items
        :param str project: Project ID or project name
        :param str scope_path: Version control path of a folder to return multiple items.
        :param str recursion_level: None (just the item), or OneLevel (contents of a folder).
        :param bool include_links: True to include links.
        :param :class:`<TfvcVersionDescriptor> <tfvc.v4_1.models.TfvcVersionDescriptor>` version_descriptor:
        :rtype: [TfvcItem]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        query_parameters = {}
        if scope_path is not None:
            query_parameters['scopePath'] = self._serialize.query(
                'scope_path', scope_path, 'str')
        if recursion_level is not None:
            query_parameters['recursionLevel'] = self._serialize.query(
                'recursion_level', recursion_level, 'str')
        if include_links is not None:
            query_parameters['includeLinks'] = self._serialize.query(
                'include_links', include_links, 'bool')
        if version_descriptor is not None:
            if version_descriptor.version_option is not None:
                query_parameters[
                    'versionDescriptor.versionOption'] = version_descriptor.version_option
            if version_descriptor.version_type is not None:
                query_parameters[
                    'versionDescriptor.versionType'] = version_descriptor.version_type
            if version_descriptor.version is not None:
                query_parameters[
                    'versionDescriptor.version'] = version_descriptor.version
        response = self._send(
            http_method='GET',
            location_id='ba9fc436-9a38-4578-89d6-e4f3241f5040',
            version='4.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[TfvcItem]',
                                 self._unwrap_collection(response))

    def get_item_text(self,
                      path,
                      project=None,
                      file_name=None,
                      download=None,
                      scope_path=None,
                      recursion_level=None,
                      version_descriptor=None,
                      include_content=None,
                      **kwargs):
        """GetItemText.
        Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download.
        :param str path: Version control path of an individual item to return.
        :param str project: Project ID or project name
        :param str file_name: file name of item returned.
        :param bool download: If true, create a downloadable attachment.
        :param str scope_path: Version control path of a folder to return multiple items.
        :param str recursion_level: None (just the item), or OneLevel (contents of a folder).
        :param :class:`<TfvcVersionDescriptor> <tfvc.v4_1.models.TfvcVersionDescriptor>` version_descriptor: Version descriptor.  Default is null.
        :param bool include_content: Set to true to include item content when requesting json.  Default is false.
        :rtype: object
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        query_parameters = {}
        if path is not None:
            query_parameters['path'] = self._serialize.query(
                'path', path, 'str')
        if file_name is not None:
            query_parameters['fileName'] = self._serialize.query(
                'file_name', file_name, 'str')
        if download is not None:
            query_parameters['download'] = self._serialize.query(
                'download', download, 'bool')
        if scope_path is not None:
            query_parameters['scopePath'] = self._serialize.query(
                'scope_path', scope_path, 'str')
        if recursion_level is not None:
            query_parameters['recursionLevel'] = self._serialize.query(
                'recursion_level', recursion_level, 'str')
        if version_descriptor is not None:
            if version_descriptor.version_option is not None:
                query_parameters[
                    'versionDescriptor.versionOption'] = version_descriptor.version_option
            if version_descriptor.version_type is not None:
                query_parameters[
                    'versionDescriptor.versionType'] = version_descriptor.version_type
            if version_descriptor.version is not None:
                query_parameters[
                    'versionDescriptor.version'] = version_descriptor.version
        if include_content is not None:
            query_parameters['includeContent'] = self._serialize.query(
                'include_content', include_content, 'bool')
        response = self._send(
            http_method='GET',
            location_id='ba9fc436-9a38-4578-89d6-e4f3241f5040',
            version='4.1',
            route_values=route_values,
            query_parameters=query_parameters,
            accept_media_type='text/plain')
        if "callback" in kwargs:
            callback = kwargs["callback"]
        else:
            callback = None
        return self._client.stream_download(response, callback=callback)

    def get_item_zip(self,
                     path,
                     project=None,
                     file_name=None,
                     download=None,
                     scope_path=None,
                     recursion_level=None,
                     version_descriptor=None,
                     include_content=None,
                     **kwargs):
        """GetItemZip.
        Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download.
        :param str path: Version control path of an individual item to return.
        :param str project: Project ID or project name
        :param str file_name: file name of item returned.
        :param bool download: If true, create a downloadable attachment.
        :param str scope_path: Version control path of a folder to return multiple items.
        :param str recursion_level: None (just the item), or OneLevel (contents of a folder).
        :param :class:`<TfvcVersionDescriptor> <tfvc.v4_1.models.TfvcVersionDescriptor>` version_descriptor: Version descriptor.  Default is null.
        :param bool include_content: Set to true to include item content when requesting json.  Default is false.
        :rtype: object
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        query_parameters = {}
        if path is not None:
            query_parameters['path'] = self._serialize.query(
                'path', path, 'str')
        if file_name is not None:
            query_parameters['fileName'] = self._serialize.query(
                'file_name', file_name, 'str')
        if download is not None:
            query_parameters['download'] = self._serialize.query(
                'download', download, 'bool')
        if scope_path is not None:
            query_parameters['scopePath'] = self._serialize.query(
                'scope_path', scope_path, 'str')
        if recursion_level is not None:
            query_parameters['recursionLevel'] = self._serialize.query(
                'recursion_level', recursion_level, 'str')
        if version_descriptor is not None:
            if version_descriptor.version_option is not None:
                query_parameters[
                    'versionDescriptor.versionOption'] = version_descriptor.version_option
            if version_descriptor.version_type is not None:
                query_parameters[
                    'versionDescriptor.versionType'] = version_descriptor.version_type
            if version_descriptor.version is not None:
                query_parameters[
                    'versionDescriptor.version'] = version_descriptor.version
        if include_content is not None:
            query_parameters['includeContent'] = self._serialize.query(
                'include_content', include_content, 'bool')
        response = self._send(
            http_method='GET',
            location_id='ba9fc436-9a38-4578-89d6-e4f3241f5040',
            version='4.1',
            route_values=route_values,
            query_parameters=query_parameters,
            accept_media_type='application/zip')
        if "callback" in kwargs:
            callback = kwargs["callback"]
        else:
            callback = None
        return self._client.stream_download(response, callback=callback)

    def get_label_items(self, label_id, top=None, skip=None):
        """GetLabelItems.
        Get items under a label.
        :param str label_id: Unique identifier of label
        :param int top: Max number of items to return
        :param int skip: Number of items to skip
        :rtype: [TfvcItem]
        """
        route_values = {}
        if label_id is not None:
            route_values['labelId'] = self._serialize.url(
                'label_id', label_id, 'str')
        query_parameters = {}
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        if skip is not None:
            query_parameters['$skip'] = self._serialize.query(
                'skip', skip, 'int')
        response = self._send(
            http_method='GET',
            location_id='06166e34-de17-4b60-8cd1-23182a346fda',
            version='4.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[TfvcItem]',
                                 self._unwrap_collection(response))

    def get_label(self, label_id, request_data, project=None):
        """GetLabel.
        Get a single deep label.
        :param str label_id: Unique identifier of label
        :param :class:`<TfvcLabelRequestData> <tfvc.v4_1.models.TfvcLabelRequestData>` request_data: maxItemCount
        :param str project: Project ID or project name
        :rtype: :class:`<TfvcLabel> <tfvc.v4_1.models.TfvcLabel>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if label_id is not None:
            route_values['labelId'] = self._serialize.url(
                'label_id', label_id, 'str')
        query_parameters = {}
        if request_data is not None:
            if request_data.label_scope is not None:
                query_parameters[
                    'requestData.labelScope'] = request_data.label_scope
            if request_data.name is not None:
                query_parameters['requestData.name'] = request_data.name
            if request_data.owner is not None:
                query_parameters['requestData.owner'] = request_data.owner
            if request_data.item_label_filter is not None:
                query_parameters[
                    'requestData.itemLabelFilter'] = request_data.item_label_filter
            if request_data.max_item_count is not None:
                query_parameters[
                    'requestData.maxItemCount'] = request_data.max_item_count
            if request_data.include_links is not None:
                query_parameters[
                    'requestData.includeLinks'] = request_data.include_links
        response = self._send(
            http_method='GET',
            location_id='a5d9bd7f-b661-4d0e-b9be-d9c16affae54',
            version='4.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('TfvcLabel', response)

    def get_labels(self, request_data, project=None, top=None, skip=None):
        """GetLabels.
        Get a collection of shallow label references.
        :param :class:`<TfvcLabelRequestData> <tfvc.v4_1.models.TfvcLabelRequestData>` request_data: labelScope, name, owner, and itemLabelFilter
        :param str project: Project ID or project name
        :param int top: Max number of labels to return
        :param int skip: Number of labels to skip
        :rtype: [TfvcLabelRef]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        query_parameters = {}
        if request_data is not None:
            if request_data.label_scope is not None:
                query_parameters[
                    'requestData.labelScope'] = request_data.label_scope
            if request_data.name is not None:
                query_parameters['requestData.name'] = request_data.name
            if request_data.owner is not None:
                query_parameters['requestData.owner'] = request_data.owner
            if request_data.item_label_filter is not None:
                query_parameters[
                    'requestData.itemLabelFilter'] = request_data.item_label_filter
            if request_data.max_item_count is not None:
                query_parameters[
                    'requestData.maxItemCount'] = request_data.max_item_count
            if request_data.include_links is not None:
                query_parameters[
                    'requestData.includeLinks'] = request_data.include_links
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        if skip is not None:
            query_parameters['$skip'] = self._serialize.query(
                'skip', skip, 'int')
        response = self._send(
            http_method='GET',
            location_id='a5d9bd7f-b661-4d0e-b9be-d9c16affae54',
            version='4.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[TfvcLabelRef]',
                                 self._unwrap_collection(response))

    def get_shelveset_changes(self, shelveset_id, top=None, skip=None):
        """GetShelvesetChanges.
        Get changes included in a shelveset.
        :param str shelveset_id: Shelveset's unique ID
        :param int top: Max number of changes to return
        :param int skip: Number of changes to skip
        :rtype: [TfvcChange]
        """
        query_parameters = {}
        if shelveset_id is not None:
            query_parameters['shelvesetId'] = self._serialize.query(
                'shelveset_id', shelveset_id, 'str')
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        if skip is not None:
            query_parameters['$skip'] = self._serialize.query(
                'skip', skip, 'int')
        response = self._send(
            http_method='GET',
            location_id='dbaf075b-0445-4c34-9e5b-82292f856522',
            version='4.1',
            query_parameters=query_parameters)
        return self._deserialize('[TfvcChange]',
                                 self._unwrap_collection(response))

    def get_shelveset(self, shelveset_id, request_data=None):
        """GetShelveset.
        Get a single deep shelveset.
        :param str shelveset_id: Shelveset's unique ID
        :param :class:`<TfvcShelvesetRequestData> <tfvc.v4_1.models.TfvcShelvesetRequestData>` request_data: includeDetails, includeWorkItems, maxChangeCount, and maxCommentLength
        :rtype: :class:`<TfvcShelveset> <tfvc.v4_1.models.TfvcShelveset>`
        """
        query_parameters = {}
        if shelveset_id is not None:
            query_parameters['shelvesetId'] = self._serialize.query(
                'shelveset_id', shelveset_id, 'str')
        if request_data is not None:
            if request_data.name is not None:
                query_parameters['requestData.name'] = request_data.name
            if request_data.owner is not None:
                query_parameters['requestData.owner'] = request_data.owner
            if request_data.max_comment_length is not None:
                query_parameters[
                    'requestData.maxCommentLength'] = request_data.max_comment_length
            if request_data.max_change_count is not None:
                query_parameters[
                    'requestData.maxChangeCount'] = request_data.max_change_count
            if request_data.include_details is not None:
                query_parameters[
                    'requestData.includeDetails'] = request_data.include_details
            if request_data.include_work_items is not None:
                query_parameters[
                    'requestData.includeWorkItems'] = request_data.include_work_items
            if request_data.include_links is not None:
                query_parameters[
                    'requestData.includeLinks'] = request_data.include_links
        response = self._send(
            http_method='GET',
            location_id='e36d44fb-e907-4b0a-b194-f83f1ed32ad3',
            version='4.1',
            query_parameters=query_parameters)
        return self._deserialize('TfvcShelveset', response)

    def get_shelvesets(self, request_data=None, top=None, skip=None):
        """GetShelvesets.
        Return a collection of shallow shelveset references.
        :param :class:`<TfvcShelvesetRequestData> <tfvc.v4_1.models.TfvcShelvesetRequestData>` request_data: name, owner, and maxCommentLength
        :param int top: Max number of shelvesets to return
        :param int skip: Number of shelvesets to skip
        :rtype: [TfvcShelvesetRef]
        """
        query_parameters = {}
        if request_data is not None:
            if request_data.name is not None:
                query_parameters['requestData.name'] = request_data.name
            if request_data.owner is not None:
                query_parameters['requestData.owner'] = request_data.owner
            if request_data.max_comment_length is not None:
                query_parameters[
                    'requestData.maxCommentLength'] = request_data.max_comment_length
            if request_data.max_change_count is not None:
                query_parameters[
                    'requestData.maxChangeCount'] = request_data.max_change_count
            if request_data.include_details is not None:
                query_parameters[
                    'requestData.includeDetails'] = request_data.include_details
            if request_data.include_work_items is not None:
                query_parameters[
                    'requestData.includeWorkItems'] = request_data.include_work_items
            if request_data.include_links is not None:
                query_parameters[
                    'requestData.includeLinks'] = request_data.include_links
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        if skip is not None:
            query_parameters['$skip'] = self._serialize.query(
                'skip', skip, 'int')
        response = self._send(
            http_method='GET',
            location_id='e36d44fb-e907-4b0a-b194-f83f1ed32ad3',
            version='4.1',
            query_parameters=query_parameters)
        return self._deserialize('[TfvcShelvesetRef]',
                                 self._unwrap_collection(response))

    def get_shelveset_work_items(self, shelveset_id):
        """GetShelvesetWorkItems.
        Get work items associated with a shelveset.
        :param str shelveset_id: Shelveset's unique ID
        :rtype: [AssociatedWorkItem]
        """
        query_parameters = {}
        if shelveset_id is not None:
            query_parameters['shelvesetId'] = self._serialize.query(
                'shelveset_id', shelveset_id, 'str')
        response = self._send(
            http_method='GET',
            location_id='a7a0c1c1-373e-425a-b031-a519474d743d',
            version='4.1',
            query_parameters=query_parameters)
        return self._deserialize('[AssociatedWorkItem]',
                                 self._unwrap_collection(response))
class AutoRestValidationTest(object):
    """Test Infrastructure for AutoRest. No server backend exists for these tests.

    :param config: Configuration for client.
    :type config: AutoRestValidationTestConfiguration
    """

    def __init__(self, config):

        self._client = ServiceClient(None, config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self._serialize = Serializer()
        self._deserialize = Deserializer(client_models)

        self.config = config

    def validation_of_method_parameters(
            self, resource_group_name, id, custom_headers={}, raw=False, **operation_config):
        """
        Validates input parameters on the method. See swagger for details.

        :param resource_group_name: Required string between 3 and 10 chars
         with pattern [a-zA-Z0-9]+.
        :type resource_group_name: str
        :param id: Required int multiple of 10 from 100 to 1000.
        :type id: int
        :param dict custom_headers: headers that will be added to the request
        :param boolean raw: returns the direct response alongside the
         deserialized response
        :rtype: Product or msrest.pipeline.ClientRawResponse
        """
        # Construct URL
        url = '/fakepath/{subscriptionId}/{resourceGroupName}/{id}'
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'id': self._serialize.url("id", id, 'int')
        }
        url = url.format(**path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['apiVersion'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Product', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def validation_of_body(
            self, resource_group_name, id, body=None, custom_headers={}, raw=False, **operation_config):
        """
        Validates body parameters on the method. See swagger for details.

        :param resource_group_name: Required string between 3 and 10 chars
         with pattern [a-zA-Z0-9]+.
        :type resource_group_name: str
        :param id: Required int multiple of 10 from 100 to 1000.
        :type id: int
        :param body:
        :type body: Product or None
        :param dict custom_headers: headers that will be added to the request
        :param boolean raw: returns the direct response alongside the
         deserialized response
        :rtype: Product or msrest.pipeline.ClientRawResponse
        """
        # Construct URL
        url = '/fakepath/{subscriptionId}/{resourceGroupName}/{id}'
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'id': self._serialize.url("id", id, 'int')
        }
        url = url.format(**path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['apiVersion'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'Product')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Product', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def get_with_constant_in_path(
            self, constant_param, custom_headers={}, raw=False, **operation_config):
        """

        :param constant_param:
        :type constant_param: str
        :param dict custom_headers: headers that will be added to the request
        :param boolean raw: returns the direct response alongside the
         deserialized response
        :rtype: None or msrest.pipeline.ClientRawResponse
        """
        # Construct URL
        url = '/validation/constantsInPath/{constantParam}/value'
        path_format_arguments = {
            'constantParam': self._serialize.url("constant_param", constant_param, 'str')
        }
        url = url.format(**path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def post_with_constant_in_body(
            self, constant_param, body=None, custom_headers={}, raw=False, **operation_config):
        """

        :param constant_param:
        :type constant_param: str
        :param body:
        :type body: Product or None
        :param dict custom_headers: headers that will be added to the request
        :param boolean raw: returns the direct response alongside the
         deserialized response
        :rtype: Product or msrest.pipeline.ClientRawResponse
        """
        # Construct URL
        url = '/validation/constantsInPath/{constantParam}/value'
        path_format_arguments = {
            'constantParam': self._serialize.url("constant_param", constant_param, 'str')
        }
        url = url.format(**path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'Product')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Product', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
Ejemplo n.º 30
0
class WorkItemTrackingClient(VssClient):
    """WorkItemTracking
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """

    def __init__(self, base_url=None, creds=None):
        super(WorkItemTrackingClient, self).__init__(base_url, creds)
        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = '5264459e-e5e0-4bd8-b118-0985e68a4ec5'

    def create_behavior(self, behavior, process_id):
        """CreateBehavior.
        [Preview API]
        :param :class:`<BehaviorCreateModel> <work-item-tracking.v4_0.models.BehaviorCreateModel>` behavior:
        :param str process_id:
        :rtype: :class:`<BehaviorModel> <work-item-tracking.v4_0.models.BehaviorModel>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        content = self._serialize.body(behavior, 'BehaviorCreateModel')
        response = self._send(http_method='POST',
                              location_id='47a651f4-fb70-43bf-b96b-7c0ba947142b',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('BehaviorModel', response)

    def delete_behavior(self, process_id, behavior_id):
        """DeleteBehavior.
        [Preview API]
        :param str process_id:
        :param str behavior_id:
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if behavior_id is not None:
            route_values['behaviorId'] = self._serialize.url('behavior_id', behavior_id, 'str')
        self._send(http_method='DELETE',
                   location_id='47a651f4-fb70-43bf-b96b-7c0ba947142b',
                   version='4.0-preview.1',
                   route_values=route_values)

    def get_behavior(self, process_id, behavior_id):
        """GetBehavior.
        [Preview API]
        :param str process_id:
        :param str behavior_id:
        :rtype: :class:`<BehaviorModel> <work-item-tracking.v4_0.models.BehaviorModel>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if behavior_id is not None:
            route_values['behaviorId'] = self._serialize.url('behavior_id', behavior_id, 'str')
        response = self._send(http_method='GET',
                              location_id='47a651f4-fb70-43bf-b96b-7c0ba947142b',
                              version='4.0-preview.1',
                              route_values=route_values)
        return self._deserialize('BehaviorModel', response)

    def get_behaviors(self, process_id):
        """GetBehaviors.
        [Preview API]
        :param str process_id:
        :rtype: [BehaviorModel]
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        response = self._send(http_method='GET',
                              location_id='47a651f4-fb70-43bf-b96b-7c0ba947142b',
                              version='4.0-preview.1',
                              route_values=route_values)
        return self._deserialize('[BehaviorModel]', self._unwrap_collection(response))

    def replace_behavior(self, behavior_data, process_id, behavior_id):
        """ReplaceBehavior.
        [Preview API]
        :param :class:`<BehaviorReplaceModel> <work-item-tracking.v4_0.models.BehaviorReplaceModel>` behavior_data:
        :param str process_id:
        :param str behavior_id:
        :rtype: :class:`<BehaviorModel> <work-item-tracking.v4_0.models.BehaviorModel>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if behavior_id is not None:
            route_values['behaviorId'] = self._serialize.url('behavior_id', behavior_id, 'str')
        content = self._serialize.body(behavior_data, 'BehaviorReplaceModel')
        response = self._send(http_method='PUT',
                              location_id='47a651f4-fb70-43bf-b96b-7c0ba947142b',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('BehaviorModel', response)

    def add_control_to_group(self, control, process_id, wit_ref_name, group_id):
        """AddControlToGroup.
        [Preview API] Creates a control, giving it an id, and adds it to the group. So far, the only controls that don't know how to generate their own ids are control extensions.
        :param :class:`<Control> <work-item-tracking.v4_0.models.Control>` control:
        :param str process_id:
        :param str wit_ref_name:
        :param str group_id:
        :rtype: :class:`<Control> <work-item-tracking.v4_0.models.Control>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        if group_id is not None:
            route_values['groupId'] = self._serialize.url('group_id', group_id, 'str')
        content = self._serialize.body(control, 'Control')
        response = self._send(http_method='POST',
                              location_id='e2e3166a-627a-4e9b-85b2-d6a097bbd731',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('Control', response)

    def edit_control(self, control, process_id, wit_ref_name, group_id, control_id):
        """EditControl.
        [Preview API]
        :param :class:`<Control> <work-item-tracking.v4_0.models.Control>` control:
        :param str process_id:
        :param str wit_ref_name:
        :param str group_id:
        :param str control_id:
        :rtype: :class:`<Control> <work-item-tracking.v4_0.models.Control>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        if group_id is not None:
            route_values['groupId'] = self._serialize.url('group_id', group_id, 'str')
        if control_id is not None:
            route_values['controlId'] = self._serialize.url('control_id', control_id, 'str')
        content = self._serialize.body(control, 'Control')
        response = self._send(http_method='PATCH',
                              location_id='e2e3166a-627a-4e9b-85b2-d6a097bbd731',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('Control', response)

    def remove_control_from_group(self, process_id, wit_ref_name, group_id, control_id):
        """RemoveControlFromGroup.
        [Preview API]
        :param str process_id:
        :param str wit_ref_name:
        :param str group_id:
        :param str control_id:
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        if group_id is not None:
            route_values['groupId'] = self._serialize.url('group_id', group_id, 'str')
        if control_id is not None:
            route_values['controlId'] = self._serialize.url('control_id', control_id, 'str')
        self._send(http_method='DELETE',
                   location_id='e2e3166a-627a-4e9b-85b2-d6a097bbd731',
                   version='4.0-preview.1',
                   route_values=route_values)

    def set_control_in_group(self, control, process_id, wit_ref_name, group_id, control_id, remove_from_group_id=None):
        """SetControlInGroup.
        [Preview API] Puts a control withan id into a group. Controls backed by fields can generate their own id.
        :param :class:`<Control> <work-item-tracking.v4_0.models.Control>` control:
        :param str process_id:
        :param str wit_ref_name:
        :param str group_id:
        :param str control_id:
        :param str remove_from_group_id:
        :rtype: :class:`<Control> <work-item-tracking.v4_0.models.Control>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        if group_id is not None:
            route_values['groupId'] = self._serialize.url('group_id', group_id, 'str')
        if control_id is not None:
            route_values['controlId'] = self._serialize.url('control_id', control_id, 'str')
        query_parameters = {}
        if remove_from_group_id is not None:
            query_parameters['removeFromGroupId'] = self._serialize.query('remove_from_group_id', remove_from_group_id, 'str')
        content = self._serialize.body(control, 'Control')
        response = self._send(http_method='PUT',
                              location_id='e2e3166a-627a-4e9b-85b2-d6a097bbd731',
                              version='4.0-preview.1',
                              route_values=route_values,
                              query_parameters=query_parameters,
                              content=content)
        return self._deserialize('Control', response)

    def create_field(self, field, process_id):
        """CreateField.
        [Preview API]
        :param :class:`<FieldModel> <work-item-tracking.v4_0.models.FieldModel>` field:
        :param str process_id:
        :rtype: :class:`<FieldModel> <work-item-tracking.v4_0.models.FieldModel>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        content = self._serialize.body(field, 'FieldModel')
        response = self._send(http_method='POST',
                              location_id='f36c66c7-911d-4163-8938-d3c5d0d7f5aa',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('FieldModel', response)

    def update_field(self, field, process_id):
        """UpdateField.
        [Preview API]
        :param :class:`<FieldUpdate> <work-item-tracking.v4_0.models.FieldUpdate>` field:
        :param str process_id:
        :rtype: :class:`<FieldModel> <work-item-tracking.v4_0.models.FieldModel>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        content = self._serialize.body(field, 'FieldUpdate')
        response = self._send(http_method='PATCH',
                              location_id='f36c66c7-911d-4163-8938-d3c5d0d7f5aa',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('FieldModel', response)

    def add_group(self, group, process_id, wit_ref_name, page_id, section_id):
        """AddGroup.
        [Preview API]
        :param :class:`<Group> <work-item-tracking.v4_0.models.Group>` group:
        :param str process_id:
        :param str wit_ref_name:
        :param str page_id:
        :param str section_id:
        :rtype: :class:`<Group> <work-item-tracking.v4_0.models.Group>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        if page_id is not None:
            route_values['pageId'] = self._serialize.url('page_id', page_id, 'str')
        if section_id is not None:
            route_values['sectionId'] = self._serialize.url('section_id', section_id, 'str')
        content = self._serialize.body(group, 'Group')
        response = self._send(http_method='POST',
                              location_id='2617828b-e850-4375-a92a-04855704d4c3',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('Group', response)

    def edit_group(self, group, process_id, wit_ref_name, page_id, section_id, group_id):
        """EditGroup.
        [Preview API]
        :param :class:`<Group> <work-item-tracking.v4_0.models.Group>` group:
        :param str process_id:
        :param str wit_ref_name:
        :param str page_id:
        :param str section_id:
        :param str group_id:
        :rtype: :class:`<Group> <work-item-tracking.v4_0.models.Group>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        if page_id is not None:
            route_values['pageId'] = self._serialize.url('page_id', page_id, 'str')
        if section_id is not None:
            route_values['sectionId'] = self._serialize.url('section_id', section_id, 'str')
        if group_id is not None:
            route_values['groupId'] = self._serialize.url('group_id', group_id, 'str')
        content = self._serialize.body(group, 'Group')
        response = self._send(http_method='PATCH',
                              location_id='2617828b-e850-4375-a92a-04855704d4c3',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('Group', response)

    def remove_group(self, process_id, wit_ref_name, page_id, section_id, group_id):
        """RemoveGroup.
        [Preview API]
        :param str process_id:
        :param str wit_ref_name:
        :param str page_id:
        :param str section_id:
        :param str group_id:
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        if page_id is not None:
            route_values['pageId'] = self._serialize.url('page_id', page_id, 'str')
        if section_id is not None:
            route_values['sectionId'] = self._serialize.url('section_id', section_id, 'str')
        if group_id is not None:
            route_values['groupId'] = self._serialize.url('group_id', group_id, 'str')
        self._send(http_method='DELETE',
                   location_id='2617828b-e850-4375-a92a-04855704d4c3',
                   version='4.0-preview.1',
                   route_values=route_values)

    def set_group_in_page(self, group, process_id, wit_ref_name, page_id, section_id, group_id, remove_from_page_id, remove_from_section_id):
        """SetGroupInPage.
        [Preview API]
        :param :class:`<Group> <work-item-tracking.v4_0.models.Group>` group:
        :param str process_id:
        :param str wit_ref_name:
        :param str page_id:
        :param str section_id:
        :param str group_id:
        :param str remove_from_page_id:
        :param str remove_from_section_id:
        :rtype: :class:`<Group> <work-item-tracking.v4_0.models.Group>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        if page_id is not None:
            route_values['pageId'] = self._serialize.url('page_id', page_id, 'str')
        if section_id is not None:
            route_values['sectionId'] = self._serialize.url('section_id', section_id, 'str')
        if group_id is not None:
            route_values['groupId'] = self._serialize.url('group_id', group_id, 'str')
        query_parameters = {}
        if remove_from_page_id is not None:
            query_parameters['removeFromPageId'] = self._serialize.query('remove_from_page_id', remove_from_page_id, 'str')
        if remove_from_section_id is not None:
            query_parameters['removeFromSectionId'] = self._serialize.query('remove_from_section_id', remove_from_section_id, 'str')
        content = self._serialize.body(group, 'Group')
        response = self._send(http_method='PUT',
                              location_id='2617828b-e850-4375-a92a-04855704d4c3',
                              version='4.0-preview.1',
                              route_values=route_values,
                              query_parameters=query_parameters,
                              content=content)
        return self._deserialize('Group', response)

    def set_group_in_section(self, group, process_id, wit_ref_name, page_id, section_id, group_id, remove_from_section_id):
        """SetGroupInSection.
        [Preview API]
        :param :class:`<Group> <work-item-tracking.v4_0.models.Group>` group:
        :param str process_id:
        :param str wit_ref_name:
        :param str page_id:
        :param str section_id:
        :param str group_id:
        :param str remove_from_section_id:
        :rtype: :class:`<Group> <work-item-tracking.v4_0.models.Group>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        if page_id is not None:
            route_values['pageId'] = self._serialize.url('page_id', page_id, 'str')
        if section_id is not None:
            route_values['sectionId'] = self._serialize.url('section_id', section_id, 'str')
        if group_id is not None:
            route_values['groupId'] = self._serialize.url('group_id', group_id, 'str')
        query_parameters = {}
        if remove_from_section_id is not None:
            query_parameters['removeFromSectionId'] = self._serialize.query('remove_from_section_id', remove_from_section_id, 'str')
        content = self._serialize.body(group, 'Group')
        response = self._send(http_method='PUT',
                              location_id='2617828b-e850-4375-a92a-04855704d4c3',
                              version='4.0-preview.1',
                              route_values=route_values,
                              query_parameters=query_parameters,
                              content=content)
        return self._deserialize('Group', response)

    def get_form_layout(self, process_id, wit_ref_name):
        """GetFormLayout.
        [Preview API]
        :param str process_id:
        :param str wit_ref_name:
        :rtype: :class:`<FormLayout> <work-item-tracking.v4_0.models.FormLayout>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        response = self._send(http_method='GET',
                              location_id='3eacc80a-ddca-4404-857a-6331aac99063',
                              version='4.0-preview.1',
                              route_values=route_values)
        return self._deserialize('FormLayout', response)

    def get_lists_metadata(self):
        """GetListsMetadata.
        [Preview API]
        :rtype: [PickListMetadataModel]
        """
        response = self._send(http_method='GET',
                              location_id='b45cc931-98e3-44a1-b1cd-2e8e9c6dc1c6',
                              version='4.0-preview.1')
        return self._deserialize('[PickListMetadataModel]', self._unwrap_collection(response))

    def create_list(self, picklist):
        """CreateList.
        [Preview API]
        :param :class:`<PickListModel> <work-item-tracking.v4_0.models.PickListModel>` picklist:
        :rtype: :class:`<PickListModel> <work-item-tracking.v4_0.models.PickListModel>`
        """
        content = self._serialize.body(picklist, 'PickListModel')
        response = self._send(http_method='POST',
                              location_id='0b6179e2-23ce-46b2-b094-2ffa5ee70286',
                              version='4.0-preview.1',
                              content=content)
        return self._deserialize('PickListModel', response)

    def delete_list(self, list_id):
        """DeleteList.
        [Preview API]
        :param str list_id:
        """
        route_values = {}
        if list_id is not None:
            route_values['listId'] = self._serialize.url('list_id', list_id, 'str')
        self._send(http_method='DELETE',
                   location_id='0b6179e2-23ce-46b2-b094-2ffa5ee70286',
                   version='4.0-preview.1',
                   route_values=route_values)

    def get_list(self, list_id):
        """GetList.
        [Preview API]
        :param str list_id:
        :rtype: :class:`<PickListModel> <work-item-tracking.v4_0.models.PickListModel>`
        """
        route_values = {}
        if list_id is not None:
            route_values['listId'] = self._serialize.url('list_id', list_id, 'str')
        response = self._send(http_method='GET',
                              location_id='0b6179e2-23ce-46b2-b094-2ffa5ee70286',
                              version='4.0-preview.1',
                              route_values=route_values)
        return self._deserialize('PickListModel', response)

    def update_list(self, picklist, list_id):
        """UpdateList.
        [Preview API]
        :param :class:`<PickListModel> <work-item-tracking.v4_0.models.PickListModel>` picklist:
        :param str list_id:
        :rtype: :class:`<PickListModel> <work-item-tracking.v4_0.models.PickListModel>`
        """
        route_values = {}
        if list_id is not None:
            route_values['listId'] = self._serialize.url('list_id', list_id, 'str')
        content = self._serialize.body(picklist, 'PickListModel')
        response = self._send(http_method='PUT',
                              location_id='0b6179e2-23ce-46b2-b094-2ffa5ee70286',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('PickListModel', response)

    def add_page(self, page, process_id, wit_ref_name):
        """AddPage.
        [Preview API]
        :param :class:`<Page> <work-item-tracking.v4_0.models.Page>` page:
        :param str process_id:
        :param str wit_ref_name:
        :rtype: :class:`<Page> <work-item-tracking.v4_0.models.Page>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        content = self._serialize.body(page, 'Page')
        response = self._send(http_method='POST',
                              location_id='1b4ac126-59b2-4f37-b4df-0a48ba807edb',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('Page', response)

    def edit_page(self, page, process_id, wit_ref_name):
        """EditPage.
        [Preview API]
        :param :class:`<Page> <work-item-tracking.v4_0.models.Page>` page:
        :param str process_id:
        :param str wit_ref_name:
        :rtype: :class:`<Page> <work-item-tracking.v4_0.models.Page>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        content = self._serialize.body(page, 'Page')
        response = self._send(http_method='PATCH',
                              location_id='1b4ac126-59b2-4f37-b4df-0a48ba807edb',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('Page', response)

    def remove_page(self, process_id, wit_ref_name, page_id):
        """RemovePage.
        [Preview API]
        :param str process_id:
        :param str wit_ref_name:
        :param str page_id:
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        if page_id is not None:
            route_values['pageId'] = self._serialize.url('page_id', page_id, 'str')
        self._send(http_method='DELETE',
                   location_id='1b4ac126-59b2-4f37-b4df-0a48ba807edb',
                   version='4.0-preview.1',
                   route_values=route_values)

    def create_state_definition(self, state_model, process_id, wit_ref_name):
        """CreateStateDefinition.
        [Preview API]
        :param :class:`<WorkItemStateInputModel> <work-item-tracking.v4_0.models.WorkItemStateInputModel>` state_model:
        :param str process_id:
        :param str wit_ref_name:
        :rtype: :class:`<WorkItemStateResultModel> <work-item-tracking.v4_0.models.WorkItemStateResultModel>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        content = self._serialize.body(state_model, 'WorkItemStateInputModel')
        response = self._send(http_method='POST',
                              location_id='4303625d-08f4-4461-b14b-32c65bba5599',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('WorkItemStateResultModel', response)

    def delete_state_definition(self, process_id, wit_ref_name, state_id):
        """DeleteStateDefinition.
        [Preview API]
        :param str process_id:
        :param str wit_ref_name:
        :param str state_id:
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        if state_id is not None:
            route_values['stateId'] = self._serialize.url('state_id', state_id, 'str')
        self._send(http_method='DELETE',
                   location_id='4303625d-08f4-4461-b14b-32c65bba5599',
                   version='4.0-preview.1',
                   route_values=route_values)

    def get_state_definition(self, process_id, wit_ref_name, state_id):
        """GetStateDefinition.
        [Preview API]
        :param str process_id:
        :param str wit_ref_name:
        :param str state_id:
        :rtype: :class:`<WorkItemStateResultModel> <work-item-tracking.v4_0.models.WorkItemStateResultModel>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        if state_id is not None:
            route_values['stateId'] = self._serialize.url('state_id', state_id, 'str')
        response = self._send(http_method='GET',
                              location_id='4303625d-08f4-4461-b14b-32c65bba5599',
                              version='4.0-preview.1',
                              route_values=route_values)
        return self._deserialize('WorkItemStateResultModel', response)

    def get_state_definitions(self, process_id, wit_ref_name):
        """GetStateDefinitions.
        [Preview API]
        :param str process_id:
        :param str wit_ref_name:
        :rtype: [WorkItemStateResultModel]
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        response = self._send(http_method='GET',
                              location_id='4303625d-08f4-4461-b14b-32c65bba5599',
                              version='4.0-preview.1',
                              route_values=route_values)
        return self._deserialize('[WorkItemStateResultModel]', self._unwrap_collection(response))

    def hide_state_definition(self, hide_state_model, process_id, wit_ref_name, state_id):
        """HideStateDefinition.
        [Preview API]
        :param :class:`<HideStateModel> <work-item-tracking.v4_0.models.HideStateModel>` hide_state_model:
        :param str process_id:
        :param str wit_ref_name:
        :param str state_id:
        :rtype: :class:`<WorkItemStateResultModel> <work-item-tracking.v4_0.models.WorkItemStateResultModel>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        if state_id is not None:
            route_values['stateId'] = self._serialize.url('state_id', state_id, 'str')
        content = self._serialize.body(hide_state_model, 'HideStateModel')
        response = self._send(http_method='PUT',
                              location_id='4303625d-08f4-4461-b14b-32c65bba5599',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('WorkItemStateResultModel', response)

    def update_state_definition(self, state_model, process_id, wit_ref_name, state_id):
        """UpdateStateDefinition.
        [Preview API]
        :param :class:`<WorkItemStateInputModel> <work-item-tracking.v4_0.models.WorkItemStateInputModel>` state_model:
        :param str process_id:
        :param str wit_ref_name:
        :param str state_id:
        :rtype: :class:`<WorkItemStateResultModel> <work-item-tracking.v4_0.models.WorkItemStateResultModel>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        if state_id is not None:
            route_values['stateId'] = self._serialize.url('state_id', state_id, 'str')
        content = self._serialize.body(state_model, 'WorkItemStateInputModel')
        response = self._send(http_method='PATCH',
                              location_id='4303625d-08f4-4461-b14b-32c65bba5599',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('WorkItemStateResultModel', response)

    def add_behavior_to_work_item_type(self, behavior, process_id, wit_ref_name_for_behaviors):
        """AddBehaviorToWorkItemType.
        [Preview API]
        :param :class:`<WorkItemTypeBehavior> <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` behavior:
        :param str process_id:
        :param str wit_ref_name_for_behaviors:
        :rtype: :class:`<WorkItemTypeBehavior> <work-item-tracking.v4_0.models.WorkItemTypeBehavior>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name_for_behaviors is not None:
            route_values['witRefNameForBehaviors'] = self._serialize.url('wit_ref_name_for_behaviors', wit_ref_name_for_behaviors, 'str')
        content = self._serialize.body(behavior, 'WorkItemTypeBehavior')
        response = self._send(http_method='POST',
                              location_id='921dfb88-ef57-4c69-94e5-dd7da2d7031d',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('WorkItemTypeBehavior', response)

    def get_behavior_for_work_item_type(self, process_id, wit_ref_name_for_behaviors, behavior_ref_name):
        """GetBehaviorForWorkItemType.
        [Preview API]
        :param str process_id:
        :param str wit_ref_name_for_behaviors:
        :param str behavior_ref_name:
        :rtype: :class:`<WorkItemTypeBehavior> <work-item-tracking.v4_0.models.WorkItemTypeBehavior>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name_for_behaviors is not None:
            route_values['witRefNameForBehaviors'] = self._serialize.url('wit_ref_name_for_behaviors', wit_ref_name_for_behaviors, 'str')
        if behavior_ref_name is not None:
            route_values['behaviorRefName'] = self._serialize.url('behavior_ref_name', behavior_ref_name, 'str')
        response = self._send(http_method='GET',
                              location_id='921dfb88-ef57-4c69-94e5-dd7da2d7031d',
                              version='4.0-preview.1',
                              route_values=route_values)
        return self._deserialize('WorkItemTypeBehavior', response)

    def get_behaviors_for_work_item_type(self, process_id, wit_ref_name_for_behaviors):
        """GetBehaviorsForWorkItemType.
        [Preview API]
        :param str process_id:
        :param str wit_ref_name_for_behaviors:
        :rtype: [WorkItemTypeBehavior]
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name_for_behaviors is not None:
            route_values['witRefNameForBehaviors'] = self._serialize.url('wit_ref_name_for_behaviors', wit_ref_name_for_behaviors, 'str')
        response = self._send(http_method='GET',
                              location_id='921dfb88-ef57-4c69-94e5-dd7da2d7031d',
                              version='4.0-preview.1',
                              route_values=route_values)
        return self._deserialize('[WorkItemTypeBehavior]', self._unwrap_collection(response))

    def remove_behavior_from_work_item_type(self, process_id, wit_ref_name_for_behaviors, behavior_ref_name):
        """RemoveBehaviorFromWorkItemType.
        [Preview API]
        :param str process_id:
        :param str wit_ref_name_for_behaviors:
        :param str behavior_ref_name:
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name_for_behaviors is not None:
            route_values['witRefNameForBehaviors'] = self._serialize.url('wit_ref_name_for_behaviors', wit_ref_name_for_behaviors, 'str')
        if behavior_ref_name is not None:
            route_values['behaviorRefName'] = self._serialize.url('behavior_ref_name', behavior_ref_name, 'str')
        self._send(http_method='DELETE',
                   location_id='921dfb88-ef57-4c69-94e5-dd7da2d7031d',
                   version='4.0-preview.1',
                   route_values=route_values)

    def update_behavior_to_work_item_type(self, behavior, process_id, wit_ref_name_for_behaviors):
        """UpdateBehaviorToWorkItemType.
        [Preview API]
        :param :class:`<WorkItemTypeBehavior> <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` behavior:
        :param str process_id:
        :param str wit_ref_name_for_behaviors:
        :rtype: :class:`<WorkItemTypeBehavior> <work-item-tracking.v4_0.models.WorkItemTypeBehavior>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name_for_behaviors is not None:
            route_values['witRefNameForBehaviors'] = self._serialize.url('wit_ref_name_for_behaviors', wit_ref_name_for_behaviors, 'str')
        content = self._serialize.body(behavior, 'WorkItemTypeBehavior')
        response = self._send(http_method='PATCH',
                              location_id='921dfb88-ef57-4c69-94e5-dd7da2d7031d',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('WorkItemTypeBehavior', response)

    def create_work_item_type(self, work_item_type, process_id):
        """CreateWorkItemType.
        [Preview API]
        :param :class:`<WorkItemTypeModel> <work-item-tracking.v4_0.models.WorkItemTypeModel>` work_item_type:
        :param str process_id:
        :rtype: :class:`<WorkItemTypeModel> <work-item-tracking.v4_0.models.WorkItemTypeModel>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        content = self._serialize.body(work_item_type, 'WorkItemTypeModel')
        response = self._send(http_method='POST',
                              location_id='1ce0acad-4638-49c3-969c-04aa65ba6bea',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('WorkItemTypeModel', response)

    def delete_work_item_type(self, process_id, wit_ref_name):
        """DeleteWorkItemType.
        [Preview API]
        :param str process_id:
        :param str wit_ref_name:
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        self._send(http_method='DELETE',
                   location_id='1ce0acad-4638-49c3-969c-04aa65ba6bea',
                   version='4.0-preview.1',
                   route_values=route_values)

    def get_work_item_type(self, process_id, wit_ref_name, expand=None):
        """GetWorkItemType.
        [Preview API]
        :param str process_id:
        :param str wit_ref_name:
        :param str expand:
        :rtype: :class:`<WorkItemTypeModel> <work-item-tracking.v4_0.models.WorkItemTypeModel>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        query_parameters = {}
        if expand is not None:
            query_parameters['$expand'] = self._serialize.query('expand', expand, 'str')
        response = self._send(http_method='GET',
                              location_id='1ce0acad-4638-49c3-969c-04aa65ba6bea',
                              version='4.0-preview.1',
                              route_values=route_values,
                              query_parameters=query_parameters)
        return self._deserialize('WorkItemTypeModel', response)

    def get_work_item_types(self, process_id, expand=None):
        """GetWorkItemTypes.
        [Preview API]
        :param str process_id:
        :param str expand:
        :rtype: [WorkItemTypeModel]
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        query_parameters = {}
        if expand is not None:
            query_parameters['$expand'] = self._serialize.query('expand', expand, 'str')
        response = self._send(http_method='GET',
                              location_id='1ce0acad-4638-49c3-969c-04aa65ba6bea',
                              version='4.0-preview.1',
                              route_values=route_values,
                              query_parameters=query_parameters)
        return self._deserialize('[WorkItemTypeModel]', self._unwrap_collection(response))

    def update_work_item_type(self, work_item_type_update, process_id, wit_ref_name):
        """UpdateWorkItemType.
        [Preview API]
        :param :class:`<WorkItemTypeUpdateModel> <work-item-tracking.v4_0.models.WorkItemTypeUpdateModel>` work_item_type_update:
        :param str process_id:
        :param str wit_ref_name:
        :rtype: :class:`<WorkItemTypeModel> <work-item-tracking.v4_0.models.WorkItemTypeModel>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name is not None:
            route_values['witRefName'] = self._serialize.url('wit_ref_name', wit_ref_name, 'str')
        content = self._serialize.body(work_item_type_update, 'WorkItemTypeUpdateModel')
        response = self._send(http_method='PATCH',
                              location_id='1ce0acad-4638-49c3-969c-04aa65ba6bea',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('WorkItemTypeModel', response)

    def add_field_to_work_item_type(self, field, process_id, wit_ref_name_for_fields):
        """AddFieldToWorkItemType.
        [Preview API]
        :param :class:`<WorkItemTypeFieldModel> <work-item-tracking.v4_0.models.WorkItemTypeFieldModel>` field:
        :param str process_id:
        :param str wit_ref_name_for_fields:
        :rtype: :class:`<WorkItemTypeFieldModel> <work-item-tracking.v4_0.models.WorkItemTypeFieldModel>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name_for_fields is not None:
            route_values['witRefNameForFields'] = self._serialize.url('wit_ref_name_for_fields', wit_ref_name_for_fields, 'str')
        content = self._serialize.body(field, 'WorkItemTypeFieldModel')
        response = self._send(http_method='POST',
                              location_id='976713b4-a62e-499e-94dc-eeb869ea9126',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('WorkItemTypeFieldModel', response)

    def get_work_item_type_field(self, process_id, wit_ref_name_for_fields, field_ref_name):
        """GetWorkItemTypeField.
        [Preview API]
        :param str process_id:
        :param str wit_ref_name_for_fields:
        :param str field_ref_name:
        :rtype: :class:`<WorkItemTypeFieldModel> <work-item-tracking.v4_0.models.WorkItemTypeFieldModel>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name_for_fields is not None:
            route_values['witRefNameForFields'] = self._serialize.url('wit_ref_name_for_fields', wit_ref_name_for_fields, 'str')
        if field_ref_name is not None:
            route_values['fieldRefName'] = self._serialize.url('field_ref_name', field_ref_name, 'str')
        response = self._send(http_method='GET',
                              location_id='976713b4-a62e-499e-94dc-eeb869ea9126',
                              version='4.0-preview.1',
                              route_values=route_values)
        return self._deserialize('WorkItemTypeFieldModel', response)

    def get_work_item_type_fields(self, process_id, wit_ref_name_for_fields):
        """GetWorkItemTypeFields.
        [Preview API]
        :param str process_id:
        :param str wit_ref_name_for_fields:
        :rtype: [WorkItemTypeFieldModel]
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name_for_fields is not None:
            route_values['witRefNameForFields'] = self._serialize.url('wit_ref_name_for_fields', wit_ref_name_for_fields, 'str')
        response = self._send(http_method='GET',
                              location_id='976713b4-a62e-499e-94dc-eeb869ea9126',
                              version='4.0-preview.1',
                              route_values=route_values)
        return self._deserialize('[WorkItemTypeFieldModel]', self._unwrap_collection(response))

    def remove_field_from_work_item_type(self, process_id, wit_ref_name_for_fields, field_ref_name):
        """RemoveFieldFromWorkItemType.
        [Preview API]
        :param str process_id:
        :param str wit_ref_name_for_fields:
        :param str field_ref_name:
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
        if wit_ref_name_for_fields is not None:
            route_values['witRefNameForFields'] = self._serialize.url('wit_ref_name_for_fields', wit_ref_name_for_fields, 'str')
        if field_ref_name is not None:
            route_values['fieldRefName'] = self._serialize.url('field_ref_name', field_ref_name, 'str')
        self._send(http_method='DELETE',
                   location_id='976713b4-a62e-499e-94dc-eeb869ea9126',
                   version='4.0-preview.1',
                   route_values=route_values)
Ejemplo n.º 31
0
class WikiClient(Client):
    """Wiki
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """
    def __init__(self, base_url=None, creds=None):
        super(WikiClient, self).__init__(base_url, creds)
        client_models = {
            k: v
            for k, v in models.__dict__.items() if isinstance(v, type)
        }
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = 'bf7d82a0-8aa5-4613-94ef-6172a5ea01f3'

    def create_attachment(self, upload_stream, project, wiki_identifier, name,
                          **kwargs):
        """CreateAttachment.
        Creates an attachment in the wiki.
        :param object upload_stream: Stream to upload
        :param str project: Project ID or project name
        :param str wiki_identifier: Wiki Id or name.
        :param str name: Wiki attachment name.
        :rtype: :class:`<WikiAttachmentResponse> <azure.devops.v5_0.wiki.models.WikiAttachmentResponse>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if wiki_identifier is not None:
            route_values['wikiIdentifier'] = self._serialize.url(
                'wiki_identifier', wiki_identifier, 'str')
        query_parameters = {}
        if name is not None:
            query_parameters['name'] = self._serialize.query(
                'name', name, 'str')
        if "callback" in kwargs:
            callback = kwargs["callback"]
        else:
            callback = None
        content = self._client.stream_upload(upload_stream, callback=callback)
        response = self._send(
            http_method='PUT',
            location_id='c4382d8d-fefc-40e0-92c5-49852e9e17c0',
            version='5.0',
            route_values=route_values,
            query_parameters=query_parameters,
            content=content,
            media_type='application/octet-stream')
        response_object = models.WikiAttachmentResponse()
        response_object.attachment = self._deserialize('WikiAttachment',
                                                       response)
        response_object.eTag = response.headers.get('ETag')
        return response_object

    def create_page_move(self,
                         page_move_parameters,
                         project,
                         wiki_identifier,
                         comment=None):
        """CreatePageMove.
        Creates a page move operation that updates the path and order of the page as provided in the parameters.
        :param :class:`<WikiPageMoveParameters> <azure.devops.v5_0.wiki.models.WikiPageMoveParameters>` page_move_parameters: Page more operation parameters.
        :param str project: Project ID or project name
        :param str wiki_identifier: Wiki Id or name.
        :param str comment: Comment that is to be associated with this page move.
        :rtype: :class:`<WikiPageMoveResponse> <azure.devops.v5_0.wiki.models.WikiPageMoveResponse>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if wiki_identifier is not None:
            route_values['wikiIdentifier'] = self._serialize.url(
                'wiki_identifier', wiki_identifier, 'str')
        query_parameters = {}
        if comment is not None:
            query_parameters['comment'] = self._serialize.query(
                'comment', comment, 'str')
        content = self._serialize.body(page_move_parameters,
                                       'WikiPageMoveParameters')
        response = self._send(
            http_method='POST',
            location_id='e37bbe71-cbae-49e5-9a4e-949143b9d910',
            version='5.0',
            route_values=route_values,
            query_parameters=query_parameters,
            content=content)
        response_object = models.WikiPageMoveResponse()
        response_object.page_move = self._deserialize('WikiPageMove', response)
        response_object.eTag = response.headers.get('ETag')
        return response_object

    def create_or_update_page(self,
                              parameters,
                              project,
                              wiki_identifier,
                              path,
                              version,
                              comment=None):
        """CreateOrUpdatePage.
        Creates or edits a wiki page.
        :param :class:`<WikiPageCreateOrUpdateParameters> <azure.devops.v5_0.wiki.models.WikiPageCreateOrUpdateParameters>` parameters: Wiki create or update operation parameters.
        :param str project: Project ID or project name
        :param str wiki_identifier: Wiki Id or name.
        :param str path: Wiki page path.
        :param String version: Version of the page on which the change is to be made. Mandatory for `Edit` scenario. To be populated in the If-Match header of the request.
        :param str comment: Comment to be associated with the page operation.
        :rtype: :class:`<WikiPageResponse> <azure.devops.v5_0.wiki.models.WikiPageResponse>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if wiki_identifier is not None:
            route_values['wikiIdentifier'] = self._serialize.url(
                'wiki_identifier', wiki_identifier, 'str')
        query_parameters = {}
        if path is not None:
            query_parameters['path'] = self._serialize.query(
                'path', path, 'str')
        if comment is not None:
            query_parameters['comment'] = self._serialize.query(
                'comment', comment, 'str')
        content = self._serialize.body(parameters,
                                       'WikiPageCreateOrUpdateParameters')
        response = self._send(
            http_method='PUT',
            location_id='25d3fbc7-fe3d-46cb-b5a5-0b6f79caf27b',
            version='5.0',
            route_values=route_values,
            query_parameters=query_parameters,
            content=content)
        response_object = models.WikiPageResponse()
        response_object.page = self._deserialize('WikiPage', response)
        response_object.eTag = response.headers.get('ETag')
        return response_object

    def delete_page(self, project, wiki_identifier, path, comment=None):
        """DeletePage.
        Deletes a wiki page.
        :param str project: Project ID or project name
        :param str wiki_identifier: Wiki Id or name.
        :param str path: Wiki page path.
        :param str comment: Comment to be associated with this page delete.
        :rtype: :class:`<WikiPageResponse> <azure.devops.v5_0.wiki.models.WikiPageResponse>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if wiki_identifier is not None:
            route_values['wikiIdentifier'] = self._serialize.url(
                'wiki_identifier', wiki_identifier, 'str')
        query_parameters = {}
        if path is not None:
            query_parameters['path'] = self._serialize.query(
                'path', path, 'str')
        if comment is not None:
            query_parameters['comment'] = self._serialize.query(
                'comment', comment, 'str')
        response = self._send(
            http_method='DELETE',
            location_id='25d3fbc7-fe3d-46cb-b5a5-0b6f79caf27b',
            version='5.0',
            route_values=route_values,
            query_parameters=query_parameters)
        response_object = models.WikiPageResponse()
        response_object.page = self._deserialize('WikiPage', response)
        response_object.eTag = response.headers.get('ETag')
        return response_object

    def get_page(self,
                 project,
                 wiki_identifier,
                 path=None,
                 recursion_level=None,
                 version_descriptor=None,
                 include_content=None):
        """GetPage.
        Gets metadata or content of the wiki page for the provided path. Content negotiation is done based on the `Accept` header sent in the request.
        :param str project: Project ID or project name
        :param str wiki_identifier: Wiki Id or name.
        :param str path: Wiki page path.
        :param str recursion_level: Recursion level for subpages retrieval. Defaults to `None` (Optional).
        :param :class:`<GitVersionDescriptor> <azure.devops.v5_0.wiki.models.GitVersionDescriptor>` version_descriptor: GitVersionDescriptor for the page. Defaults to the default branch (Optional).
        :param bool include_content: True to include the content of the page in the response for Json content type. Defaults to false (Optional)
        :rtype: :class:`<WikiPageResponse> <azure.devops.v5_0.wiki.models.WikiPageResponse>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if wiki_identifier is not None:
            route_values['wikiIdentifier'] = self._serialize.url(
                'wiki_identifier', wiki_identifier, 'str')
        query_parameters = {}
        if path is not None:
            query_parameters['path'] = self._serialize.query(
                'path', path, 'str')
        if recursion_level is not None:
            query_parameters['recursionLevel'] = self._serialize.query(
                'recursion_level', recursion_level, 'str')
        if version_descriptor is not None:
            if version_descriptor.version_type is not None:
                query_parameters[
                    'versionDescriptor.versionType'] = version_descriptor.version_type
            if version_descriptor.version is not None:
                query_parameters[
                    'versionDescriptor.version'] = version_descriptor.version
            if version_descriptor.version_options is not None:
                query_parameters[
                    'versionDescriptor.versionOptions'] = version_descriptor.version_options
        if include_content is not None:
            query_parameters['includeContent'] = self._serialize.query(
                'include_content', include_content, 'bool')
        response = self._send(
            http_method='GET',
            location_id='25d3fbc7-fe3d-46cb-b5a5-0b6f79caf27b',
            version='5.0',
            route_values=route_values,
            query_parameters=query_parameters)
        response_object = models.WikiPageResponse()
        response_object.page = self._deserialize('WikiPage', response)
        response_object.eTag = response.headers.get('ETag')
        return response_object

    def get_page_text(self,
                      project,
                      wiki_identifier,
                      path=None,
                      recursion_level=None,
                      version_descriptor=None,
                      include_content=None,
                      **kwargs):
        """GetPageText.
        Gets metadata or content of the wiki page for the provided path. Content negotiation is done based on the `Accept` header sent in the request.
        :param str project: Project ID or project name
        :param str wiki_identifier: Wiki Id or name.
        :param str path: Wiki page path.
        :param str recursion_level: Recursion level for subpages retrieval. Defaults to `None` (Optional).
        :param :class:`<GitVersionDescriptor> <azure.devops.v5_0.wiki.models.GitVersionDescriptor>` version_descriptor: GitVersionDescriptor for the page. Defaults to the default branch (Optional).
        :param bool include_content: True to include the content of the page in the response for Json content type. Defaults to false (Optional)
        :rtype: object
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if wiki_identifier is not None:
            route_values['wikiIdentifier'] = self._serialize.url(
                'wiki_identifier', wiki_identifier, 'str')
        query_parameters = {}
        if path is not None:
            query_parameters['path'] = self._serialize.query(
                'path', path, 'str')
        if recursion_level is not None:
            query_parameters['recursionLevel'] = self._serialize.query(
                'recursion_level', recursion_level, 'str')
        if version_descriptor is not None:
            if version_descriptor.version_type is not None:
                query_parameters[
                    'versionDescriptor.versionType'] = version_descriptor.version_type
            if version_descriptor.version is not None:
                query_parameters[
                    'versionDescriptor.version'] = version_descriptor.version
            if version_descriptor.version_options is not None:
                query_parameters[
                    'versionDescriptor.versionOptions'] = version_descriptor.version_options
        if include_content is not None:
            query_parameters['includeContent'] = self._serialize.query(
                'include_content', include_content, 'bool')
        response = self._send(
            http_method='GET',
            location_id='25d3fbc7-fe3d-46cb-b5a5-0b6f79caf27b',
            version='5.0',
            route_values=route_values,
            query_parameters=query_parameters,
            accept_media_type='text/plain')
        if "callback" in kwargs:
            callback = kwargs["callback"]
        else:
            callback = None
        return self._client.stream_download(response, callback=callback)

    def get_page_zip(self,
                     project,
                     wiki_identifier,
                     path=None,
                     recursion_level=None,
                     version_descriptor=None,
                     include_content=None,
                     **kwargs):
        """GetPageZip.
        Gets metadata or content of the wiki page for the provided path. Content negotiation is done based on the `Accept` header sent in the request.
        :param str project: Project ID or project name
        :param str wiki_identifier: Wiki Id or name.
        :param str path: Wiki page path.
        :param str recursion_level: Recursion level for subpages retrieval. Defaults to `None` (Optional).
        :param :class:`<GitVersionDescriptor> <azure.devops.v5_0.wiki.models.GitVersionDescriptor>` version_descriptor: GitVersionDescriptor for the page. Defaults to the default branch (Optional).
        :param bool include_content: True to include the content of the page in the response for Json content type. Defaults to false (Optional)
        :rtype: object
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if wiki_identifier is not None:
            route_values['wikiIdentifier'] = self._serialize.url(
                'wiki_identifier', wiki_identifier, 'str')
        query_parameters = {}
        if path is not None:
            query_parameters['path'] = self._serialize.query(
                'path', path, 'str')
        if recursion_level is not None:
            query_parameters['recursionLevel'] = self._serialize.query(
                'recursion_level', recursion_level, 'str')
        if version_descriptor is not None:
            if version_descriptor.version_type is not None:
                query_parameters[
                    'versionDescriptor.versionType'] = version_descriptor.version_type
            if version_descriptor.version is not None:
                query_parameters[
                    'versionDescriptor.version'] = version_descriptor.version
            if version_descriptor.version_options is not None:
                query_parameters[
                    'versionDescriptor.versionOptions'] = version_descriptor.version_options
        if include_content is not None:
            query_parameters['includeContent'] = self._serialize.query(
                'include_content', include_content, 'bool')
        response = self._send(
            http_method='GET',
            location_id='25d3fbc7-fe3d-46cb-b5a5-0b6f79caf27b',
            version='5.0',
            route_values=route_values,
            query_parameters=query_parameters,
            accept_media_type='application/zip')
        if "callback" in kwargs:
            callback = kwargs["callback"]
        else:
            callback = None
        return self._client.stream_download(response, callback=callback)

    def create_wiki(self, wiki_create_params, project=None):
        """CreateWiki.
        Creates the wiki resource.
        :param :class:`<WikiCreateParametersV2> <azure.devops.v5_0.wiki.models.WikiCreateParametersV2>` wiki_create_params: Parameters for the wiki creation.
        :param str project: Project ID or project name
        :rtype: :class:`<WikiV2> <azure.devops.v5_0.wiki.models.WikiV2>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        content = self._serialize.body(wiki_create_params,
                                       'WikiCreateParametersV2')
        response = self._send(
            http_method='POST',
            location_id='288d122c-dbd4-451d-aa5f-7dbbba070728',
            version='5.0',
            route_values=route_values,
            content=content)
        return self._deserialize('WikiV2', response)

    def delete_wiki(self, wiki_identifier, project=None):
        """DeleteWiki.
        Deletes the wiki corresponding to the wiki name or Id provided.
        :param str wiki_identifier: Wiki name or Id.
        :param str project: Project ID or project name
        :rtype: :class:`<WikiV2> <azure.devops.v5_0.wiki.models.WikiV2>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if wiki_identifier is not None:
            route_values['wikiIdentifier'] = self._serialize.url(
                'wiki_identifier', wiki_identifier, 'str')
        response = self._send(
            http_method='DELETE',
            location_id='288d122c-dbd4-451d-aa5f-7dbbba070728',
            version='5.0',
            route_values=route_values)
        return self._deserialize('WikiV2', response)

    def get_all_wikis(self, project=None):
        """GetAllWikis.
        Gets all wikis in a project or collection.
        :param str project: Project ID or project name
        :rtype: [WikiV2]
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        response = self._send(
            http_method='GET',
            location_id='288d122c-dbd4-451d-aa5f-7dbbba070728',
            version='5.0',
            route_values=route_values)
        return self._deserialize('[WikiV2]', self._unwrap_collection(response))

    def get_wiki(self, wiki_identifier, project=None):
        """GetWiki.
        Gets the wiki corresponding to the wiki name or Id provided.
        :param str wiki_identifier: Wiki name or id.
        :param str project: Project ID or project name
        :rtype: :class:`<WikiV2> <azure.devops.v5_0.wiki.models.WikiV2>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if wiki_identifier is not None:
            route_values['wikiIdentifier'] = self._serialize.url(
                'wiki_identifier', wiki_identifier, 'str')
        response = self._send(
            http_method='GET',
            location_id='288d122c-dbd4-451d-aa5f-7dbbba070728',
            version='5.0',
            route_values=route_values)
        return self._deserialize('WikiV2', response)

    def update_wiki(self, update_parameters, wiki_identifier, project=None):
        """UpdateWiki.
        Updates the wiki corresponding to the wiki Id or name provided using the update parameters.
        :param :class:`<WikiUpdateParameters> <azure.devops.v5_0.wiki.models.WikiUpdateParameters>` update_parameters: Update parameters.
        :param str wiki_identifier: Wiki name or Id.
        :param str project: Project ID or project name
        :rtype: :class:`<WikiV2> <azure.devops.v5_0.wiki.models.WikiV2>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url(
                'project', project, 'str')
        if wiki_identifier is not None:
            route_values['wikiIdentifier'] = self._serialize.url(
                'wiki_identifier', wiki_identifier, 'str')
        content = self._serialize.body(update_parameters,
                                       'WikiUpdateParameters')
        response = self._send(
            http_method='PATCH',
            location_id='288d122c-dbd4-451d-aa5f-7dbbba070728',
            version='5.0',
            route_values=route_values,
            content=content)
        return self._deserialize('WikiV2', response)
class NotificationClient(Client):
    """Notification
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """
    def __init__(self, base_url=None, creds=None):
        super(NotificationClient, self).__init__(base_url, creds)
        client_models = {
            k: v
            for k, v in models.__dict__.items() if isinstance(v, type)
        }
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = None

    def list_logs(self, source, entry_id=None, start_time=None, end_time=None):
        """ListLogs.
        [Preview API] Get a list of diagnostic logs for this service.
        :param str source: ID specifying which type of logs to check diagnostics for.
        :param str entry_id: The ID of the specific log to query for.
        :param datetime start_time: Start time for the time range to query in.
        :param datetime end_time: End time for the time range to query in.
        :rtype: [INotificationDiagnosticLog]
        """
        route_values = {}
        if source is not None:
            route_values['source'] = self._serialize.url(
                'source', source, 'str')
        if entry_id is not None:
            route_values['entryId'] = self._serialize.url(
                'entry_id', entry_id, 'str')
        query_parameters = {}
        if start_time is not None:
            query_parameters['startTime'] = self._serialize.query(
                'start_time', start_time, 'iso-8601')
        if end_time is not None:
            query_parameters['endTime'] = self._serialize.query(
                'end_time', end_time, 'iso-8601')
        response = self._send(
            http_method='GET',
            location_id='991842f3-eb16-4aea-ac81-81353ef2b75c',
            version='6.0-preview.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[INotificationDiagnosticLog]',
                                 self._unwrap_collection(response))

    def get_subscription_diagnostics(self, subscription_id):
        """GetSubscriptionDiagnostics.
        [Preview API] Get the diagnostics settings for a subscription.
        :param str subscription_id: The id of the notifications subscription.
        :rtype: :class:`<SubscriptionDiagnostics> <azure.devops.v6_0.notification.models.SubscriptionDiagnostics>`
        """
        route_values = {}
        if subscription_id is not None:
            route_values['subscriptionId'] = self._serialize.url(
                'subscription_id', subscription_id, 'str')
        response = self._send(
            http_method='GET',
            location_id='20f1929d-4be7-4c2e-a74e-d47640ff3418',
            version='6.0-preview.1',
            route_values=route_values)
        return self._deserialize('SubscriptionDiagnostics', response)

    def update_subscription_diagnostics(self, update_parameters,
                                        subscription_id):
        """UpdateSubscriptionDiagnostics.
        [Preview API] Update the diagnostics settings for a subscription.
        :param :class:`<UpdateSubscripitonDiagnosticsParameters> <azure.devops.v6_0.notification.models.UpdateSubscripitonDiagnosticsParameters>` update_parameters:
        :param str subscription_id: The id of the notifications subscription.
        :rtype: :class:`<SubscriptionDiagnostics> <azure.devops.v6_0.notification.models.SubscriptionDiagnostics>`
        """
        route_values = {}
        if subscription_id is not None:
            route_values['subscriptionId'] = self._serialize.url(
                'subscription_id', subscription_id, 'str')
        content = self._serialize.body(
            update_parameters, 'UpdateSubscripitonDiagnosticsParameters')
        response = self._send(
            http_method='PUT',
            location_id='20f1929d-4be7-4c2e-a74e-d47640ff3418',
            version='6.0-preview.1',
            route_values=route_values,
            content=content)
        return self._deserialize('SubscriptionDiagnostics', response)

    def get_event_type(self, event_type):
        """GetEventType.
        [Preview API] Get a specific event type.
        :param str event_type: The ID of the event type.
        :rtype: :class:`<NotificationEventType> <azure.devops.v6_0.notification.models.NotificationEventType>`
        """
        route_values = {}
        if event_type is not None:
            route_values['eventType'] = self._serialize.url(
                'event_type', event_type, 'str')
        response = self._send(
            http_method='GET',
            location_id='cc84fb5f-6247-4c7a-aeae-e5a3c3fddb21',
            version='6.0-preview.1',
            route_values=route_values)
        return self._deserialize('NotificationEventType', response)

    def list_event_types(self, publisher_id=None):
        """ListEventTypes.
        [Preview API] List available event types for this service. Optionally filter by only event types for the specified publisher.
        :param str publisher_id: Limit to event types for this publisher
        :rtype: [NotificationEventType]
        """
        query_parameters = {}
        if publisher_id is not None:
            query_parameters['publisherId'] = self._serialize.query(
                'publisher_id', publisher_id, 'str')
        response = self._send(
            http_method='GET',
            location_id='cc84fb5f-6247-4c7a-aeae-e5a3c3fddb21',
            version='6.0-preview.1',
            query_parameters=query_parameters)
        return self._deserialize('[NotificationEventType]',
                                 self._unwrap_collection(response))

    def get_settings(self):
        """GetSettings.
        [Preview API]
        :rtype: :class:`<NotificationAdminSettings> <azure.devops.v6_0.notification.models.NotificationAdminSettings>`
        """
        response = self._send(
            http_method='GET',
            location_id='cbe076d8-2803-45ff-8d8d-44653686ea2a',
            version='6.0-preview.1')
        return self._deserialize('NotificationAdminSettings', response)

    def update_settings(self, update_parameters):
        """UpdateSettings.
        [Preview API]
        :param :class:`<NotificationAdminSettingsUpdateParameters> <azure.devops.v6_0.notification.models.NotificationAdminSettingsUpdateParameters>` update_parameters:
        :rtype: :class:`<NotificationAdminSettings> <azure.devops.v6_0.notification.models.NotificationAdminSettings>`
        """
        content = self._serialize.body(
            update_parameters, 'NotificationAdminSettingsUpdateParameters')
        response = self._send(
            http_method='PATCH',
            location_id='cbe076d8-2803-45ff-8d8d-44653686ea2a',
            version='6.0-preview.1',
            content=content)
        return self._deserialize('NotificationAdminSettings', response)

    def get_subscriber(self, subscriber_id):
        """GetSubscriber.
        [Preview API] Get delivery preferences of a notifications subscriber.
        :param str subscriber_id: ID of the user or group.
        :rtype: :class:`<NotificationSubscriber> <azure.devops.v6_0.notification.models.NotificationSubscriber>`
        """
        route_values = {}
        if subscriber_id is not None:
            route_values['subscriberId'] = self._serialize.url(
                'subscriber_id', subscriber_id, 'str')
        response = self._send(
            http_method='GET',
            location_id='4d5caff1-25ba-430b-b808-7a1f352cc197',
            version='6.0-preview.1',
            route_values=route_values)
        return self._deserialize('NotificationSubscriber', response)

    def update_subscriber(self, update_parameters, subscriber_id):
        """UpdateSubscriber.
        [Preview API] Update delivery preferences of a notifications subscriber.
        :param :class:`<NotificationSubscriberUpdateParameters> <azure.devops.v6_0.notification.models.NotificationSubscriberUpdateParameters>` update_parameters:
        :param str subscriber_id: ID of the user or group.
        :rtype: :class:`<NotificationSubscriber> <azure.devops.v6_0.notification.models.NotificationSubscriber>`
        """
        route_values = {}
        if subscriber_id is not None:
            route_values['subscriberId'] = self._serialize.url(
                'subscriber_id', subscriber_id, 'str')
        content = self._serialize.body(
            update_parameters, 'NotificationSubscriberUpdateParameters')
        response = self._send(
            http_method='PATCH',
            location_id='4d5caff1-25ba-430b-b808-7a1f352cc197',
            version='6.0-preview.1',
            route_values=route_values,
            content=content)
        return self._deserialize('NotificationSubscriber', response)

    def query_subscriptions(self, subscription_query):
        """QuerySubscriptions.
        [Preview API] Query for subscriptions. A subscription is returned if it matches one or more of the specified conditions.
        :param :class:`<SubscriptionQuery> <azure.devops.v6_0.notification.models.SubscriptionQuery>` subscription_query:
        :rtype: [NotificationSubscription]
        """
        content = self._serialize.body(subscription_query, 'SubscriptionQuery')
        response = self._send(
            http_method='POST',
            location_id='6864db85-08c0-4006-8e8e-cc1bebe31675',
            version='6.0-preview.1',
            content=content)
        return self._deserialize('[NotificationSubscription]',
                                 self._unwrap_collection(response))

    def create_subscription(self, create_parameters):
        """CreateSubscription.
        [Preview API] Create a new subscription.
        :param :class:`<NotificationSubscriptionCreateParameters> <azure.devops.v6_0.notification.models.NotificationSubscriptionCreateParameters>` create_parameters:
        :rtype: :class:`<NotificationSubscription> <azure.devops.v6_0.notification.models.NotificationSubscription>`
        """
        content = self._serialize.body(
            create_parameters, 'NotificationSubscriptionCreateParameters')
        response = self._send(
            http_method='POST',
            location_id='70f911d6-abac-488c-85b3-a206bf57e165',
            version='6.0-preview.1',
            content=content)
        return self._deserialize('NotificationSubscription', response)

    def delete_subscription(self, subscription_id):
        """DeleteSubscription.
        [Preview API] Delete a subscription.
        :param str subscription_id:
        """
        route_values = {}
        if subscription_id is not None:
            route_values['subscriptionId'] = self._serialize.url(
                'subscription_id', subscription_id, 'str')
        self._send(http_method='DELETE',
                   location_id='70f911d6-abac-488c-85b3-a206bf57e165',
                   version='6.0-preview.1',
                   route_values=route_values)

    def get_subscription(self, subscription_id, query_flags=None):
        """GetSubscription.
        [Preview API] Get a notification subscription by its ID.
        :param str subscription_id:
        :param str query_flags:
        :rtype: :class:`<NotificationSubscription> <azure.devops.v6_0.notification.models.NotificationSubscription>`
        """
        route_values = {}
        if subscription_id is not None:
            route_values['subscriptionId'] = self._serialize.url(
                'subscription_id', subscription_id, 'str')
        query_parameters = {}
        if query_flags is not None:
            query_parameters['queryFlags'] = self._serialize.query(
                'query_flags', query_flags, 'str')
        response = self._send(
            http_method='GET',
            location_id='70f911d6-abac-488c-85b3-a206bf57e165',
            version='6.0-preview.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('NotificationSubscription', response)

    def list_subscriptions(self, target_id=None, ids=None, query_flags=None):
        """ListSubscriptions.
        [Preview API] Get a list of notification subscriptions, either by subscription IDs or by all subscriptions for a given user or group.
        :param str target_id: User or Group ID
        :param [str] ids: List of subscription IDs
        :param str query_flags:
        :rtype: [NotificationSubscription]
        """
        query_parameters = {}
        if target_id is not None:
            query_parameters['targetId'] = self._serialize.query(
                'target_id', target_id, 'str')
        if ids is not None:
            ids = ",".join(ids)
            query_parameters['ids'] = self._serialize.query('ids', ids, 'str')
        if query_flags is not None:
            query_parameters['queryFlags'] = self._serialize.query(
                'query_flags', query_flags, 'str')
        response = self._send(
            http_method='GET',
            location_id='70f911d6-abac-488c-85b3-a206bf57e165',
            version='6.0-preview.1',
            query_parameters=query_parameters)
        return self._deserialize('[NotificationSubscription]',
                                 self._unwrap_collection(response))

    def update_subscription(self, update_parameters, subscription_id):
        """UpdateSubscription.
        [Preview API] Update an existing subscription. Depending on the type of subscription and permissions, the caller can update the description, filter settings, channel (delivery) settings and more.
        :param :class:`<NotificationSubscriptionUpdateParameters> <azure.devops.v6_0.notification.models.NotificationSubscriptionUpdateParameters>` update_parameters:
        :param str subscription_id:
        :rtype: :class:`<NotificationSubscription> <azure.devops.v6_0.notification.models.NotificationSubscription>`
        """
        route_values = {}
        if subscription_id is not None:
            route_values['subscriptionId'] = self._serialize.url(
                'subscription_id', subscription_id, 'str')
        content = self._serialize.body(
            update_parameters, 'NotificationSubscriptionUpdateParameters')
        response = self._send(
            http_method='PATCH',
            location_id='70f911d6-abac-488c-85b3-a206bf57e165',
            version='6.0-preview.1',
            route_values=route_values,
            content=content)
        return self._deserialize('NotificationSubscription', response)

    def get_subscription_templates(self):
        """GetSubscriptionTemplates.
        [Preview API] Get available subscription templates.
        :rtype: [NotificationSubscriptionTemplate]
        """
        response = self._send(
            http_method='GET',
            location_id='fa5d24ba-7484-4f3d-888d-4ec6b1974082',
            version='6.0-preview.1')
        return self._deserialize('[NotificationSubscriptionTemplate]',
                                 self._unwrap_collection(response))

    def update_subscription_user_settings(self, user_settings, subscription_id,
                                          user_id):
        """UpdateSubscriptionUserSettings.
        [Preview API] Update the specified user's settings for the specified subscription. This API is typically used to opt in or out of a shared subscription. User settings can only be applied to shared subscriptions, like team subscriptions or default subscriptions.
        :param :class:`<SubscriptionUserSettings> <azure.devops.v6_0.notification.models.SubscriptionUserSettings>` user_settings:
        :param str subscription_id:
        :param str user_id: ID of the user
        :rtype: :class:`<SubscriptionUserSettings> <azure.devops.v6_0.notification.models.SubscriptionUserSettings>`
        """
        route_values = {}
        if subscription_id is not None:
            route_values['subscriptionId'] = self._serialize.url(
                'subscription_id', subscription_id, 'str')
        if user_id is not None:
            route_values['userId'] = self._serialize.url(
                'user_id', user_id, 'str')
        content = self._serialize.body(user_settings,
                                       'SubscriptionUserSettings')
        response = self._send(
            http_method='PUT',
            location_id='ed5a3dff-aeb5-41b1-b4f7-89e66e58b62e',
            version='6.0-preview.1',
            route_values=route_values,
            content=content)
        return self._deserialize('SubscriptionUserSettings', response)
Ejemplo n.º 33
0
class FeatureManagementClient(VssClient):
    """FeatureManagement
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """

    def __init__(self, base_url=None, creds=None):
        super(FeatureManagementClient, self).__init__(base_url, creds)
        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = None

    def get_feature(self, feature_id):
        """GetFeature.
        [Preview API] Get a specific feature by its id
        :param str feature_id: The contribution id of the feature
        :rtype: :class:`<ContributedFeature> <feature-management.v4_0.models.ContributedFeature>`
        """
        route_values = {}
        if feature_id is not None:
            route_values['featureId'] = self._serialize.url('feature_id', feature_id, 'str')
        response = self._send(http_method='GET',
                              location_id='c4209f25-7a27-41dd-9f04-06080c7b6afd',
                              version='4.0-preview.1',
                              route_values=route_values)
        return self._deserialize('ContributedFeature', response)

    def get_features(self, target_contribution_id=None):
        """GetFeatures.
        [Preview API] Get a list of all defined features
        :param str target_contribution_id: Optional target contribution. If null/empty, return all features. If specified include the features that target the specified contribution.
        :rtype: [ContributedFeature]
        """
        query_parameters = {}
        if target_contribution_id is not None:
            query_parameters['targetContributionId'] = self._serialize.query('target_contribution_id', target_contribution_id, 'str')
        response = self._send(http_method='GET',
                              location_id='c4209f25-7a27-41dd-9f04-06080c7b6afd',
                              version='4.0-preview.1',
                              query_parameters=query_parameters,
                              returns_collection=True)
        return self._deserialize('[ContributedFeature]', response)

    def get_feature_state(self, feature_id, user_scope):
        """GetFeatureState.
        [Preview API] Get the state of the specified feature for the given user/all-users scope
        :param str feature_id: Contribution id of the feature
        :param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
        :rtype: :class:`<ContributedFeatureState> <feature-management.v4_0.models.ContributedFeatureState>`
        """
        route_values = {}
        if feature_id is not None:
            route_values['featureId'] = self._serialize.url('feature_id', feature_id, 'str')
        if user_scope is not None:
            route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
        response = self._send(http_method='GET',
                              location_id='98911314-3f9b-4eaf-80e8-83900d8e85d9',
                              version='4.0-preview.1',
                              route_values=route_values)
        return self._deserialize('ContributedFeatureState', response)

    def set_feature_state(self, feature, feature_id, user_scope, reason=None, reason_code=None):
        """SetFeatureState.
        [Preview API] Set the state of a feature
        :param :class:`<ContributedFeatureState> <feature-management.v4_0.models.ContributedFeatureState>` feature: Posted feature state object. Should specify the effective value.
        :param str feature_id: Contribution id of the feature
        :param str user_scope: User-Scope at which to set the value. Should be "me" for the current user or "host" for all users.
        :param str reason: Reason for changing the state
        :param str reason_code: Short reason code
        :rtype: :class:`<ContributedFeatureState> <feature-management.v4_0.models.ContributedFeatureState>`
        """
        route_values = {}
        if feature_id is not None:
            route_values['featureId'] = self._serialize.url('feature_id', feature_id, 'str')
        if user_scope is not None:
            route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
        query_parameters = {}
        if reason is not None:
            query_parameters['reason'] = self._serialize.query('reason', reason, 'str')
        if reason_code is not None:
            query_parameters['reasonCode'] = self._serialize.query('reason_code', reason_code, 'str')
        content = self._serialize.body(feature, 'ContributedFeatureState')
        response = self._send(http_method='PATCH',
                              location_id='98911314-3f9b-4eaf-80e8-83900d8e85d9',
                              version='4.0-preview.1',
                              route_values=route_values,
                              query_parameters=query_parameters,
                              content=content)
        return self._deserialize('ContributedFeatureState', response)

    def get_feature_state_for_scope(self, feature_id, user_scope, scope_name, scope_value):
        """GetFeatureStateForScope.
        [Preview API] Get the state of the specified feature for the given named scope
        :param str feature_id: Contribution id of the feature
        :param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
        :param str scope_name: Scope at which to get the feature setting for (e.g. "project" or "team")
        :param str scope_value: Value of the scope (e.g. the project or team id)
        :rtype: :class:`<ContributedFeatureState> <feature-management.v4_0.models.ContributedFeatureState>`
        """
        route_values = {}
        if feature_id is not None:
            route_values['featureId'] = self._serialize.url('feature_id', feature_id, 'str')
        if user_scope is not None:
            route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
        if scope_name is not None:
            route_values['scopeName'] = self._serialize.url('scope_name', scope_name, 'str')
        if scope_value is not None:
            route_values['scopeValue'] = self._serialize.url('scope_value', scope_value, 'str')
        response = self._send(http_method='GET',
                              location_id='dd291e43-aa9f-4cee-8465-a93c78e414a4',
                              version='4.0-preview.1',
                              route_values=route_values)
        return self._deserialize('ContributedFeatureState', response)

    def set_feature_state_for_scope(self, feature, feature_id, user_scope, scope_name, scope_value, reason=None, reason_code=None):
        """SetFeatureStateForScope.
        [Preview API] Set the state of a feature at a specific scope
        :param :class:`<ContributedFeatureState> <feature-management.v4_0.models.ContributedFeatureState>` feature: Posted feature state object. Should specify the effective value.
        :param str feature_id: Contribution id of the feature
        :param str user_scope: User-Scope at which to set the value. Should be "me" for the current user or "host" for all users.
        :param str scope_name: Scope at which to get the feature setting for (e.g. "project" or "team")
        :param str scope_value: Value of the scope (e.g. the project or team id)
        :param str reason: Reason for changing the state
        :param str reason_code: Short reason code
        :rtype: :class:`<ContributedFeatureState> <feature-management.v4_0.models.ContributedFeatureState>`
        """
        route_values = {}
        if feature_id is not None:
            route_values['featureId'] = self._serialize.url('feature_id', feature_id, 'str')
        if user_scope is not None:
            route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
        if scope_name is not None:
            route_values['scopeName'] = self._serialize.url('scope_name', scope_name, 'str')
        if scope_value is not None:
            route_values['scopeValue'] = self._serialize.url('scope_value', scope_value, 'str')
        query_parameters = {}
        if reason is not None:
            query_parameters['reason'] = self._serialize.query('reason', reason, 'str')
        if reason_code is not None:
            query_parameters['reasonCode'] = self._serialize.query('reason_code', reason_code, 'str')
        content = self._serialize.body(feature, 'ContributedFeatureState')
        response = self._send(http_method='PATCH',
                              location_id='dd291e43-aa9f-4cee-8465-a93c78e414a4',
                              version='4.0-preview.1',
                              route_values=route_values,
                              query_parameters=query_parameters,
                              content=content)
        return self._deserialize('ContributedFeatureState', response)

    def query_feature_states(self, query):
        """QueryFeatureStates.
        [Preview API] Get the effective state for a list of feature ids
        :param :class:`<ContributedFeatureStateQuery> <feature-management.v4_0.models.ContributedFeatureStateQuery>` query: Features to query along with current scope values
        :rtype: :class:`<ContributedFeatureStateQuery> <feature-management.v4_0.models.ContributedFeatureStateQuery>`
        """
        content = self._serialize.body(query, 'ContributedFeatureStateQuery')
        response = self._send(http_method='POST',
                              location_id='2b4486ad-122b-400c-ae65-17b6672c1f9d',
                              version='4.0-preview.1',
                              content=content)
        return self._deserialize('ContributedFeatureStateQuery', response)

    def query_feature_states_for_default_scope(self, query, user_scope):
        """QueryFeatureStatesForDefaultScope.
        [Preview API] Get the states of the specified features for the default scope
        :param :class:`<ContributedFeatureStateQuery> <feature-management.v4_0.models.ContributedFeatureStateQuery>` query: Query describing the features to query.
        :param str user_scope:
        :rtype: :class:`<ContributedFeatureStateQuery> <feature-management.v4_0.models.ContributedFeatureStateQuery>`
        """
        route_values = {}
        if user_scope is not None:
            route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
        content = self._serialize.body(query, 'ContributedFeatureStateQuery')
        response = self._send(http_method='POST',
                              location_id='3f810f28-03e2-4239-b0bc-788add3005e5',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('ContributedFeatureStateQuery', response)

    def query_feature_states_for_named_scope(self, query, user_scope, scope_name, scope_value):
        """QueryFeatureStatesForNamedScope.
        [Preview API] Get the states of the specified features for the specific named scope
        :param :class:`<ContributedFeatureStateQuery> <feature-management.v4_0.models.ContributedFeatureStateQuery>` query: Query describing the features to query.
        :param str user_scope:
        :param str scope_name:
        :param str scope_value:
        :rtype: :class:`<ContributedFeatureStateQuery> <feature-management.v4_0.models.ContributedFeatureStateQuery>`
        """
        route_values = {}
        if user_scope is not None:
            route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
        if scope_name is not None:
            route_values['scopeName'] = self._serialize.url('scope_name', scope_name, 'str')
        if scope_value is not None:
            route_values['scopeValue'] = self._serialize.url('scope_value', scope_value, 'str')
        content = self._serialize.body(query, 'ContributedFeatureStateQuery')
        response = self._send(http_method='POST',
                              location_id='f29e997b-c2da-4d15-8380-765788a1a74c',
                              version='4.0-preview.1',
                              route_values=route_values,
                              content=content)
        return self._deserialize('ContributedFeatureStateQuery', response)
Ejemplo n.º 34
0
class CoreClient(Client):
    """Core
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """
    def __init__(self, base_url=None, creds=None):
        super(CoreClient, self).__init__(base_url, creds)
        client_models = {
            k: v
            for k, v in models.__dict__.items() if isinstance(v, type)
        }
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = '79134c72-4a58-4b42-976c-04e7115f32bf'

    def remove_project_avatar(self, project_id):
        """RemoveProjectAvatar.
        [Preview API] Removes the avatar for the project.
        :param str project_id: The ID or name of the project.
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        self._send(http_method='DELETE',
                   location_id='54b2a2a0-859b-4d05-827c-ec4c862f641a',
                   version='5.1-preview.1',
                   route_values=route_values)

    def set_project_avatar(self, avatar_blob, project_id):
        """SetProjectAvatar.
        [Preview API] Sets the avatar for the project.
        :param :class:`<ProjectAvatar> <azure.devops.v5_1.core.models.ProjectAvatar>` avatar_blob: The avatar blob data object to upload.
        :param str project_id: The ID or name of the project.
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        content = self._serialize.body(avatar_blob, 'ProjectAvatar')
        self._send(http_method='PUT',
                   location_id='54b2a2a0-859b-4d05-827c-ec4c862f641a',
                   version='5.1-preview.1',
                   route_values=route_values,
                   content=content)

    def create_connected_service(self, connected_service_creation_data,
                                 project_id):
        """CreateConnectedService.
        [Preview API]
        :param :class:`<WebApiConnectedServiceDetails> <azure.devops.v5_1.core.models.WebApiConnectedServiceDetails>` connected_service_creation_data:
        :param str project_id:
        :rtype: :class:`<WebApiConnectedService> <azure.devops.v5_1.core.models.WebApiConnectedService>`
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        content = self._serialize.body(connected_service_creation_data,
                                       'WebApiConnectedServiceDetails')
        response = self._send(
            http_method='POST',
            location_id='b4f70219-e18b-42c5-abe3-98b07d35525e',
            version='5.1-preview.1',
            route_values=route_values,
            content=content)
        return self._deserialize('WebApiConnectedService', response)

    def get_connected_service_details(self, project_id, name):
        """GetConnectedServiceDetails.
        [Preview API]
        :param str project_id:
        :param str name:
        :rtype: :class:`<WebApiConnectedServiceDetails> <azure.devops.v5_1.core.models.WebApiConnectedServiceDetails>`
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        if name is not None:
            route_values['name'] = self._serialize.url('name', name, 'str')
        response = self._send(
            http_method='GET',
            location_id='b4f70219-e18b-42c5-abe3-98b07d35525e',
            version='5.1-preview.1',
            route_values=route_values)
        return self._deserialize('WebApiConnectedServiceDetails', response)

    def get_connected_services(self, project_id, kind=None):
        """GetConnectedServices.
        [Preview API]
        :param str project_id:
        :param str kind:
        :rtype: [WebApiConnectedService]
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        query_parameters = {}
        if kind is not None:
            query_parameters['kind'] = self._serialize.query(
                'kind', kind, 'str')
        response = self._send(
            http_method='GET',
            location_id='b4f70219-e18b-42c5-abe3-98b07d35525e',
            version='5.1-preview.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[WebApiConnectedService]',
                                 self._unwrap_collection(response))

    def get_team_members_with_extended_properties(self,
                                                  project_id,
                                                  team_id,
                                                  top=None,
                                                  skip=None):
        """GetTeamMembersWithExtendedProperties.
        Get a list of members for a specific team.
        :param str project_id: The name or ID (GUID) of the team project the team belongs to.
        :param str team_id: The name or ID (GUID) of the team .
        :param int top:
        :param int skip:
        :rtype: [TeamMember]
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        if team_id is not None:
            route_values['teamId'] = self._serialize.url(
                'team_id', team_id, 'str')
        query_parameters = {}
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        if skip is not None:
            query_parameters['$skip'] = self._serialize.query(
                'skip', skip, 'int')
        response = self._send(
            http_method='GET',
            location_id='294c494c-2600-4d7e-b76c-3dd50c3c95be',
            version='5.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[TeamMember]',
                                 self._unwrap_collection(response))

    def get_process_by_id(self, process_id):
        """GetProcessById.
        Get a process by ID.
        :param str process_id: ID for a process.
        :rtype: :class:`<Process> <azure.devops.v5_1.core.models.Process>`
        """
        route_values = {}
        if process_id is not None:
            route_values['processId'] = self._serialize.url(
                'process_id', process_id, 'str')
        response = self._send(
            http_method='GET',
            location_id='93878975-88c5-4e6a-8abb-7ddd77a8a7d8',
            version='5.1',
            route_values=route_values)
        return self._deserialize('Process', response)

    def get_processes(self):
        """GetProcesses.
        Get a list of processes.
        :rtype: [Process]
        """
        response = self._send(
            http_method='GET',
            location_id='93878975-88c5-4e6a-8abb-7ddd77a8a7d8',
            version='5.1')
        return self._deserialize('[Process]',
                                 self._unwrap_collection(response))

    def get_project_collection(self, collection_id):
        """GetProjectCollection.
        Get project collection with the specified id or name.
        :param str collection_id:
        :rtype: :class:`<TeamProjectCollection> <azure.devops.v5_1.core.models.TeamProjectCollection>`
        """
        route_values = {}
        if collection_id is not None:
            route_values['collectionId'] = self._serialize.url(
                'collection_id', collection_id, 'str')
        response = self._send(
            http_method='GET',
            location_id='8031090f-ef1d-4af6-85fc-698cd75d42bf',
            version='5.1',
            route_values=route_values)
        return self._deserialize('TeamProjectCollection', response)

    def get_project_collections(self, top=None, skip=None):
        """GetProjectCollections.
        Get project collection references for this application.
        :param int top:
        :param int skip:
        :rtype: [TeamProjectCollectionReference]
        """
        query_parameters = {}
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        if skip is not None:
            query_parameters['$skip'] = self._serialize.query(
                'skip', skip, 'int')
        response = self._send(
            http_method='GET',
            location_id='8031090f-ef1d-4af6-85fc-698cd75d42bf',
            version='5.1',
            query_parameters=query_parameters)
        return self._deserialize('[TeamProjectCollectionReference]',
                                 self._unwrap_collection(response))

    def get_project(self,
                    project_id,
                    include_capabilities=None,
                    include_history=None):
        """GetProject.
        Get project with the specified id or name, optionally including capabilities.
        :param str project_id:
        :param bool include_capabilities: Include capabilities (such as source control) in the team project result (default: false).
        :param bool include_history: Search within renamed projects (that had such name in the past).
        :rtype: :class:`<TeamProject> <azure.devops.v5_1.core.models.TeamProject>`
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        query_parameters = {}
        if include_capabilities is not None:
            query_parameters['includeCapabilities'] = self._serialize.query(
                'include_capabilities', include_capabilities, 'bool')
        if include_history is not None:
            query_parameters['includeHistory'] = self._serialize.query(
                'include_history', include_history, 'bool')
        response = self._send(
            http_method='GET',
            location_id='603fe2ac-9723-48b9-88ad-09305aa6c6e1',
            version='5.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('TeamProject', response)

    def get_projects(self,
                     state_filter=None,
                     top=None,
                     skip=None,
                     continuation_token=None,
                     get_default_team_image_url=None):
        """GetProjects.
        Get all projects in the organization that the authenticated user has access to.
        :param str state_filter: Filter on team projects in a specific team project state (default: WellFormed).
        :param int top:
        :param int skip:
        :param str continuation_token:
        :param bool get_default_team_image_url:
        :rtype: :class:`<GetProjectsResponseValue>`
        """
        query_parameters = {}
        if state_filter is not None:
            query_parameters['stateFilter'] = self._serialize.query(
                'state_filter', state_filter, 'str')
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        if skip is not None:
            query_parameters['$skip'] = self._serialize.query(
                'skip', skip, 'int')
        if continuation_token is not None:
            query_parameters['continuationToken'] = self._serialize.query(
                'continuation_token', continuation_token, 'str')
        if get_default_team_image_url is not None:
            query_parameters['getDefaultTeamImageUrl'] = self._serialize.query(
                'get_default_team_image_url', get_default_team_image_url,
                'bool')
        response = self._send(
            http_method='GET',
            location_id='603fe2ac-9723-48b9-88ad-09305aa6c6e1',
            version='5.1',
            query_parameters=query_parameters)
        response_value = self._deserialize('[TeamProjectReference]',
                                           self._unwrap_collection(response))
        continuation_token = self._get_continuation_token(response)
        return self.GetProjectsResponseValue(response_value,
                                             continuation_token)

    class GetProjectsResponseValue(object):
        def __init__(self, value, continuation_token):
            """
            Response for the get_projects method

            :param value:
            :type value: :class:`<[TeamProjectReference]> <azure.devops.v5_1.core.models.[TeamProjectReference]>`
            :param continuation_token: The continuation token to be used to get the next page of results.
            :type continuation_token: str
            """
            self.value = value
            self.continuation_token = continuation_token

    def queue_create_project(self, project_to_create):
        """QueueCreateProject.
        Queues a project to be created. Use the [GetOperation](../../operations/operations/get) to periodically check for create project status.
        :param :class:`<TeamProject> <azure.devops.v5_1.core.models.TeamProject>` project_to_create: The project to create.
        :rtype: :class:`<OperationReference> <azure.devops.v5_1.core.models.OperationReference>`
        """
        content = self._serialize.body(project_to_create, 'TeamProject')
        response = self._send(
            http_method='POST',
            location_id='603fe2ac-9723-48b9-88ad-09305aa6c6e1',
            version='5.1',
            content=content)
        return self._deserialize('OperationReference', response)

    def queue_delete_project(self, project_id):
        """QueueDeleteProject.
        Queues a project to be deleted. Use the [GetOperation](../../operations/operations/get) to periodically check for delete project status.
        :param str project_id: The project id of the project to delete.
        :rtype: :class:`<OperationReference> <azure.devops.v5_1.core.models.OperationReference>`
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        response = self._send(
            http_method='DELETE',
            location_id='603fe2ac-9723-48b9-88ad-09305aa6c6e1',
            version='5.1',
            route_values=route_values)
        return self._deserialize('OperationReference', response)

    def update_project(self, project_update, project_id):
        """UpdateProject.
        Update an existing project's name, abbreviation, description, or restore a project.
        :param :class:`<TeamProject> <azure.devops.v5_1.core.models.TeamProject>` project_update: The updates for the project. The state must be set to wellFormed to restore the project.
        :param str project_id: The project id of the project to update.
        :rtype: :class:`<OperationReference> <azure.devops.v5_1.core.models.OperationReference>`
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        content = self._serialize.body(project_update, 'TeamProject')
        response = self._send(
            http_method='PATCH',
            location_id='603fe2ac-9723-48b9-88ad-09305aa6c6e1',
            version='5.1',
            route_values=route_values,
            content=content)
        return self._deserialize('OperationReference', response)

    def get_project_properties(self, project_id, keys=None):
        """GetProjectProperties.
        [Preview API] Get a collection of team project properties.
        :param str project_id: The team project ID.
        :param [str] keys: A comma-delimited string of team project property names. Wildcard characters ("?" and "*") are supported. If no key is specified, all properties will be returned.
        :rtype: [ProjectProperty]
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        query_parameters = {}
        if keys is not None:
            keys = ",".join(keys)
            query_parameters['keys'] = self._serialize.query(
                'keys', keys, 'str')
        response = self._send(
            http_method='GET',
            location_id='4976a71a-4487-49aa-8aab-a1eda469037a',
            version='5.1-preview.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[ProjectProperty]',
                                 self._unwrap_collection(response))

    def set_project_properties(self, project_id, patch_document):
        """SetProjectProperties.
        [Preview API] Create, update, and delete team project properties.
        :param str project_id: The team project ID.
        :param :class:`<[JsonPatchOperation]> <azure.devops.v5_1.core.models.[JsonPatchOperation]>` patch_document: A JSON Patch document that represents an array of property operations. See RFC 6902 for more details on JSON Patch. The accepted operation verbs are Add and Remove, where Add is used for both creating and updating properties. The path consists of a forward slash and a property name.
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        content = self._serialize.body(patch_document, '[JsonPatchOperation]')
        self._send(http_method='PATCH',
                   location_id='4976a71a-4487-49aa-8aab-a1eda469037a',
                   version='5.1-preview.1',
                   route_values=route_values,
                   content=content,
                   media_type='application/json-patch+json')

    def create_or_update_proxy(self, proxy):
        """CreateOrUpdateProxy.
        [Preview API]
        :param :class:`<Proxy> <azure.devops.v5_1.core.models.Proxy>` proxy:
        :rtype: :class:`<Proxy> <azure.devops.v5_1.core.models.Proxy>`
        """
        content = self._serialize.body(proxy, 'Proxy')
        response = self._send(
            http_method='PUT',
            location_id='ec1f4311-f2b4-4c15-b2b8-8990b80d2908',
            version='5.1-preview.2',
            content=content)
        return self._deserialize('Proxy', response)

    def delete_proxy(self, proxy_url, site=None):
        """DeleteProxy.
        [Preview API]
        :param str proxy_url:
        :param str site:
        """
        query_parameters = {}
        if proxy_url is not None:
            query_parameters['proxyUrl'] = self._serialize.query(
                'proxy_url', proxy_url, 'str')
        if site is not None:
            query_parameters['site'] = self._serialize.query(
                'site', site, 'str')
        self._send(http_method='DELETE',
                   location_id='ec1f4311-f2b4-4c15-b2b8-8990b80d2908',
                   version='5.1-preview.2',
                   query_parameters=query_parameters)

    def get_proxies(self, proxy_url=None):
        """GetProxies.
        [Preview API]
        :param str proxy_url:
        :rtype: [Proxy]
        """
        query_parameters = {}
        if proxy_url is not None:
            query_parameters['proxyUrl'] = self._serialize.query(
                'proxy_url', proxy_url, 'str')
        response = self._send(
            http_method='GET',
            location_id='ec1f4311-f2b4-4c15-b2b8-8990b80d2908',
            version='5.1-preview.2',
            query_parameters=query_parameters)
        return self._deserialize('[Proxy]', self._unwrap_collection(response))

    def create_team(self, team, project_id):
        """CreateTeam.
        Create a team in a team project.
        :param :class:`<WebApiTeam> <azure.devops.v5_1.core.models.WebApiTeam>` team: The team data used to create the team.
        :param str project_id: The name or ID (GUID) of the team project in which to create the team.
        :rtype: :class:`<WebApiTeam> <azure.devops.v5_1.core.models.WebApiTeam>`
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        content = self._serialize.body(team, 'WebApiTeam')
        response = self._send(
            http_method='POST',
            location_id='d30a3dd1-f8ba-442a-b86a-bd0c0c383e59',
            version='5.1',
            route_values=route_values,
            content=content)
        return self._deserialize('WebApiTeam', response)

    def delete_team(self, project_id, team_id):
        """DeleteTeam.
        Delete a team.
        :param str project_id: The name or ID (GUID) of the team project containing the team to delete.
        :param str team_id: The name or ID of the team to delete.
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        if team_id is not None:
            route_values['teamId'] = self._serialize.url(
                'team_id', team_id, 'str')
        self._send(http_method='DELETE',
                   location_id='d30a3dd1-f8ba-442a-b86a-bd0c0c383e59',
                   version='5.1',
                   route_values=route_values)

    def get_team(self, project_id, team_id, expand_identity=None):
        """GetTeam.
        Get a specific team.
        :param str project_id: The name or ID (GUID) of the team project containing the team.
        :param str team_id: The name or ID (GUID) of the team.
        :param bool expand_identity: A value indicating whether or not to expand Identity information in the result WebApiTeam object.
        :rtype: :class:`<WebApiTeam> <azure.devops.v5_1.core.models.WebApiTeam>`
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        if team_id is not None:
            route_values['teamId'] = self._serialize.url(
                'team_id', team_id, 'str')
        query_parameters = {}
        if expand_identity is not None:
            query_parameters['$expandIdentity'] = self._serialize.query(
                'expand_identity', expand_identity, 'bool')
        response = self._send(
            http_method='GET',
            location_id='d30a3dd1-f8ba-442a-b86a-bd0c0c383e59',
            version='5.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('WebApiTeam', response)

    def get_teams(self,
                  project_id,
                  mine=None,
                  top=None,
                  skip=None,
                  expand_identity=None):
        """GetTeams.
        Get a list of teams.
        :param str project_id:
        :param bool mine: If true return all the teams requesting user is member, otherwise return all the teams user has read access.
        :param int top: Maximum number of teams to return.
        :param int skip: Number of teams to skip.
        :param bool expand_identity: A value indicating whether or not to expand Identity information in the result WebApiTeam object.
        :rtype: [WebApiTeam]
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        query_parameters = {}
        if mine is not None:
            query_parameters['$mine'] = self._serialize.query(
                'mine', mine, 'bool')
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        if skip is not None:
            query_parameters['$skip'] = self._serialize.query(
                'skip', skip, 'int')
        if expand_identity is not None:
            query_parameters['$expandIdentity'] = self._serialize.query(
                'expand_identity', expand_identity, 'bool')
        response = self._send(
            http_method='GET',
            location_id='d30a3dd1-f8ba-442a-b86a-bd0c0c383e59',
            version='5.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[WebApiTeam]',
                                 self._unwrap_collection(response))

    def update_team(self, team_data, project_id, team_id):
        """UpdateTeam.
        Update a team's name and/or description.
        :param :class:`<WebApiTeam> <azure.devops.v5_1.core.models.WebApiTeam>` team_data:
        :param str project_id: The name or ID (GUID) of the team project containing the team to update.
        :param str team_id: The name of ID of the team to update.
        :rtype: :class:`<WebApiTeam> <azure.devops.v5_1.core.models.WebApiTeam>`
        """
        route_values = {}
        if project_id is not None:
            route_values['projectId'] = self._serialize.url(
                'project_id', project_id, 'str')
        if team_id is not None:
            route_values['teamId'] = self._serialize.url(
                'team_id', team_id, 'str')
        content = self._serialize.body(team_data, 'WebApiTeam')
        response = self._send(
            http_method='PATCH',
            location_id='d30a3dd1-f8ba-442a-b86a-bd0c0c383e59',
            version='5.1',
            route_values=route_values,
            content=content)
        return self._deserialize('WebApiTeam', response)

    def get_all_teams(self,
                      mine=None,
                      top=None,
                      skip=None,
                      expand_identity=None):
        """GetAllTeams.
        [Preview API] Get a list of all teams.
        :param bool mine: If true, then return all teams requesting user is member. Otherwise return all teams user has read access.
        :param int top: Maximum number of teams to return.
        :param int skip: Number of teams to skip.
        :param bool expand_identity: A value indicating whether or not to expand Identity information in the result WebApiTeam object.
        :rtype: [WebApiTeam]
        """
        query_parameters = {}
        if mine is not None:
            query_parameters['$mine'] = self._serialize.query(
                'mine', mine, 'bool')
        if top is not None:
            query_parameters['$top'] = self._serialize.query('top', top, 'int')
        if skip is not None:
            query_parameters['$skip'] = self._serialize.query(
                'skip', skip, 'int')
        if expand_identity is not None:
            query_parameters['$expandIdentity'] = self._serialize.query(
                'expand_identity', expand_identity, 'bool')
        response = self._send(
            http_method='GET',
            location_id='7a4d9ee9-3433-4347-b47a-7a80f1cf307e',
            version='5.1-preview.3',
            query_parameters=query_parameters)
        return self._deserialize('[WebApiTeam]',
                                 self._unwrap_collection(response))
Ejemplo n.º 35
0
class AzureOpcTwinClient(object):
    """Azure Industrial IoT OPC UA Twin Service

    :ivar config: Configuration for client.
    :vartype config: AzureOpcTwinClientConfiguration

    :param credentials: Subscription credentials which uniquely identify
     client subscription.
    :type credentials: None
    :param str base_url: Service URL
    """

    def __init__(
            self, credentials, base_url=None):

        self.config = AzureOpcTwinClientConfiguration(credentials, base_url)
        self._client = ServiceClient(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self.api_version = 'v2'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)


    def browse(
            self, endpoint_id, body, custom_headers=None, raw=False, **operation_config):
        """Browse node references.

        Browse a node on the specified endpoint. The endpoint must be activated
        and connected and the module client and server must trust each other.

        :param endpoint_id: The identifier of the activated endpoint.
        :type endpoint_id: str
        :param body: The browse request
        :type body: ~azure-iiot-opc-twin.models.BrowseRequestApiModel
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: BrowseResponseApiModel or ClientRawResponse if raw=true
        :rtype: ~azure-iiot-opc-twin.models.BrowseResponseApiModel or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.browse.metadata['url']
        path_format_arguments = {
            'endpointId': self._serialize.url("endpoint_id", endpoint_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json-patch+json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, 'BrowseRequestApiModel')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('BrowseResponseApiModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    browse.metadata = {'url': '/v2/browse/{endpointId}'}

    def get_set_of_unique_nodes(
            self, endpoint_id, node_id=None, custom_headers=None, raw=False, **operation_config):
        """Browse set of unique target nodes.

        Browse the set of unique hierarchically referenced target nodes on the
        endpoint. The endpoint must be activated and connected and the module
        client and server must trust each other. The root node id to browse
        from can be provided as part of the query parameters. If it is not
        provided, the RootFolder node is browsed. Note that this is the same as
        the POST method with the model containing the node id and the
        targetNodesOnly flag set to true.

        :param endpoint_id: The identifier of the activated endpoint.
        :type endpoint_id: str
        :param node_id: The node to browse or omit to browse the root node
         (i=84)
        :type node_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: BrowseResponseApiModel or ClientRawResponse if raw=true
        :rtype: ~azure-iiot-opc-twin.models.BrowseResponseApiModel or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.get_set_of_unique_nodes.metadata['url']
        path_format_arguments = {
            'endpointId': self._serialize.url("endpoint_id", endpoint_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if node_id is not None:
            query_parameters['nodeId'] = self._serialize.query("node_id", node_id, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('BrowseResponseApiModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get_set_of_unique_nodes.metadata = {'url': '/v2/browse/{endpointId}'}

    def browse_next(
            self, endpoint_id, body, custom_headers=None, raw=False, **operation_config):
        """Browse next set of references.

        Browse next set of references on the endpoint. The endpoint must be
        activated and connected and the module client and server must trust
        each other.

        :param endpoint_id: The identifier of the activated endpoint.
        :type endpoint_id: str
        :param body: The request body with continuation token.
        :type body: ~azure-iiot-opc-twin.models.BrowseNextRequestApiModel
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: BrowseNextResponseApiModel or ClientRawResponse if raw=true
        :rtype: ~azure-iiot-opc-twin.models.BrowseNextResponseApiModel or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.browse_next.metadata['url']
        path_format_arguments = {
            'endpointId': self._serialize.url("endpoint_id", endpoint_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json-patch+json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, 'BrowseNextRequestApiModel')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('BrowseNextResponseApiModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    browse_next.metadata = {'url': '/v2/browse/{endpointId}/next'}

    def get_next_set_of_unique_nodes(
            self, endpoint_id, continuation_token, custom_headers=None, raw=False, **operation_config):
        """Browse next set of unique target nodes.

        Browse the next set of unique hierarchically referenced target nodes on
        the endpoint. The endpoint must be activated and connected and the
        module client and server must trust each other. Note that this is the
        same as the POST method with the model containing the continuation
        token and the targetNodesOnly flag set to true.

        :param endpoint_id: The identifier of the activated endpoint.
        :type endpoint_id: str
        :param continuation_token: Continuation token from GetSetOfUniqueNodes
         operation
        :type continuation_token: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: BrowseNextResponseApiModel or ClientRawResponse if raw=true
        :rtype: ~azure-iiot-opc-twin.models.BrowseNextResponseApiModel or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.get_next_set_of_unique_nodes.metadata['url']
        path_format_arguments = {
            'endpointId': self._serialize.url("endpoint_id", endpoint_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['continuationToken'] = self._serialize.query("continuation_token", continuation_token, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('BrowseNextResponseApiModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get_next_set_of_unique_nodes.metadata = {'url': '/v2/browse/{endpointId}/next'}

    def browse_using_path(
            self, endpoint_id, body, custom_headers=None, raw=False, **operation_config):
        """Browse using a browse path.

        Browse using a path from the specified node id. This call uses
        TranslateBrowsePathsToNodeIds service under the hood. The endpoint must
        be activated and connected and the module client and server must trust
        each other.

        :param endpoint_id: The identifier of the activated endpoint.
        :type endpoint_id: str
        :param body: The browse path request
        :type body: ~azure-iiot-opc-twin.models.BrowsePathRequestApiModel
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: BrowsePathResponseApiModel or ClientRawResponse if raw=true
        :rtype: ~azure-iiot-opc-twin.models.BrowsePathResponseApiModel or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.browse_using_path.metadata['url']
        path_format_arguments = {
            'endpointId': self._serialize.url("endpoint_id", endpoint_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json-patch+json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, 'BrowsePathRequestApiModel')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('BrowsePathResponseApiModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    browse_using_path.metadata = {'url': '/v2/browse/{endpointId}/path'}

    def get_call_metadata(
            self, endpoint_id, body, custom_headers=None, raw=False, **operation_config):
        """Get method meta data.

        Return method meta data to support a user interface displaying forms to
        input and output arguments. The endpoint must be activated and
        connected and the module client and server must trust each other.

        :param endpoint_id: The identifier of the activated endpoint.
        :type endpoint_id: str
        :param body: The method metadata request
        :type body: ~azure-iiot-opc-twin.models.MethodMetadataRequestApiModel
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: MethodMetadataResponseApiModel or ClientRawResponse if
         raw=true
        :rtype: ~azure-iiot-opc-twin.models.MethodMetadataResponseApiModel or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.get_call_metadata.metadata['url']
        path_format_arguments = {
            'endpointId': self._serialize.url("endpoint_id", endpoint_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json-patch+json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, 'MethodMetadataRequestApiModel')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('MethodMetadataResponseApiModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get_call_metadata.metadata = {'url': '/v2/call/{endpointId}/metadata'}

    def call_method(
            self, endpoint_id, body, custom_headers=None, raw=False, **operation_config):
        """Call a method.

        Invoke method node with specified input arguments. The endpoint must be
        activated and connected and the module client and server must trust
        each other.

        :param endpoint_id: The identifier of the activated endpoint.
        :type endpoint_id: str
        :param body: The method call request
        :type body: ~azure-iiot-opc-twin.models.MethodCallRequestApiModel
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: MethodCallResponseApiModel or ClientRawResponse if raw=true
        :rtype: ~azure-iiot-opc-twin.models.MethodCallResponseApiModel or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.call_method.metadata['url']
        path_format_arguments = {
            'endpointId': self._serialize.url("endpoint_id", endpoint_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json-patch+json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, 'MethodCallRequestApiModel')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('MethodCallResponseApiModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    call_method.metadata = {'url': '/v2/call/{endpointId}'}

    def read_value(
            self, endpoint_id, body, custom_headers=None, raw=False, **operation_config):
        """Read variable value.

        Read a variable node's value. The endpoint must be activated and
        connected and the module client and server must trust each other.

        :param endpoint_id: The identifier of the activated endpoint.
        :type endpoint_id: str
        :param body: The read value request
        :type body: ~azure-iiot-opc-twin.models.ValueReadRequestApiModel
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ValueReadResponseApiModel or ClientRawResponse if raw=true
        :rtype: ~azure-iiot-opc-twin.models.ValueReadResponseApiModel or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.read_value.metadata['url']
        path_format_arguments = {
            'endpointId': self._serialize.url("endpoint_id", endpoint_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json-patch+json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, 'ValueReadRequestApiModel')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ValueReadResponseApiModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    read_value.metadata = {'url': '/v2/read/{endpointId}'}

    def get_value(
            self, endpoint_id, node_id, custom_headers=None, raw=False, **operation_config):
        """Get variable value.

        Get a variable node's value using its node id. The endpoint must be
        activated and connected and the module client and server must trust
        each other.

        :param endpoint_id: The identifier of the activated endpoint.
        :type endpoint_id: str
        :param node_id: The node to read
        :type node_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ValueReadResponseApiModel or ClientRawResponse if raw=true
        :rtype: ~azure-iiot-opc-twin.models.ValueReadResponseApiModel or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.get_value.metadata['url']
        path_format_arguments = {
            'endpointId': self._serialize.url("endpoint_id", endpoint_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['nodeId'] = self._serialize.query("node_id", node_id, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ValueReadResponseApiModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get_value.metadata = {'url': '/v2/read/{endpointId}'}

    def read_attributes(
            self, endpoint_id, body, custom_headers=None, raw=False, **operation_config):
        """Read node attributes.

        Read attributes of a node. The endpoint must be activated and connected
        and the module client and server must trust each other.

        :param endpoint_id: The identifier of the activated endpoint.
        :type endpoint_id: str
        :param body: The read request
        :type body: ~azure-iiot-opc-twin.models.ReadRequestApiModel
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ReadResponseApiModel or ClientRawResponse if raw=true
        :rtype: ~azure-iiot-opc-twin.models.ReadResponseApiModel or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.read_attributes.metadata['url']
        path_format_arguments = {
            'endpointId': self._serialize.url("endpoint_id", endpoint_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json-patch+json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, 'ReadRequestApiModel')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ReadResponseApiModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    read_attributes.metadata = {'url': '/v2/read/{endpointId}/attributes'}

    def write_value(
            self, endpoint_id, body, custom_headers=None, raw=False, **operation_config):
        """Write variable value.

        Write variable node's value. The endpoint must be activated and
        connected and the module client and server must trust each other.

        :param endpoint_id: The identifier of the activated endpoint.
        :type endpoint_id: str
        :param body: The write value request
        :type body: ~azure-iiot-opc-twin.models.ValueWriteRequestApiModel
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ValueWriteResponseApiModel or ClientRawResponse if raw=true
        :rtype: ~azure-iiot-opc-twin.models.ValueWriteResponseApiModel or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.write_value.metadata['url']
        path_format_arguments = {
            'endpointId': self._serialize.url("endpoint_id", endpoint_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json-patch+json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, 'ValueWriteRequestApiModel')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ValueWriteResponseApiModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    write_value.metadata = {'url': '/v2/write/{endpointId}'}

    def write_attributes(
            self, endpoint_id, body, custom_headers=None, raw=False, **operation_config):
        """Write node attributes.

        Write any attribute of a node. The endpoint must be activated and
        connected and the module client and server must trust each other.

        :param endpoint_id: The identifier of the activated endpoint.
        :type endpoint_id: str
        :param body: The batch write request
        :type body: ~azure-iiot-opc-twin.models.WriteRequestApiModel
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: WriteResponseApiModel or ClientRawResponse if raw=true
        :rtype: ~azure-iiot-opc-twin.models.WriteResponseApiModel or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = self.write_attributes.metadata['url']
        path_format_arguments = {
            'endpointId': self._serialize.url("endpoint_id", endpoint_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json-patch+json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, 'WriteRequestApiModel')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('WriteResponseApiModel', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    write_attributes.metadata = {'url': '/v2/write/{endpointId}/attributes'}
Ejemplo n.º 36
0
class SettingsClient(VssClient):
    """Settings
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """

    def __init__(self, base_url=None, creds=None):
        super(SettingsClient, self).__init__(base_url, creds)
        self._serialize = Serializer()
        self._deserialize = Deserializer()

    resource_area_identifier = None

    def get_entries(self, user_scope, key=None):
        """GetEntries.
        [Preview API] Get all setting entries for the given user/all-users scope
        :param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
        :param str key: Optional key under which to filter all the entries
        :rtype: {object}
        """
        route_values = {}
        if user_scope is not None:
            route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
        if key is not None:
            route_values['key'] = self._serialize.url('key', key, 'str')
        response = self._send(http_method='GET',
                              location_id='cd006711-163d-4cd4-a597-b05bad2556ff',
                              version='4.1-preview.1',
                              route_values=route_values)
        return self._deserialize('{object}', self._unwrap_collection(response))

    def remove_entries(self, user_scope, key):
        """RemoveEntries.
        [Preview API] Remove the entry or entries under the specified path
        :param str user_scope: User-Scope at which to remove the value. Should be "me" for the current user or "host" for all users.
        :param str key: Root key of the entry or entries to remove
        """
        route_values = {}
        if user_scope is not None:
            route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
        if key is not None:
            route_values['key'] = self._serialize.url('key', key, 'str')
        self._send(http_method='DELETE',
                   location_id='cd006711-163d-4cd4-a597-b05bad2556ff',
                   version='4.1-preview.1',
                   route_values=route_values)

    def set_entries(self, entries, user_scope):
        """SetEntries.
        [Preview API] Set the specified setting entry values for the given user/all-users scope
        :param {object} entries: The entries to set
        :param str user_scope: User-Scope at which to set the values. Should be "me" for the current user or "host" for all users.
        """
        route_values = {}
        if user_scope is not None:
            route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
        content = self._serialize.body(entries, '{object}')
        self._send(http_method='PATCH',
                   location_id='cd006711-163d-4cd4-a597-b05bad2556ff',
                   version='4.1-preview.1',
                   route_values=route_values,
                   content=content)

    def get_entries_for_scope(self, user_scope, scope_name, scope_value, key=None):
        """GetEntriesForScope.
        [Preview API] Get all setting entries for the given named scope
        :param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
        :param str scope_name: Scope at which to get the setting for (e.g. "project" or "team")
        :param str scope_value: Value of the scope (e.g. the project or team id)
        :param str key: Optional key under which to filter all the entries
        :rtype: {object}
        """
        route_values = {}
        if user_scope is not None:
            route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
        if scope_name is not None:
            route_values['scopeName'] = self._serialize.url('scope_name', scope_name, 'str')
        if scope_value is not None:
            route_values['scopeValue'] = self._serialize.url('scope_value', scope_value, 'str')
        if key is not None:
            route_values['key'] = self._serialize.url('key', key, 'str')
        response = self._send(http_method='GET',
                              location_id='4cbaafaf-e8af-4570-98d1-79ee99c56327',
                              version='4.1-preview.1',
                              route_values=route_values)
        return self._deserialize('{object}', self._unwrap_collection(response))

    def remove_entries_for_scope(self, user_scope, scope_name, scope_value, key):
        """RemoveEntriesForScope.
        [Preview API] Remove the entry or entries under the specified path
        :param str user_scope: User-Scope at which to remove the value. Should be "me" for the current user or "host" for all users.
        :param str scope_name: Scope at which to get the setting for (e.g. "project" or "team")
        :param str scope_value: Value of the scope (e.g. the project or team id)
        :param str key: Root key of the entry or entries to remove
        """
        route_values = {}
        if user_scope is not None:
            route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
        if scope_name is not None:
            route_values['scopeName'] = self._serialize.url('scope_name', scope_name, 'str')
        if scope_value is not None:
            route_values['scopeValue'] = self._serialize.url('scope_value', scope_value, 'str')
        if key is not None:
            route_values['key'] = self._serialize.url('key', key, 'str')
        self._send(http_method='DELETE',
                   location_id='4cbaafaf-e8af-4570-98d1-79ee99c56327',
                   version='4.1-preview.1',
                   route_values=route_values)

    def set_entries_for_scope(self, entries, user_scope, scope_name, scope_value):
        """SetEntriesForScope.
        [Preview API] Set the specified entries for the given named scope
        :param {object} entries: The entries to set
        :param str user_scope: User-Scope at which to set the values. Should be "me" for the current user or "host" for all users.
        :param str scope_name: Scope at which to set the settings on (e.g. "project" or "team")
        :param str scope_value: Value of the scope (e.g. the project or team id)
        """
        route_values = {}
        if user_scope is not None:
            route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
        if scope_name is not None:
            route_values['scopeName'] = self._serialize.url('scope_name', scope_name, 'str')
        if scope_value is not None:
            route_values['scopeValue'] = self._serialize.url('scope_value', scope_value, 'str')
        content = self._serialize.body(entries, '{object}')
        self._send(http_method='PATCH',
                   location_id='4cbaafaf-e8af-4570-98d1-79ee99c56327',
                   version='4.1-preview.1',
                   route_values=route_values,
                   content=content)
Ejemplo n.º 37
0
class CustomVisionPredictionClient(SDKClient):
    """CustomVisionPredictionClient

    :ivar config: Configuration for client.
    :vartype config: CustomVisionPredictionClientConfiguration

    :param api_key: API key.
    :type api_key: str
    :param endpoint: Supported Cognitive Services endpoints.
    :type endpoint: str
    """

    def __init__(
            self, api_key, endpoint):

        self.config = CustomVisionPredictionClientConfiguration(api_key, endpoint)
        super(CustomVisionPredictionClient, self).__init__(None, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self.api_version = '3.0'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)


    def classify_image_url(
            self, project_id, published_name, url, application=None, custom_headers=None, raw=False, **operation_config):
        """Classify an image url and saves the result.

        :param project_id: The project id.
        :type project_id: str
        :param published_name: Specifies the name of the model to evaluate
         against.
        :type published_name: str
        :param url: Url of the image.
        :type url: str
        :param application: Optional. Specifies the name of application using
         the endpoint.
        :type application: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ImagePrediction or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.vision.customvision.prediction.models.ImagePrediction
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`CustomVisionErrorException<azure.cognitiveservices.vision.customvision.prediction.models.CustomVisionErrorException>`
        """
        image_url = models.ImageUrl(url=url)

        # Construct URL
        url = self.classify_image_url.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'projectId': self._serialize.url("project_id", project_id, 'str'),
            'publishedName': self._serialize.url("published_name", published_name, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if application is not None:
            query_parameters['application'] = self._serialize.query("application", application, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['Prediction-Key'] = self._serialize.header("self.config.api_key", self.config.api_key, 'str')

        # Construct body
        body_content = self._serialize.body(image_url, 'ImageUrl')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.CustomVisionErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ImagePrediction', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    classify_image_url.metadata = {'url': '/{projectId}/classify/iterations/{publishedName}/url'}

    def classify_image(
            self, project_id, published_name, image_data, application=None, custom_headers=None, raw=False, **operation_config):
        """Classify an image and saves the result.

        :param project_id: The project id.
        :type project_id: str
        :param published_name: Specifies the name of the model to evaluate
         against.
        :type published_name: str
        :param image_data: Binary image data. Supported formats are JPEG, GIF,
         PNG, and BMP. Supports images up to 4MB.
        :type image_data: Generator
        :param application: Optional. Specifies the name of application using
         the endpoint.
        :type application: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ImagePrediction or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.vision.customvision.prediction.models.ImagePrediction
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`CustomVisionErrorException<azure.cognitiveservices.vision.customvision.prediction.models.CustomVisionErrorException>`
        """
        # Construct URL
        url = self.classify_image.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'projectId': self._serialize.url("project_id", project_id, 'str'),
            'publishedName': self._serialize.url("published_name", published_name, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if application is not None:
            query_parameters['application'] = self._serialize.query("application", application, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'multipart/form-data'
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['Prediction-Key'] = self._serialize.header("self.config.api_key", self.config.api_key, 'str')

        # Construct form data
        form_data_content = {
            'imageData': image_data,
        }

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, form_content=form_data_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.CustomVisionErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ImagePrediction', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    classify_image.metadata = {'url': '/{projectId}/classify/iterations/{publishedName}/image'}

    def classify_image_url_with_no_store(
            self, project_id, published_name, url, application=None, custom_headers=None, raw=False, **operation_config):
        """Classify an image url without saving the result.

        :param project_id: The project id.
        :type project_id: str
        :param published_name: Specifies the name of the model to evaluate
         against.
        :type published_name: str
        :param url: Url of the image.
        :type url: str
        :param application: Optional. Specifies the name of application using
         the endpoint.
        :type application: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ImagePrediction or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.vision.customvision.prediction.models.ImagePrediction
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`CustomVisionErrorException<azure.cognitiveservices.vision.customvision.prediction.models.CustomVisionErrorException>`
        """
        image_url = models.ImageUrl(url=url)

        # Construct URL
        url = self.classify_image_url_with_no_store.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'projectId': self._serialize.url("project_id", project_id, 'str'),
            'publishedName': self._serialize.url("published_name", published_name, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if application is not None:
            query_parameters['application'] = self._serialize.query("application", application, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['Prediction-Key'] = self._serialize.header("self.config.api_key", self.config.api_key, 'str')

        # Construct body
        body_content = self._serialize.body(image_url, 'ImageUrl')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.CustomVisionErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ImagePrediction', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    classify_image_url_with_no_store.metadata = {'url': '/{projectId}/classify/iterations/{publishedName}/url/nostore'}

    def classify_image_with_no_store(
            self, project_id, published_name, image_data, application=None, custom_headers=None, raw=False, **operation_config):
        """Classify an image without saving the result.

        :param project_id: The project id.
        :type project_id: str
        :param published_name: Specifies the name of the model to evaluate
         against.
        :type published_name: str
        :param image_data: Binary image data. Supported formats are JPEG, GIF,
         PNG, and BMP. Supports images up to 0MB.
        :type image_data: Generator
        :param application: Optional. Specifies the name of application using
         the endpoint.
        :type application: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ImagePrediction or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.vision.customvision.prediction.models.ImagePrediction
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`CustomVisionErrorException<azure.cognitiveservices.vision.customvision.prediction.models.CustomVisionErrorException>`
        """
        # Construct URL
        url = self.classify_image_with_no_store.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'projectId': self._serialize.url("project_id", project_id, 'str'),
            'publishedName': self._serialize.url("published_name", published_name, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if application is not None:
            query_parameters['application'] = self._serialize.query("application", application, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'multipart/form-data'
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['Prediction-Key'] = self._serialize.header("self.config.api_key", self.config.api_key, 'str')

        # Construct form data
        form_data_content = {
            'imageData': image_data,
        }

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, form_content=form_data_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.CustomVisionErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ImagePrediction', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    classify_image_with_no_store.metadata = {'url': '/{projectId}/classify/iterations/{publishedName}/image/nostore'}

    def detect_image_url(
            self, project_id, published_name, url, application=None, custom_headers=None, raw=False, **operation_config):
        """Detect objects in an image url and saves the result.

        :param project_id: The project id.
        :type project_id: str
        :param published_name: Specifies the name of the model to evaluate
         against.
        :type published_name: str
        :param url: Url of the image.
        :type url: str
        :param application: Optional. Specifies the name of application using
         the endpoint.
        :type application: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ImagePrediction or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.vision.customvision.prediction.models.ImagePrediction
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`CustomVisionErrorException<azure.cognitiveservices.vision.customvision.prediction.models.CustomVisionErrorException>`
        """
        image_url = models.ImageUrl(url=url)

        # Construct URL
        url = self.detect_image_url.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'projectId': self._serialize.url("project_id", project_id, 'str'),
            'publishedName': self._serialize.url("published_name", published_name, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if application is not None:
            query_parameters['application'] = self._serialize.query("application", application, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['Prediction-Key'] = self._serialize.header("self.config.api_key", self.config.api_key, 'str')

        # Construct body
        body_content = self._serialize.body(image_url, 'ImageUrl')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.CustomVisionErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ImagePrediction', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    detect_image_url.metadata = {'url': '/{projectId}/detect/iterations/{publishedName}/url'}

    def detect_image(
            self, project_id, published_name, image_data, application=None, custom_headers=None, raw=False, **operation_config):
        """Detect objects in an image and saves the result.

        :param project_id: The project id.
        :type project_id: str
        :param published_name: Specifies the name of the model to evaluate
         against.
        :type published_name: str
        :param image_data: Binary image data. Supported formats are JPEG, GIF,
         PNG, and BMP. Supports images up to 4MB.
        :type image_data: Generator
        :param application: Optional. Specifies the name of application using
         the endpoint.
        :type application: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ImagePrediction or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.vision.customvision.prediction.models.ImagePrediction
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`CustomVisionErrorException<azure.cognitiveservices.vision.customvision.prediction.models.CustomVisionErrorException>`
        """
        # Construct URL
        url = self.detect_image.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'projectId': self._serialize.url("project_id", project_id, 'str'),
            'publishedName': self._serialize.url("published_name", published_name, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if application is not None:
            query_parameters['application'] = self._serialize.query("application", application, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'multipart/form-data'
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['Prediction-Key'] = self._serialize.header("self.config.api_key", self.config.api_key, 'str')

        # Construct form data
        form_data_content = {
            'imageData': image_data,
        }

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, form_content=form_data_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.CustomVisionErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ImagePrediction', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    detect_image.metadata = {'url': '/{projectId}/detect/iterations/{publishedName}/image'}

    def detect_image_url_with_no_store(
            self, project_id, published_name, url, application=None, custom_headers=None, raw=False, **operation_config):
        """Detect objects in an image url without saving the result.

        :param project_id: The project id.
        :type project_id: str
        :param published_name: Specifies the name of the model to evaluate
         against.
        :type published_name: str
        :param url: Url of the image.
        :type url: str
        :param application: Optional. Specifies the name of application using
         the endpoint.
        :type application: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ImagePrediction or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.vision.customvision.prediction.models.ImagePrediction
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`CustomVisionErrorException<azure.cognitiveservices.vision.customvision.prediction.models.CustomVisionErrorException>`
        """
        image_url = models.ImageUrl(url=url)

        # Construct URL
        url = self.detect_image_url_with_no_store.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'projectId': self._serialize.url("project_id", project_id, 'str'),
            'publishedName': self._serialize.url("published_name", published_name, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if application is not None:
            query_parameters['application'] = self._serialize.query("application", application, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['Prediction-Key'] = self._serialize.header("self.config.api_key", self.config.api_key, 'str')

        # Construct body
        body_content = self._serialize.body(image_url, 'ImageUrl')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.CustomVisionErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ImagePrediction', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    detect_image_url_with_no_store.metadata = {'url': '/{projectId}/detect/iterations/{publishedName}/url/nostore'}

    def detect_image_with_no_store(
            self, project_id, published_name, image_data, application=None, custom_headers=None, raw=False, **operation_config):
        """Detect objects in an image without saving the result.

        :param project_id: The project id.
        :type project_id: str
        :param published_name: Specifies the name of the model to evaluate
         against.
        :type published_name: str
        :param image_data: Binary image data. Supported formats are JPEG, GIF,
         PNG, and BMP. Supports images up to 0MB.
        :type image_data: Generator
        :param application: Optional. Specifies the name of application using
         the endpoint.
        :type application: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ImagePrediction or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.vision.customvision.prediction.models.ImagePrediction
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`CustomVisionErrorException<azure.cognitiveservices.vision.customvision.prediction.models.CustomVisionErrorException>`
        """
        # Construct URL
        url = self.detect_image_with_no_store.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'projectId': self._serialize.url("project_id", project_id, 'str'),
            'publishedName': self._serialize.url("published_name", published_name, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if application is not None:
            query_parameters['application'] = self._serialize.query("application", application, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'multipart/form-data'
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['Prediction-Key'] = self._serialize.header("self.config.api_key", self.config.api_key, 'str')

        # Construct form data
        form_data_content = {
            'imageData': image_data,
        }

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, form_content=form_data_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.CustomVisionErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ImagePrediction', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    detect_image_with_no_store.metadata = {'url': '/{projectId}/detect/iterations/{publishedName}/image/nostore'}
Ejemplo n.º 38
0
class SecurityClient(Client):
    """Security
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """
    def __init__(self, base_url=None, creds=None):
        super(SecurityClient, self).__init__(base_url, creds)
        client_models = {
            k: v
            for k, v in models.__dict__.items() if isinstance(v, type)
        }
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = None

    def remove_access_control_entries(self,
                                      security_namespace_id,
                                      token=None,
                                      descriptors=None):
        """RemoveAccessControlEntries.
        Remove the specified ACEs from the ACL belonging to the specified token.
        :param str security_namespace_id: Security namespace identifier.
        :param str token: The token whose ACL should be modified.
        :param str descriptors: String containing a list of identity descriptors separated by ',' whose entries should be removed.
        :rtype: bool
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        query_parameters = {}
        if token is not None:
            query_parameters['token'] = self._serialize.query(
                'token', token, 'str')
        if descriptors is not None:
            query_parameters['descriptors'] = self._serialize.query(
                'descriptors', descriptors, 'str')
        response = self._send(
            http_method='DELETE',
            location_id='ac08c8ff-4323-4b08-af90-bcd018d380ce',
            version='5.0',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('bool', response)

    def set_access_control_entries(self, container, security_namespace_id):
        """SetAccessControlEntries.
        Add or update ACEs in the ACL for the provided token. The request body contains the target token, a list of [ACEs](https://docs.microsoft.com/en-us/rest/api/azure/devops/security/access%20control%20entries/set%20access%20control%20entries?#accesscontrolentry) and a optional merge parameter. In the case of a collision (by identity descriptor) with an existing ACE in the ACL, the "merge" parameter determines the behavior. If set, the existing ACE has its allow and deny merged with the incoming ACE's allow and deny. If unset, the existing ACE is displaced.
        :param :class:`<object> <azure.devops.v5_0.security.models.object>` container:
        :param str security_namespace_id: Security namespace identifier.
        :rtype: [AccessControlEntry]
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        content = self._serialize.body(container, 'object')
        response = self._send(
            http_method='POST',
            location_id='ac08c8ff-4323-4b08-af90-bcd018d380ce',
            version='5.0',
            route_values=route_values,
            content=content)
        return self._deserialize('[AccessControlEntry]',
                                 self._unwrap_collection(response))

    def query_access_control_lists(self,
                                   security_namespace_id,
                                   token=None,
                                   descriptors=None,
                                   include_extended_info=None,
                                   recurse=None):
        """QueryAccessControlLists.
        Return a list of access control lists for the specified security namespace and token. All ACLs in the security namespace will be retrieved if no optional parameters are provided.
        :param str security_namespace_id: Security namespace identifier.
        :param str token: Security token
        :param str descriptors: An optional filter string containing a list of identity descriptors separated by ',' whose ACEs should be retrieved. If this is left null, entire ACLs will be returned.
        :param bool include_extended_info: If true, populate the extended information properties for the access control entries contained in the returned lists.
        :param bool recurse: If true and this is a hierarchical namespace, return child ACLs of the specified token.
        :rtype: [AccessControlList]
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        query_parameters = {}
        if token is not None:
            query_parameters['token'] = self._serialize.query(
                'token', token, 'str')
        if descriptors is not None:
            query_parameters['descriptors'] = self._serialize.query(
                'descriptors', descriptors, 'str')
        if include_extended_info is not None:
            query_parameters['includeExtendedInfo'] = self._serialize.query(
                'include_extended_info', include_extended_info, 'bool')
        if recurse is not None:
            query_parameters['recurse'] = self._serialize.query(
                'recurse', recurse, 'bool')
        response = self._send(
            http_method='GET',
            location_id='18a2ad18-7571-46ae-bec7-0c7da1495885',
            version='5.0',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[AccessControlList]',
                                 self._unwrap_collection(response))

    def remove_access_control_lists(self,
                                    security_namespace_id,
                                    tokens=None,
                                    recurse=None):
        """RemoveAccessControlLists.
        Remove access control lists under the specfied security namespace.
        :param str security_namespace_id: Security namespace identifier.
        :param str tokens: One or more comma-separated security tokens
        :param bool recurse: If true and this is a hierarchical namespace, also remove child ACLs of the specified tokens.
        :rtype: bool
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        query_parameters = {}
        if tokens is not None:
            query_parameters['tokens'] = self._serialize.query(
                'tokens', tokens, 'str')
        if recurse is not None:
            query_parameters['recurse'] = self._serialize.query(
                'recurse', recurse, 'bool')
        response = self._send(
            http_method='DELETE',
            location_id='18a2ad18-7571-46ae-bec7-0c7da1495885',
            version='5.0',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('bool', response)

    def set_access_control_lists(self, access_control_lists,
                                 security_namespace_id):
        """SetAccessControlLists.
        Create or update one or more access control lists. All data that currently exists for the ACLs supplied will be overwritten.
        :param :class:`<VssJsonCollectionWrapper> <azure.devops.v5_0.security.models.VssJsonCollectionWrapper>` access_control_lists: A list of ACLs to create or update.
        :param str security_namespace_id: Security namespace identifier.
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        content = self._serialize.body(access_control_lists,
                                       'VssJsonCollectionWrapper')
        self._send(http_method='POST',
                   location_id='18a2ad18-7571-46ae-bec7-0c7da1495885',
                   version='5.0',
                   route_values=route_values,
                   content=content)

    def has_permissions_batch(self, eval_batch):
        """HasPermissionsBatch.
        Evaluates multiple permissions for the calling user.  Note: This method does not aggregate the results, nor does it short-circuit if one of the permissions evaluates to false.
        :param :class:`<PermissionEvaluationBatch> <azure.devops.v5_0.security.models.PermissionEvaluationBatch>` eval_batch: The set of evaluation requests.
        :rtype: :class:`<PermissionEvaluationBatch> <azure.devops.v5_0.security.models.PermissionEvaluationBatch>`
        """
        content = self._serialize.body(eval_batch, 'PermissionEvaluationBatch')
        response = self._send(
            http_method='POST',
            location_id='cf1faa59-1b63-4448-bf04-13d981a46f5d',
            version='5.0',
            content=content)
        return self._deserialize('PermissionEvaluationBatch', response)

    def has_permissions(self,
                        security_namespace_id,
                        permissions=None,
                        tokens=None,
                        always_allow_administrators=None,
                        delimiter=None):
        """HasPermissions.
        Evaluates whether the caller has the specified permissions on the specified set of security tokens.
        :param str security_namespace_id: Security namespace identifier.
        :param int permissions: Permissions to evaluate.
        :param str tokens: One or more security tokens to evaluate.
        :param bool always_allow_administrators: If true and if the caller is an administrator, always return true.
        :param str delimiter: Optional security token separator. Defaults to ",".
        :rtype: [bool]
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        if permissions is not None:
            route_values['permissions'] = self._serialize.url(
                'permissions', permissions, 'int')
        query_parameters = {}
        if tokens is not None:
            query_parameters['tokens'] = self._serialize.query(
                'tokens', tokens, 'str')
        if always_allow_administrators is not None:
            query_parameters[
                'alwaysAllowAdministrators'] = self._serialize.query(
                    'always_allow_administrators', always_allow_administrators,
                    'bool')
        if delimiter is not None:
            query_parameters['delimiter'] = self._serialize.query(
                'delimiter', delimiter, 'str')
        response = self._send(
            http_method='GET',
            location_id='dd3b8bd6-c7fc-4cbd-929a-933d9c011c9d',
            version='5.0',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[bool]', self._unwrap_collection(response))

    def remove_permission(self,
                          security_namespace_id,
                          descriptor,
                          permissions=None,
                          token=None):
        """RemovePermission.
        Removes the specified permissions on a security token for a user or group.
        :param str security_namespace_id: Security namespace identifier.
        :param str descriptor: Identity descriptor of the user to remove permissions for.
        :param int permissions: Permissions to remove.
        :param str token: Security token to remove permissions for.
        :rtype: :class:`<AccessControlEntry> <azure.devops.v5_0.security.models.AccessControlEntry>`
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        if permissions is not None:
            route_values['permissions'] = self._serialize.url(
                'permissions', permissions, 'int')
        query_parameters = {}
        if descriptor is not None:
            query_parameters['descriptor'] = self._serialize.query(
                'descriptor', descriptor, 'str')
        if token is not None:
            query_parameters['token'] = self._serialize.query(
                'token', token, 'str')
        response = self._send(
            http_method='DELETE',
            location_id='dd3b8bd6-c7fc-4cbd-929a-933d9c011c9d',
            version='5.0',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('AccessControlEntry', response)

    def query_security_namespaces(self,
                                  security_namespace_id=None,
                                  local_only=None):
        """QuerySecurityNamespaces.
        List all security namespaces or just the specified namespace.
        :param str security_namespace_id: Security namespace identifier.
        :param bool local_only: If true, retrieve only local security namespaces.
        :rtype: [SecurityNamespaceDescription]
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        query_parameters = {}
        if local_only is not None:
            query_parameters['localOnly'] = self._serialize.query(
                'local_only', local_only, 'bool')
        response = self._send(
            http_method='GET',
            location_id='ce7b9f95-fde9-4be8-a86d-83b366f0b87a',
            version='5.0',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('[SecurityNamespaceDescription]',
                                 self._unwrap_collection(response))
class WebSiteManagementClient(object):
    """WebSite Management Client

    :ivar config: Configuration for client.
    :vartype config: WebSiteManagementClientConfiguration

    :ivar app_service_certificate_orders: AppServiceCertificateOrders operations
    :vartype app_service_certificate_orders: azure.mgmt.web.operations.AppServiceCertificateOrdersOperations
    :ivar domains: Domains operations
    :vartype domains: azure.mgmt.web.operations.DomainsOperations
    :ivar top_level_domains: TopLevelDomains operations
    :vartype top_level_domains: azure.mgmt.web.operations.TopLevelDomainsOperations
    :ivar certificates: Certificates operations
    :vartype certificates: azure.mgmt.web.operations.CertificatesOperations
    :ivar deleted_web_apps: DeletedWebApps operations
    :vartype deleted_web_apps: azure.mgmt.web.operations.DeletedWebAppsOperations
    :ivar provider: Provider operations
    :vartype provider: azure.mgmt.web.operations.ProviderOperations
    :ivar recommendations: Recommendations operations
    :vartype recommendations: azure.mgmt.web.operations.RecommendationsOperations
    :ivar web_apps: WebApps operations
    :vartype web_apps: azure.mgmt.web.operations.WebAppsOperations
    :ivar app_service_environments: AppServiceEnvironments operations
    :vartype app_service_environments: azure.mgmt.web.operations.AppServiceEnvironmentsOperations
    :ivar app_service_plans: AppServicePlans operations
    :vartype app_service_plans: azure.mgmt.web.operations.AppServicePlansOperations

    :param credentials: Credentials needed for the client to connect to Azure.
    :type credentials: :mod:`A msrestazure Credentials
     object<msrestazure.azure_active_directory>`
    :param subscription_id: Your Azure subscription ID. This is a
     GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000).
    :type subscription_id: str
    :param str base_url: Service URL
    """

    def __init__(
            self, credentials, subscription_id, base_url=None):

        self.config = WebSiteManagementClientConfiguration(credentials, subscription_id, base_url)
        self._client = ServiceClient(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

        self.app_service_certificate_orders = AppServiceCertificateOrdersOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.domains = DomainsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.top_level_domains = TopLevelDomainsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.certificates = CertificatesOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.deleted_web_apps = DeletedWebAppsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.provider = ProviderOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.recommendations = RecommendationsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.web_apps = WebAppsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.app_service_environments = AppServiceEnvironmentsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.app_service_plans = AppServicePlansOperations(
            self._client, self.config, self._serialize, self._deserialize)

    def get_publishing_user(
            self, custom_headers=None, raw=False, **operation_config):
        """Gets publishing user.

        Gets publishing user.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: User or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.web.models.User or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-03-01"

        # Construct URL
        url = '/providers/Microsoft.Web/publishingUsers/web'

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('User', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def update_publishing_user(
            self, user_details, custom_headers=None, raw=False, **operation_config):
        """Updates publishing user.

        Updates publishing user.

        :param user_details: Details of publishing user
        :type user_details: ~azure.mgmt.web.models.User
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: User or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.web.models.User or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-03-01"

        # Construct URL
        url = '/providers/Microsoft.Web/publishingUsers/web'

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(user_details, 'User')

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('User', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def list_source_controls(
            self, custom_headers=None, raw=False, **operation_config):
        """Gets the source controls available for Azure websites.

        Gets the source controls available for Azure websites.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of SourceControl
        :rtype:
         ~azure.mgmt.web.models.SourceControlPaged[~azure.mgmt.web.models.SourceControl]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-03-01"

        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = '/providers/Microsoft.Web/sourcecontrols'

                # Construct parameters
                query_parameters = {}
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Content-Type'] = 'application/json; charset=utf-8'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters)
            response = self._client.send(
                request, header_parameters, **operation_config)

            if response.status_code not in [200]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            return response

        # Deserialize response
        deserialized = models.SourceControlPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.SourceControlPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized

    def get_source_control(
            self, source_control_type, custom_headers=None, raw=False, **operation_config):
        """Gets source control token.

        Gets source control token.

        :param source_control_type: Type of source control
        :type source_control_type: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: SourceControl or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.web.models.SourceControl or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-03-01"

        # Construct URL
        url = '/providers/Microsoft.Web/sourcecontrols/{sourceControlType}'
        path_format_arguments = {
            'sourceControlType': self._serialize.url("source_control_type", source_control_type, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('SourceControl', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def update_source_control(
            self, source_control_type, request_message, custom_headers=None, raw=False, **operation_config):
        """Updates source control token.

        Updates source control token.

        :param source_control_type: Type of source control
        :type source_control_type: str
        :param request_message: Source control token information
        :type request_message: ~azure.mgmt.web.models.SourceControl
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: SourceControl or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.web.models.SourceControl or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-03-01"

        # Construct URL
        url = '/providers/Microsoft.Web/sourcecontrols/{sourceControlType}'
        path_format_arguments = {
            'sourceControlType': self._serialize.url("source_control_type", source_control_type, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(request_message, 'SourceControl')

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('SourceControl', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def check_name_availability(
            self, name, type, is_fqdn=None, custom_headers=None, raw=False, **operation_config):
        """Check if a resource name is available.

        Check if a resource name is available.

        :param name: Resource name to verify.
        :type name: str
        :param type: Resource type used for verification. Possible values
         include: 'Site', 'Slot', 'HostingEnvironment'
        :type type: str or ~azure.mgmt.web.models.CheckNameResourceTypes
        :param is_fqdn: Is fully qualified domain name.
        :type is_fqdn: bool
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ResourceNameAvailability or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.web.models.ResourceNameAvailability or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        request = models.ResourceNameAvailabilityRequest(name=name, type=type, is_fqdn=is_fqdn)

        api_version = "2016-03-01"

        # Construct URL
        url = '/subscriptions/{subscriptionId}/providers/Microsoft.Web/checknameavailability'
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(request, 'ResourceNameAvailabilityRequest')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ResourceNameAvailability', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def get_subscription_deployment_locations(
            self, custom_headers=None, raw=False, **operation_config):
        """Gets list of available geo regions plus ministamps.

        Gets list of available geo regions plus ministamps.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: DeploymentLocations or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.web.models.DeploymentLocations or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-03-01"

        # Construct URL
        url = '/subscriptions/{subscriptionId}/providers/Microsoft.Web/deploymentLocations'
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('DeploymentLocations', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def list_geo_regions(
            self, sku=None, linux_workers_enabled=None, custom_headers=None, raw=False, **operation_config):
        """Get a list of available geographical regions.

        Get a list of available geographical regions.

        :param sku: Name of SKU used to filter the regions. Possible values
         include: 'Free', 'Shared', 'Basic', 'Standard', 'Premium',
         'PremiumV2', 'Dynamic', 'Isolated'
        :type sku: str or ~azure.mgmt.web.models.SkuName
        :param linux_workers_enabled: Specify <code>true</code> if you want to
         filter to only regions that support Linux workers.
        :type linux_workers_enabled: bool
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of GeoRegion
        :rtype:
         ~azure.mgmt.web.models.GeoRegionPaged[~azure.mgmt.web.models.GeoRegion]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-03-01"

        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = '/subscriptions/{subscriptionId}/providers/Microsoft.Web/geoRegions'
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                if sku is not None:
                    query_parameters['sku'] = self._serialize.query("sku", sku, 'str')
                if linux_workers_enabled is not None:
                    query_parameters['linuxWorkersEnabled'] = self._serialize.query("linux_workers_enabled", linux_workers_enabled, 'bool')
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Content-Type'] = 'application/json; charset=utf-8'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters)
            response = self._client.send(
                request, header_parameters, **operation_config)

            if response.status_code not in [200]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            return response

        # Deserialize response
        deserialized = models.GeoRegionPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.GeoRegionPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized

    def list_premier_add_on_offers(
            self, custom_headers=None, raw=False, **operation_config):
        """List all premier add-on offers.

        List all premier add-on offers.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of PremierAddOnOffer
        :rtype:
         ~azure.mgmt.web.models.PremierAddOnOfferPaged[~azure.mgmt.web.models.PremierAddOnOffer]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-03-01"

        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = '/subscriptions/{subscriptionId}/providers/Microsoft.Web/premieraddonoffers'
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Content-Type'] = 'application/json; charset=utf-8'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters)
            response = self._client.send(
                request, header_parameters, **operation_config)

            if response.status_code not in [200]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            return response

        # Deserialize response
        deserialized = models.PremierAddOnOfferPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.PremierAddOnOfferPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized

    def list_skus(
            self, custom_headers=None, raw=False, **operation_config):
        """List all SKUs.

        List all SKUs.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: SkuInfos or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.web.models.SkuInfos or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-03-01"

        # Construct URL
        url = '/subscriptions/{subscriptionId}/providers/Microsoft.Web/skus'
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('SkuInfos', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def verify_hosting_environment_vnet(
            self, parameters, custom_headers=None, raw=False, **operation_config):
        """Verifies if this VNET is compatible with an App Service Environment by
        analyzing the Network Security Group rules.

        Verifies if this VNET is compatible with an App Service Environment by
        analyzing the Network Security Group rules.

        :param parameters: VNET information
        :type parameters: ~azure.mgmt.web.models.VnetParameters
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: VnetValidationFailureDetails or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.web.models.VnetValidationFailureDetails or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-03-01"

        # Construct URL
        url = '/subscriptions/{subscriptionId}/providers/Microsoft.Web/verifyHostingEnvironmentVnet'
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(parameters, 'VnetParameters')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('VnetValidationFailureDetails', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def move(
            self, resource_group_name, target_resource_group=None, resources=None, custom_headers=None, raw=False, **operation_config):
        """Move resources between resource groups.

        Move resources between resource groups.

        :param resource_group_name: Name of the resource group to which the
         resource belongs.
        :type resource_group_name: str
        :param target_resource_group:
        :type target_resource_group: str
        :param resources:
        :type resources: list[str]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        move_resource_envelope = models.CsmMoveResourceEnvelope(target_resource_group=target_resource_group, resources=resources)

        api_version = "2016-03-01"

        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/moveResources'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+[^\.]$'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(move_resource_envelope, 'CsmMoveResourceEnvelope')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [204]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def validate(
            self, resource_group_name, validate_request, custom_headers=None, raw=False, **operation_config):
        """Validate if a resource can be created.

        Validate if a resource can be created.

        :param resource_group_name: Name of the resource group to which the
         resource belongs.
        :type resource_group_name: str
        :param validate_request: Request with the resources to validate.
        :type validate_request: ~azure.mgmt.web.models.ValidateRequest
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ValidateResponse or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.web.models.ValidateResponse or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-03-01"

        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/validate'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+[^\.]$'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(validate_request, 'ValidateRequest')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ValidateResponse', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def validate_move(
            self, resource_group_name, target_resource_group=None, resources=None, custom_headers=None, raw=False, **operation_config):
        """Validate whether a resource can be moved.

        Validate whether a resource can be moved.

        :param resource_group_name: Name of the resource group to which the
         resource belongs.
        :type resource_group_name: str
        :param target_resource_group:
        :type target_resource_group: str
        :param resources:
        :type resources: list[str]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        move_resource_envelope = models.CsmMoveResourceEnvelope(target_resource_group=target_resource_group, resources=resources)

        api_version = "2016-03-01"

        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/validateMoveResources'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+[^\.]$'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(move_resource_envelope, 'CsmMoveResourceEnvelope')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [204]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response
Ejemplo n.º 40
0
class SwaggerPetstore(object):
    """This is a sample server Petstore server.  You can find out more about Swagger at &lt;a href="http://swagger.io"&gt;http://swagger.io&lt;/a&gt; or on irc.freenode.net, #swagger.  For this sample, you can use the api key "special-key" to test the authorization filters

    :ivar config: Configuration for client.
    :vartype config: SwaggerPetstoreConfiguration

    :param str base_url: Service URL
    """
    def __init__(self, base_url=None):

        self.config = SwaggerPetstoreConfiguration(base_url)
        self._client = ServiceClient(None, self.config)

        client_models = {
            k: v
            for k, v in models.__dict__.items() if isinstance(v, type)
        }
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    def add_pet_using_byte_array(self,
                                 body=None,
                                 custom_headers=None,
                                 raw=False,
                                 **operation_config):
        """Fake endpoint to test byte array in body parameter for adding a new pet
        to the store.

        :param body: Pet object in the form of byte array
        :type body: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/pet'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'str')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request, header_parameters, body_content,
                                     **operation_config)

        if response.status_code not in [405]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def add_pet(self,
                body=None,
                custom_headers=None,
                raw=False,
                **operation_config):
        """Add a new pet to the store.

        Adds a new pet to the store. You may receive an HTTP invalid input if
        your pet is invalid.

        :param body: Pet object that needs to be added to the store
        :type body: :class:`Pet <petstore.models.Pet>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/pet'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'Pet')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request, header_parameters, body_content,
                                     **operation_config)

        if response.status_code not in [405]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def update_pet(self,
                   body=None,
                   custom_headers=None,
                   raw=False,
                   **operation_config):
        """Update an existing pet.

        :param body: Pet object that needs to be added to the store
        :type body: :class:`Pet <petstore.models.Pet>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/pet'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'Pet')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(request, header_parameters, body_content,
                                     **operation_config)

        if response.status_code not in [405, 404, 400]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def find_pets_by_status(self,
                            status=None,
                            custom_headers=None,
                            raw=False,
                            **operation_config):
        """Finds Pets by status.

        Multiple status values can be provided with comma seperated strings.

        :param status: Status values that need to be considered for filter
        :type status: list of str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: list of :class:`Pet <petstore.models.Pet>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/pet/findByStatus'

        # Construct parameters
        query_parameters = {}
        if status is not None:
            query_parameters['status'] = self._serialize.query("status",
                                                               status,
                                                               '[str]',
                                                               div=',')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters,
                                     **operation_config)

        if response.status_code not in [200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('[Pet]', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def find_pets_by_tags(self,
                          tags=None,
                          custom_headers=None,
                          raw=False,
                          **operation_config):
        """Finds Pets by tags.

        Muliple tags can be provided with comma seperated strings. Use tag1,
        tag2, tag3 for testing.

        :param tags: Tags to filter by
        :type tags: list of str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: list of :class:`Pet <petstore.models.Pet>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/pet/findByTags'

        # Construct parameters
        query_parameters = {}
        if tags is not None:
            query_parameters['tags'] = self._serialize.query("tags",
                                                             tags,
                                                             '[str]',
                                                             div=',')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters,
                                     **operation_config)

        if response.status_code not in [200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('[Pet]', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def find_pets_with_byte_array(self,
                                  pet_id,
                                  custom_headers=None,
                                  raw=False,
                                  **operation_config):
        """Fake endpoint to test byte array return by 'Find pet by ID'.

        Returns a pet when ID < 10.  ID > 10 or nonintegers will simulate API
        error conditions.

        :param pet_id: ID of pet that needs to be fetched
        :type pet_id: long
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: str
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/pet/{petId}'
        path_format_arguments = {
            'petId': self._serialize.url("pet_id", pet_id, 'long')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters,
                                     **operation_config)

        if response.status_code not in [404, 200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def get_pet_by_id(self,
                      pet_id,
                      custom_headers=None,
                      raw=False,
                      **operation_config):
        """Find pet by ID.

        Returns a pet when ID < 10.  ID > 10 or nonintegers will simulate API
        error conditions.

        :param pet_id: ID of pet that needs to be fetched
        :type pet_id: long
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`Pet <petstore.models.Pet>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/pet/{petId}'
        path_format_arguments = {
            'petId': self._serialize.url("pet_id", pet_id, 'long')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters,
                                     **operation_config)

        if response.status_code not in [404, 200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Pet', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def update_pet_with_form(self,
                             pet_id,
                             name=None,
                             status=None,
                             custom_headers=None,
                             raw=False,
                             **operation_config):
        """Updates a pet in the store with form data.

        :param pet_id: ID of pet that needs to be updated
        :type pet_id: str
        :param name: Updated name of the pet
        :type name: str
        :param status: Updated status of the pet
        :type status: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/pet/{petId}'
        path_format_arguments = {
            'petId': self._serialize.url("pet_id", pet_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/x-www-form-urlencoded'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct form data
        form_data_content = {
            'name': name,
            'status': status,
        }

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send_formdata(request, header_parameters,
                                              form_data_content,
                                              **operation_config)

        if response.status_code not in [405]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def delete_pet(self,
                   pet_id,
                   api_key=None,
                   custom_headers=None,
                   raw=False,
                   **operation_config):
        """Deletes a pet.

        :param pet_id: Pet id to delete
        :type pet_id: long
        :param api_key:
        :type api_key: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/pet/{petId}'
        path_format_arguments = {
            'petId': self._serialize.url("pet_id", pet_id, 'long')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        if api_key is not None:
            header_parameters['api_key'] = self._serialize.header(
                "api_key", api_key, 'str')

        # Construct and send request
        request = self._client.delete(url, query_parameters)
        response = self._client.send(request, header_parameters,
                                     **operation_config)

        if response.status_code not in [400]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def upload_file(self,
                    pet_id,
                    additional_metadata=None,
                    file=None,
                    custom_headers=None,
                    raw=False,
                    **operation_config):
        """uploads an image.

        :param pet_id: ID of pet to update
        :type pet_id: long
        :param additional_metadata: Additional data to pass to server
        :type additional_metadata: str
        :param file: file to upload
        :type file: Generator
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/pet/{petId}/uploadImage'
        path_format_arguments = {
            'petId': self._serialize.url("pet_id", pet_id, 'long')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'multipart/form-data'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct form data
        form_data_content = {
            'additionalMetadata': additional_metadata,
            'file': file,
        }

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send_formdata(request, header_parameters,
                                              form_data_content,
                                              **operation_config)

        if response.status_code < 200 or response.status_code >= 300:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def get_inventory(self,
                      custom_headers=None,
                      raw=False,
                      **operation_config):
        """Returns pet inventories by status.

        Returns a map of status codes to quantities.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: dict
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/store/inventory'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters,
                                     **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('{int}', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def place_order(self,
                    body=None,
                    custom_headers=None,
                    raw=False,
                    **operation_config):
        """Place an order for a pet.

        :param body: order placed for purchasing the pet
        :type body: :class:`Order <petstore.models.Order>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`Order <petstore.models.Order>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/store/order'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'Order')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request, header_parameters, body_content,
                                     **operation_config)

        if response.status_code not in [200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Order', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def get_order_by_id(self,
                        order_id,
                        custom_headers=None,
                        raw=False,
                        **operation_config):
        """Find purchase order by ID.

        For valid response try integer IDs with value <= 5 or > 10. Other
        values will generated exceptions.

        :param order_id: ID of pet that needs to be fetched
        :type order_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`Order <petstore.models.Order>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/store/order/{orderId}'
        path_format_arguments = {
            'orderId': self._serialize.url("order_id", order_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters,
                                     **operation_config)

        if response.status_code not in [404, 200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Order', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def delete_order(self,
                     order_id,
                     custom_headers=None,
                     raw=False,
                     **operation_config):
        """Delete purchase order by ID.

        For valid response try integer IDs with value < 1000. Anything above
        1000 or nonintegers will generate API errors.

        :param order_id: ID of the order that needs to be deleted
        :type order_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/store/order/{orderId}'
        path_format_arguments = {
            'orderId': self._serialize.url("order_id", order_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.delete(url, query_parameters)
        response = self._client.send(request, header_parameters,
                                     **operation_config)

        if response.status_code not in [404, 400]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def create_user(self,
                    body=None,
                    custom_headers=None,
                    raw=False,
                    **operation_config):
        """Create user.

        This can only be done by the logged in user.

        :param body: Created user object
        :type body: :class:`User <petstore.models.User>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/user'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'User')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request, header_parameters, body_content,
                                     **operation_config)

        if response.status_code < 200 or response.status_code >= 300:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def create_users_with_array_input(self,
                                      body=None,
                                      custom_headers=None,
                                      raw=False,
                                      **operation_config):
        """Creates list of users with given input array.

        :param body: List of user object
        :type body: list of :class:`User <petstore.models.User>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/user/createWithArray'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, '[User]')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request, header_parameters, body_content,
                                     **operation_config)

        if response.status_code < 200 or response.status_code >= 300:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def create_users_with_list_input(self,
                                     body=None,
                                     custom_headers=None,
                                     raw=False,
                                     **operation_config):
        """Creates list of users with given input array.

        :param body: List of user object
        :type body: list of :class:`User <petstore.models.User>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/user/createWithList'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, '[User]')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request, header_parameters, body_content,
                                     **operation_config)

        if response.status_code < 200 or response.status_code >= 300:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def login_user(self,
                   username=None,
                   password=None,
                   custom_headers=None,
                   raw=False,
                   **operation_config):
        """Logs user into the system.

        :param username: The user name for login
        :type username: str
        :param password: The password for login in clear text
        :type password: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: str
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/user/login'

        # Construct parameters
        query_parameters = {}
        if username is not None:
            query_parameters['username'] = self._serialize.query(
                "username", username, 'str')
        if password is not None:
            query_parameters['password'] = self._serialize.query(
                "password", password, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters,
                                     **operation_config)

        if response.status_code not in [200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def logout_user(self, custom_headers=None, raw=False, **operation_config):
        """Logs out current logged in user session.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/user/logout'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters,
                                     **operation_config)

        if response.status_code < 200 or response.status_code >= 300:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def get_user_by_name(self,
                         username,
                         custom_headers=None,
                         raw=False,
                         **operation_config):
        """Get user by user name.

        :param username: The name that needs to be fetched. Use user1 for
         testing.
        :type username: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`User <petstore.models.User>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/user/{username}'
        path_format_arguments = {
            'username': self._serialize.url("username", username, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters,
                                     **operation_config)

        if response.status_code not in [404, 200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('User', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def update_user(self,
                    username,
                    body=None,
                    custom_headers=None,
                    raw=False,
                    **operation_config):
        """Updated user.

        This can only be done by the logged in user.

        :param username: name that need to be deleted
        :type username: str
        :param body: Updated user object
        :type body: :class:`User <petstore.models.User>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/user/{username}'
        path_format_arguments = {
            'username': self._serialize.url("username", username, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'User')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(request, header_parameters, body_content,
                                     **operation_config)

        if response.status_code not in [404, 400]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def delete_user(self,
                    username,
                    custom_headers=None,
                    raw=False,
                    **operation_config):
        """Delete user.

        This can only be done by the logged in user.

        :param username: The name that needs to be deleted
        :type username: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/user/{username}'
        path_format_arguments = {
            'username': self._serialize.url("username", username, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.delete(url, query_parameters)
        response = self._client.send(request, header_parameters,
                                     **operation_config)

        if response.status_code not in [404, 400]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response
class ResourceGraphClient(SDKClient):
    """Azure Resource Graph API Reference

    :ivar config: Configuration for client.
    :vartype config: ResourceGraphClientConfiguration

    :ivar operations: Operations operations
    :vartype operations: azure.mgmt.resourcegraph.operations.Operations

    :param credentials: Credentials needed for the client to connect to Azure.
    :type credentials: :mod:`A msrestazure Credentials
     object<msrestazure.azure_active_directory>`
    :param str base_url: Service URL
    """

    def __init__(
            self, credentials, base_url=None):

        self.config = ResourceGraphClientConfiguration(credentials, base_url)
        super(ResourceGraphClient, self).__init__(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self.api_version = '2018-09-01-preview'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

        self.operations = Operations(
            self._client, self.config, self._serialize, self._deserialize)

    def resources(
            self, query, custom_headers=None, raw=False, **operation_config):
        """Queries the resources managed by Azure Resource Manager for all
        subscriptions specified in the request.

        :param query: Request specifying query and its options.
        :type query: ~azure.mgmt.resourcegraph.models.QueryRequest
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: QueryResponse or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.resourcegraph.models.QueryResponse or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.resourcegraph.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.resources.metadata['url']

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(query, 'QueryRequest')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('QueryResponse', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    resources.metadata = {'url': '/providers/Microsoft.ResourceGraph/resources'}
Ejemplo n.º 42
0
class SwaggerPetstore(object):
    """This is a sample server Petstore server.  You can find out more about Swagger at &lt;a href="http://swagger.io"&gt;http://swagger.io&lt;/a&gt; or on irc.freenode.net, #swagger.  For this sample, you can use the api key "special-key" to test the authorization filters

    :ivar config: Configuration for client.
    :vartype config: SwaggerPetstoreConfiguration

    :param str base_url: Service URL
    :param str filepath: Existing config
    """

    def __init__(
            self, base_url=None, filepath=None):

        self.config = SwaggerPetstoreConfiguration(base_url, filepath)
        self._client = ServiceClient(None, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)


    def add_pet_using_byte_array(
            self, body=None, custom_headers=None, raw=False, **operation_config):
        """Fake endpoint to test byte array in body parameter for adding a new
        pet to the store.

        :param body: Pet object in the form of byte array
        :type body: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/pet'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'str')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [405]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def add_pet(
            self, body=None, custom_headers=None, raw=False, **operation_config):
        """Add a new pet to the store.

        Adds a new pet to the store. You may receive an HTTP invalid input if
        your pet is invalid.

        :param body: Pet object that needs to be added to the store
        :type body: :class:`Pet <Petstore.models.Pet>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/pet'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'Pet')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [405]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def update_pet(
            self, body=None, custom_headers=None, raw=False, **operation_config):
        """Update an existing pet.

        :param body: Pet object that needs to be added to the store
        :type body: :class:`Pet <Petstore.models.Pet>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/pet'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'Pet')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [405, 404, 400]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def find_pets_by_status(
            self, status=None, custom_headers=None, raw=False, **operation_config):
        """Finds Pets by status.

        Multiple status values can be provided with comma seperated strings.

        :param status: Status values that need to be considered for filter
        :type status: list of str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: list of :class:`Pet <Petstore.models.Pet>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/pet/findByStatus'

        # Construct parameters
        query_parameters = {}
        if status is not None:
            query_parameters['status'] = self._serialize.query("status", status, '[str]', div=',')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('[Pet]', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def find_pets_by_tags(
            self, tags=None, custom_headers=None, raw=False, **operation_config):
        """Finds Pets by tags.

        Muliple tags can be provided with comma seperated strings. Use tag1,
        tag2, tag3 for testing.

        :param tags: Tags to filter by
        :type tags: list of str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: list of :class:`Pet <Petstore.models.Pet>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/pet/findByTags'

        # Construct parameters
        query_parameters = {}
        if tags is not None:
            query_parameters['tags'] = self._serialize.query("tags", tags, '[str]', div=',')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('[Pet]', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def find_pets_with_byte_array(
            self, pet_id, custom_headers=None, raw=False, **operation_config):
        """Fake endpoint to test byte array return by 'Find pet by ID'.

        Returns a pet when ID < 10.  ID > 10 or nonintegers will simulate API
        error conditions.

        :param pet_id: ID of pet that needs to be fetched
        :type pet_id: long
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: str
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/pet/{petId}'
        path_format_arguments = {
            'petId': self._serialize.url("pet_id", pet_id, 'long')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [404, 200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def get_pet_by_id(
            self, pet_id, custom_headers=None, raw=False, **operation_config):
        """Find pet by ID.

        Returns a pet when ID < 10.  ID > 10 or nonintegers will simulate API
        error conditions.

        :param pet_id: ID of pet that needs to be fetched
        :type pet_id: long
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`Pet <Petstore.models.Pet>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/pet/{petId}'
        path_format_arguments = {
            'petId': self._serialize.url("pet_id", pet_id, 'long')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [404, 200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Pet', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def update_pet_with_form(
            self, pet_id, name=None, status=None, custom_headers=None, raw=False, **operation_config):
        """Updates a pet in the store with form data.

        :param pet_id: ID of pet that needs to be updated
        :type pet_id: str
        :param name: Updated name of the pet
        :type name: str
        :param status: Updated status of the pet
        :type status: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/pet/{petId}'
        path_format_arguments = {
            'petId': self._serialize.url("pet_id", pet_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/x-www-form-urlencoded'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct form data
        form_data_content = {
            'name': name,
            'status': status,
        }

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send_formdata(
            request, header_parameters, form_data_content, **operation_config)

        if response.status_code not in [405]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def delete_pet(
            self, pet_id, api_key=None, custom_headers=None, raw=False, **operation_config):
        """Deletes a pet.

        :param pet_id: Pet id to delete
        :type pet_id: long
        :param api_key:
        :type api_key: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/pet/{petId}'
        path_format_arguments = {
            'petId': self._serialize.url("pet_id", pet_id, 'long')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        if api_key is not None:
            header_parameters['api_key'] = self._serialize.header("api_key", api_key, 'str')

        # Construct and send request
        request = self._client.delete(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [400]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def upload_file(
            self, pet_id, additional_metadata=None, file=None, custom_headers=None, raw=False, **operation_config):
        """uploads an image.

        :param pet_id: ID of pet to update
        :type pet_id: long
        :param additional_metadata: Additional data to pass to server
        :type additional_metadata: str
        :param file: file to upload
        :type file: Generator
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/pet/{petId}/uploadImage'
        path_format_arguments = {
            'petId': self._serialize.url("pet_id", pet_id, 'long')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'multipart/form-data'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct form data
        form_data_content = {
            'additionalMetadata': additional_metadata,
            'file': file,
        }

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send_formdata(
            request, header_parameters, form_data_content, **operation_config)

        if response.status_code < 200 or response.status_code >= 300:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def get_inventory(
            self, custom_headers=None, raw=False, **operation_config):
        """Returns pet inventories by status.

        Returns a map of status codes to quantities.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: dict
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/store/inventory'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('{int}', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def place_order(
            self, body=None, custom_headers=None, raw=False, **operation_config):
        """Place an order for a pet.

        :param body: order placed for purchasing the pet
        :type body: :class:`Order <Petstore.models.Order>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`Order <Petstore.models.Order>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/store/order'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'Order')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Order', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def get_order_by_id(
            self, order_id, custom_headers=None, raw=False, **operation_config):
        """Find purchase order by ID.

        For valid response try integer IDs with value <= 5 or > 10. Other
        values will generated exceptions.

        :param order_id: ID of pet that needs to be fetched
        :type order_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`Order <Petstore.models.Order>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/store/order/{orderId}'
        path_format_arguments = {
            'orderId': self._serialize.url("order_id", order_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [404, 200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Order', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def delete_order(
            self, order_id, custom_headers=None, raw=False, **operation_config):
        """Delete purchase order by ID.

        For valid response try integer IDs with value < 1000. Anything above
        1000 or nonintegers will generate API errors.

        :param order_id: ID of the order that needs to be deleted
        :type order_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/store/order/{orderId}'
        path_format_arguments = {
            'orderId': self._serialize.url("order_id", order_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.delete(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [404, 400]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def create_user(
            self, body=None, custom_headers=None, raw=False, **operation_config):
        """Create user.

        This can only be done by the logged in user.

        :param body: Created user object
        :type body: :class:`User <Petstore.models.User>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/user'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'User')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code < 200 or response.status_code >= 300:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def create_users_with_array_input(
            self, body=None, custom_headers=None, raw=False, **operation_config):
        """Creates list of users with given input array.

        :param body: List of user object
        :type body: list of :class:`User <Petstore.models.User>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/user/createWithArray'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, '[User]')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code < 200 or response.status_code >= 300:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def create_users_with_list_input(
            self, body=None, custom_headers=None, raw=False, **operation_config):
        """Creates list of users with given input array.

        :param body: List of user object
        :type body: list of :class:`User <Petstore.models.User>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/user/createWithList'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, '[User]')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code < 200 or response.status_code >= 300:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def login_user(
            self, username=None, password=None, custom_headers=None, raw=False, **operation_config):
        """Logs user into the system.

        :param username: The user name for login
        :type username: str
        :param password: The password for login in clear text
        :type password: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: str
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/user/login'

        # Construct parameters
        query_parameters = {}
        if username is not None:
            query_parameters['username'] = self._serialize.query("username", username, 'str')
        if password is not None:
            query_parameters['password'] = self._serialize.query("password", password, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('str', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def logout_user(
            self, custom_headers=None, raw=False, **operation_config):
        """Logs out current logged in user session.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/user/logout'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code < 200 or response.status_code >= 300:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def get_user_by_name(
            self, username, custom_headers=None, raw=False, **operation_config):
        """Get user by user name.

        :param username: The name that needs to be fetched. Use user1 for
         testing.
        :type username: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`User <Petstore.models.User>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/user/{username}'
        path_format_arguments = {
            'username': self._serialize.url("username", username, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [404, 200, 400]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('User', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def update_user(
            self, username, body=None, custom_headers=None, raw=False, **operation_config):
        """Updated user.

        This can only be done by the logged in user.

        :param username: name that need to be deleted
        :type username: str
        :param body: Updated user object
        :type body: :class:`User <Petstore.models.User>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/user/{username}'
        path_format_arguments = {
            'username': self._serialize.url("username", username, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if body is not None:
            body_content = self._serialize.body(body, 'User')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [404, 400]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def delete_user(
            self, username, custom_headers=None, raw=False, **operation_config):
        """Delete user.

        This can only be done by the logged in user.

        :param username: The name that needs to be deleted
        :type username: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/user/{username}'
        path_format_arguments = {
            'username': self._serialize.url("username", username, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.delete(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [404, 400]:
            raise HttpOperationError(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response
class CdnManagementClient(object):
    """Use these APIs to manage Azure CDN resources through the Azure Resource Manager. You must make sure that requests made to these resources are secure.

    :ivar config: Configuration for client.
    :vartype config: CdnManagementClientConfiguration

    :ivar profiles: Profiles operations
    :vartype profiles: azure.mgmt.cdn.operations.ProfilesOperations
    :ivar endpoints: Endpoints operations
    :vartype endpoints: azure.mgmt.cdn.operations.EndpointsOperations
    :ivar origins: Origins operations
    :vartype origins: azure.mgmt.cdn.operations.OriginsOperations
    :ivar custom_domains: CustomDomains operations
    :vartype custom_domains: azure.mgmt.cdn.operations.CustomDomainsOperations
    :ivar resource_usage: ResourceUsage operations
    :vartype resource_usage: azure.mgmt.cdn.operations.ResourceUsageOperations
    :ivar operations: Operations operations
    :vartype operations: azure.mgmt.cdn.operations.Operations
    :ivar edge_nodes: EdgeNodes operations
    :vartype edge_nodes: azure.mgmt.cdn.operations.EdgeNodesOperations

    :param credentials: Credentials needed for the client to connect to Azure.
    :type credentials: :mod:`A msrestazure Credentials
     object<msrestazure.azure_active_directory>`
    :param subscription_id: Azure Subscription ID.
    :type subscription_id: str
    :param str base_url: Service URL
    """

    def __init__(
            self, credentials, subscription_id, base_url=None):

        self.config = CdnManagementClientConfiguration(credentials, subscription_id, base_url)
        self._client = ServiceClient(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self.api_version = '2017-04-02'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

        self.profiles = ProfilesOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.endpoints = EndpointsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.origins = OriginsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.custom_domains = CustomDomainsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.resource_usage = ResourceUsageOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.operations = Operations(
            self._client, self.config, self._serialize, self._deserialize)
        self.edge_nodes = EdgeNodesOperations(
            self._client, self.config, self._serialize, self._deserialize)

    def check_name_availability(
            self, name, custom_headers=None, raw=False, **operation_config):
        """Check the availability of a resource name. This is needed for resources
        where name is globally unique, such as a CDN endpoint.

        :param name: The resource name to validate.
        :type name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: CheckNameAvailabilityOutput or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.cdn.models.ErrorResponseException>`
        """
        check_name_availability_input = models.CheckNameAvailabilityInput(name=name)

        # Construct URL
        url = self.check_name_availability.metadata['url']

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(check_name_availability_input, 'CheckNameAvailabilityInput')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('CheckNameAvailabilityOutput', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    check_name_availability.metadata = {'url': '/providers/Microsoft.Cdn/checkNameAvailability'}

    def validate_probe(
            self, probe_url, custom_headers=None, raw=False, **operation_config):
        """Check if the probe path is a valid path and the file can be accessed.
        Probe path is the path to a file hosted on the origin server to help
        accelerate the delivery of dynamic content via the CDN endpoint. This
        path is relative to the origin path specified in the endpoint
        configuration.

        :param probe_url: The probe URL to validate.
        :type probe_url: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ValidateProbeOutput or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.cdn.models.ValidateProbeOutput or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.cdn.models.ErrorResponseException>`
        """
        validate_probe_input = models.ValidateProbeInput(probe_url=probe_url)

        # Construct URL
        url = self.validate_probe.metadata['url']
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(validate_probe_input, 'ValidateProbeInput')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ValidateProbeOutput', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    validate_probe.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateProbe'}
class AutoRestResourceFlatteningTestService(object):
    """Resource Flattening for AutoRest

    :param config: Configuration for client.
    :type config: AutoRestResourceFlatteningTestServiceConfiguration
    """

    def __init__(self, config):

        self._client = ServiceClient(None, config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self._serialize = Serializer()
        self._deserialize = Deserializer(client_models)

        self.config = config

    def put_array(
            self, resource_array=None, custom_headers={}, raw=False, **operation_config):
        """
        Put External Resource as an Array

        :param resource_array: External Resource as an Array to put
        :type resource_array: list of :class:`Resource
         <fixtures.acceptancetestsmodelflattening.models.Resource>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/model-flatten/array'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if resource_array is not None:
            body_content = self._serialize.body(resource_array, '[Resource]')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def get_array(
            self, custom_headers={}, raw=False, **operation_config):
        """
        Get External Resource as an Array

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: list of :class:`FlattenedProduct
         <fixtures.acceptancetestsmodelflattening.models.FlattenedProduct>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/model-flatten/array'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('[FlattenedProduct]', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def put_dictionary(
            self, resource_dictionary=None, custom_headers={}, raw=False, **operation_config):
        """
        Put External Resource as a Dictionary

        :param resource_dictionary: External Resource as a Dictionary to put
        :type resource_dictionary: dict
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/model-flatten/dictionary'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if resource_dictionary is not None:
            body_content = self._serialize.body(resource_dictionary, '{FlattenedProduct}')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def get_dictionary(
            self, custom_headers={}, raw=False, **operation_config):
        """
        Get External Resource as a Dictionary

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: dict
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/model-flatten/dictionary'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('{FlattenedProduct}', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def put_resource_collection(
            self, resource_complex_object=None, custom_headers={}, raw=False, **operation_config):
        """
        Put External Resource as a ResourceCollection

        :param resource_complex_object: External Resource as a
         ResourceCollection to put
        :type resource_complex_object: :class:`ResourceCollection
         <fixtures.acceptancetestsmodelflattening.models.ResourceCollection>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/model-flatten/resourcecollection'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if resource_complex_object is not None:
            body_content = self._serialize.body(resource_complex_object, 'ResourceCollection')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def get_resource_collection(
            self, custom_headers={}, raw=False, **operation_config):
        """
        Get External Resource as a ResourceCollection

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`ResourceCollection
         <fixtures.acceptancetestsmodelflattening.models.ResourceCollection>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/model-flatten/resourcecollection'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ResourceCollection', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def put_simple_product(
            self, simple_body_product=None, custom_headers={}, raw=False, **operation_config):
        """
        Put Simple Product with client flattening true on the model

        :param simple_body_product: Simple body product to put
        :type simple_body_product: :class:`SimpleProduct
         <fixtures.acceptancetestsmodelflattening.models.SimpleProduct>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`SimpleProduct
         <fixtures.acceptancetestsmodelflattening.models.SimpleProduct>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/model-flatten/customFlattening'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if simple_body_product is not None:
            body_content = self._serialize.body(simple_body_product, 'SimpleProduct')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('SimpleProduct', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def post_flattened_simple_product(
            self, product_id, max_product_display_name, description=None, odatavalue=None, custom_headers={}, raw=False, **operation_config):
        """
        Put Flattened Simple Product with client flattening true on the
        parameter

        :param product_id: Unique identifier representing a specific product
         for a given latitude & longitude. For example, uberX in San
         Francisco will have a different product_id than uberX in Los Angeles.
        :type product_id: str
        :param max_product_display_name: Display name of product.
        :type max_product_display_name: str
        :param description: Description of product.
        :type description: str
        :param odatavalue: URL value.
        :type odatavalue: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`SimpleProduct
         <fixtures.acceptancetestsmodelflattening.models.SimpleProduct>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        simple_body_product = models.SimpleProduct(product_id=product_id, description=description, max_product_display_name=max_product_display_name, odatavalue=odatavalue)

        # Construct URL
        url = '/model-flatten/customFlattening'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if simple_body_product is not None:
            body_content = self._serialize.body(simple_body_product, 'SimpleProduct')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('SimpleProduct', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def put_simple_product_with_grouping(
            self, flatten_parameter_group, custom_headers={}, raw=False, **operation_config):
        """
        Put Simple Product with client flattening true on the model

        :param flatten_parameter_group: Additional parameters for the
         operation
        :type flatten_parameter_group: :class:`FlattenParameterGroup
         <fixtures.acceptancetestsmodelflattening.models.FlattenParameterGroup>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`SimpleProduct
         <fixtures.acceptancetestsmodelflattening.models.SimpleProduct>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        name = None
        if flatten_parameter_group is not None:
            name = flatten_parameter_group.name
        product_id = None
        if flatten_parameter_group is not None:
            product_id = flatten_parameter_group.product_id
        description = None
        if flatten_parameter_group is not None:
            description = flatten_parameter_group.description
        max_product_display_name = None
        if flatten_parameter_group is not None:
            max_product_display_name = flatten_parameter_group.max_product_display_name
        odatavalue = None
        if flatten_parameter_group is not None:
            odatavalue = flatten_parameter_group.odatavalue
        simple_body_product = models.SimpleProduct(product_id=product_id, description=description, max_product_display_name=max_product_display_name, odatavalue=odatavalue)

        # Construct URL
        url = '/model-flatten/customFlattening/parametergrouping/{name}/'
        path_format_arguments = {
            'name': self._serialize.url("name", name, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if simple_body_product is not None:
            body_content = self._serialize.body(simple_body_product, 'SimpleProduct')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('SimpleProduct', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
Ejemplo n.º 45
0
class UPackPackagingClient(Client):
    """UPackPackaging
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """
    def __init__(self, base_url=None, creds=None):
        super(UPackPackagingClient, self).__init__(base_url, creds)
        client_models = {
            k: v
            for k, v in models.__dict__.items() if isinstance(v, type)
        }
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = 'd397749b-f115-4027-b6dd-77a65dd10d21'

    def add_package(self, metadata, feed_id, package_name, package_version):
        """AddPackage.
        [Preview API]
        :param :class:`<UPackPackagePushMetadata> <azure.devops.v5_1.upack_packaging.models.UPackPackagePushMetadata>` metadata:
        :param str feed_id:
        :param str package_name:
        :param str package_version:
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url(
                'feed_id', feed_id, 'str')
        if package_name is not None:
            route_values['packageName'] = self._serialize.url(
                'package_name', package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url(
                'package_version', package_version, 'str')
        content = self._serialize.body(metadata, 'UPackPackagePushMetadata')
        self._send(http_method='PUT',
                   location_id='4cdb2ced-0758-4651-8032-010f070dd7e5',
                   version='5.1-preview.1',
                   route_values=route_values,
                   content=content)

    def get_package_metadata(self,
                             feed_id,
                             package_name,
                             package_version,
                             intent=None):
        """GetPackageMetadata.
        [Preview API]
        :param str feed_id:
        :param str package_name:
        :param str package_version:
        :param str intent:
        :rtype: :class:`<UPackPackageMetadata> <azure.devops.v5_1.upack_packaging.models.UPackPackageMetadata>`
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url(
                'feed_id', feed_id, 'str')
        if package_name is not None:
            route_values['packageName'] = self._serialize.url(
                'package_name', package_name, 'str')
        if package_version is not None:
            route_values['packageVersion'] = self._serialize.url(
                'package_version', package_version, 'str')
        query_parameters = {}
        if intent is not None:
            query_parameters['intent'] = self._serialize.query(
                'intent', intent, 'str')
        response = self._send(
            http_method='GET',
            location_id='4cdb2ced-0758-4651-8032-010f070dd7e5',
            version='5.1-preview.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('UPackPackageMetadata', response)

    def get_package_versions_metadata(self, feed_id, package_name):
        """GetPackageVersionsMetadata.
        [Preview API]
        :param str feed_id:
        :param str package_name:
        :rtype: :class:`<UPackLimitedPackageMetadataListResponse> <azure.devops.v5_1.upack_packaging.models.UPackLimitedPackageMetadataListResponse>`
        """
        route_values = {}
        if feed_id is not None:
            route_values['feedId'] = self._serialize.url(
                'feed_id', feed_id, 'str')
        if package_name is not None:
            route_values['packageName'] = self._serialize.url(
                'package_name', package_name, 'str')
        response = self._send(
            http_method='GET',
            location_id='4cdb2ced-0758-4651-8032-010f070dd7e5',
            version='5.1-preview.1',
            route_values=route_values)
        return self._deserialize('UPackLimitedPackageMetadataListResponse',
                                 response)
class ManagementGroupsAPI(SDKClient):
    """The Azure Management Groups API enables consolidation of multiple subscriptions/resources into an organizational hierarchy and centrally manage access control, policies, alerting and reporting for those resources.

    :ivar config: Configuration for client.
    :vartype config: ManagementGroupsAPIConfiguration

    :ivar management_groups: ManagementGroups operations
    :vartype management_groups: azure.mgmt.managementgroups.operations.ManagementGroupsOperations
    :ivar management_group_subscriptions: ManagementGroupSubscriptions operations
    :vartype management_group_subscriptions: azure.mgmt.managementgroups.operations.ManagementGroupSubscriptionsOperations
    :ivar operations: Operations operations
    :vartype operations: azure.mgmt.managementgroups.operations.Operations
    :ivar entities: Entities operations
    :vartype entities: azure.mgmt.managementgroups.operations.EntitiesOperations

    :param credentials: Credentials needed for the client to connect to Azure.
    :type credentials: :mod:`A msrestazure Credentials
     object<msrestazure.azure_active_directory>`
    :param str base_url: Service URL
    """

    def __init__(
            self, credentials, base_url=None):

        self.config = ManagementGroupsAPIConfiguration(credentials, base_url)
        super(ManagementGroupsAPI, self).__init__(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self.api_version = '2018-03-01-preview'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

        self.management_groups = ManagementGroupsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.management_group_subscriptions = ManagementGroupSubscriptionsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.operations = Operations(
            self._client, self.config, self._serialize, self._deserialize)
        self.entities = EntitiesOperations(
            self._client, self.config, self._serialize, self._deserialize)

    def check_name_availability(
            self, check_name_availability_request, custom_headers=None, raw=False, **operation_config):
        """Checks if the specified management group name is valid and unique.

        :param check_name_availability_request: Management group name
         availability check parameters.
        :type check_name_availability_request:
         ~azure.mgmt.managementgroups.models.CheckNameAvailabilityRequest
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: CheckNameAvailabilityResult or ClientRawResponse if raw=true
        :rtype:
         ~azure.mgmt.managementgroups.models.CheckNameAvailabilityResult or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.managementgroups.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.check_name_availability.metadata['url']

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(check_name_availability_request, 'CheckNameAvailabilityRequest')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('CheckNameAvailabilityResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    check_name_availability.metadata = {'url': '/providers/Microsoft.Management/checkNameAvailability'}

    def start_tenant_backfill(
            self, custom_headers=None, raw=False, **operation_config):
        """Starts backfilling subscriptions for the Tenant.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: TenantBackfillStatusResult or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.managementgroups.models.TenantBackfillStatusResult
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.managementgroups.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.start_tenant_backfill.metadata['url']

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('TenantBackfillStatusResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    start_tenant_backfill.metadata = {'url': '/providers/Microsoft.Management/startTenantBackfill'}

    def tenant_backfill_status(
            self, custom_headers=None, raw=False, **operation_config):
        """Gets tenant backfill status.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: TenantBackfillStatusResult or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.managementgroups.models.TenantBackfillStatusResult
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.managementgroups.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.tenant_backfill_status.metadata['url']

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('TenantBackfillStatusResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    tenant_backfill_status.metadata = {'url': '/providers/Microsoft.Management/tenantBackfillStatus'}
class FrontDoorManagementClient(SDKClient):
    """FrontDoor Client

    :ivar config: Configuration for client.
    :vartype config: FrontDoorManagementClientConfiguration

    :ivar front_doors: FrontDoors operations
    :vartype front_doors: azure.mgmt.frontdoor.operations.FrontDoorsOperations
    :ivar routing_rules: RoutingRules operations
    :vartype routing_rules: azure.mgmt.frontdoor.operations.RoutingRulesOperations
    :ivar health_probe_settings: HealthProbeSettings operations
    :vartype health_probe_settings: azure.mgmt.frontdoor.operations.HealthProbeSettingsOperations
    :ivar load_balancing_settings: LoadBalancingSettings operations
    :vartype load_balancing_settings: azure.mgmt.frontdoor.operations.LoadBalancingSettingsOperations
    :ivar backend_pools: BackendPools operations
    :vartype backend_pools: azure.mgmt.frontdoor.operations.BackendPoolsOperations
    :ivar frontend_endpoints: FrontendEndpoints operations
    :vartype frontend_endpoints: azure.mgmt.frontdoor.operations.FrontendEndpointsOperations
    :ivar endpoints: Endpoints operations
    :vartype endpoints: azure.mgmt.frontdoor.operations.EndpointsOperations
    :ivar policies: Policies operations
    :vartype policies: azure.mgmt.frontdoor.operations.PoliciesOperations

    :param credentials: Credentials needed for the client to connect to Azure.
    :type credentials: :mod:`A msrestazure Credentials
     object<msrestazure.azure_active_directory>`
    :param subscription_id: The subscription credentials which uniquely
     identify the Microsoft Azure subscription. The subscription ID forms part
     of the URI for every service call.
    :type subscription_id: str
    :param str base_url: Service URL
    """

    def __init__(
            self, credentials, subscription_id, base_url=None):

        self.config = FrontDoorManagementClientConfiguration(credentials, subscription_id, base_url)
        super(FrontDoorManagementClient, self).__init__(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

        self.front_doors = FrontDoorsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.routing_rules = RoutingRulesOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.health_probe_settings = HealthProbeSettingsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.load_balancing_settings = LoadBalancingSettingsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.backend_pools = BackendPoolsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.frontend_endpoints = FrontendEndpointsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.endpoints = EndpointsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.policies = PoliciesOperations(
            self._client, self.config, self._serialize, self._deserialize)

    def check_front_door_name_availability(
            self, name, type, custom_headers=None, raw=False, **operation_config):
        """Check the availability of a Front Door resource name.

        :param name: The resource name to validate.
        :type name: str
        :param type: The type of the resource whose name is to be validated.
         Possible values include: 'Microsoft.Network/frontDoors',
         'Microsoft.Network/frontDoors/frontendEndpoints'
        :type type: str or ~azure.mgmt.frontdoor.models.ResourceType
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: CheckNameAvailabilityOutput or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.frontdoor.models.CheckNameAvailabilityOutput or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.frontdoor.models.ErrorResponseException>`
        """
        check_front_door_name_availability_input = models.CheckNameAvailabilityInput(name=name, type=type)

        api_version = "2018-08-01"

        # Construct URL
        url = self.check_front_door_name_availability.metadata['url']

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(check_front_door_name_availability_input, 'CheckNameAvailabilityInput')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('CheckNameAvailabilityOutput', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    check_front_door_name_availability.metadata = {'url': '/providers/Microsoft.Network/checkFrontDoorNameAvailability'}

    def check_front_door_name_availability_with_subscription(
            self, name, type, custom_headers=None, raw=False, **operation_config):
        """Check the availability of a Front Door subdomain.

        :param name: The resource name to validate.
        :type name: str
        :param type: The type of the resource whose name is to be validated.
         Possible values include: 'Microsoft.Network/frontDoors',
         'Microsoft.Network/frontDoors/frontendEndpoints'
        :type type: str or ~azure.mgmt.frontdoor.models.ResourceType
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: CheckNameAvailabilityOutput or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.frontdoor.models.CheckNameAvailabilityOutput or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.frontdoor.models.ErrorResponseException>`
        """
        check_front_door_name_availability_input = models.CheckNameAvailabilityInput(name=name, type=type)

        api_version = "2018-08-01"

        # Construct URL
        url = self.check_front_door_name_availability_with_subscription.metadata['url']
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(check_front_door_name_availability_input, 'CheckNameAvailabilityInput')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('CheckNameAvailabilityOutput', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    check_front_door_name_availability_with_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/checkFrontDoorNameAvailability'}
Ejemplo n.º 48
0
class SecurityClient(VssClient):
    """Security
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """
    def __init__(self, base_url=None, creds=None):
        super(SecurityClient, self).__init__(base_url, creds)
        client_models = {
            k: v
            for k, v in models.__dict__.items() if isinstance(v, type)
        }
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = None

    def remove_access_control_entries(self,
                                      security_namespace_id,
                                      token=None,
                                      descriptors=None):
        """RemoveAccessControlEntries.
        [Preview API] Remove the specified ACEs from the ACL belonging to the specified token.
        :param str security_namespace_id:
        :param str token:
        :param str descriptors:
        :rtype: bool
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        query_parameters = {}
        if token is not None:
            query_parameters['token'] = self._serialize.query(
                'token', token, 'str')
        if descriptors is not None:
            query_parameters['descriptors'] = self._serialize.query(
                'descriptors', descriptors, 'str')
        response = self._send(
            http_method='DELETE',
            location_id='ac08c8ff-4323-4b08-af90-bcd018d380ce',
            version='4.1-preview.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('bool', response)

    def set_access_control_entries(self, container, security_namespace_id):
        """SetAccessControlEntries.
        [Preview API] Add or update ACEs in the ACL for the provided token. In the case of a collision (by identity descriptor) with an existing ACE in the ACL, the "merge" parameter determines the behavior. If set, the existing ACE has its allow and deny merged with the incoming ACE's allow and deny. If unset, the existing ACE is displaced.
        :param :class:`<object> <security.v4_1.models.object>` container:
        :param str security_namespace_id:
        :rtype: [AccessControlEntry]
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        content = self._serialize.body(container, 'object')
        response = self._send(
            http_method='POST',
            location_id='ac08c8ff-4323-4b08-af90-bcd018d380ce',
            version='4.1-preview.1',
            route_values=route_values,
            content=content,
            returns_collection=True)
        return self._deserialize('[AccessControlEntry]', response)

    def query_access_control_lists(self,
                                   security_namespace_id,
                                   token=None,
                                   descriptors=None,
                                   include_extended_info=None,
                                   recurse=None):
        """QueryAccessControlLists.
        [Preview API] Return a list of access control lists for the specified security namespace and token.
        :param str security_namespace_id: Security namespace identifier.
        :param str token: Security token
        :param str descriptors:
        :param bool include_extended_info: If true, populate the extended information properties for the access control entries contained in the returned lists.
        :param bool recurse: If true and this is a hierarchical namespace, return child ACLs of the specified token.
        :rtype: [AccessControlList]
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        query_parameters = {}
        if token is not None:
            query_parameters['token'] = self._serialize.query(
                'token', token, 'str')
        if descriptors is not None:
            query_parameters['descriptors'] = self._serialize.query(
                'descriptors', descriptors, 'str')
        if include_extended_info is not None:
            query_parameters['includeExtendedInfo'] = self._serialize.query(
                'include_extended_info', include_extended_info, 'bool')
        if recurse is not None:
            query_parameters['recurse'] = self._serialize.query(
                'recurse', recurse, 'bool')
        response = self._send(
            http_method='GET',
            location_id='18a2ad18-7571-46ae-bec7-0c7da1495885',
            version='4.1-preview.1',
            route_values=route_values,
            query_parameters=query_parameters,
            returns_collection=True)
        return self._deserialize('[AccessControlList]', response)

    def remove_access_control_lists(self,
                                    security_namespace_id,
                                    tokens=None,
                                    recurse=None):
        """RemoveAccessControlLists.
        [Preview API] Remove access control lists under the specfied security namespace.
        :param str security_namespace_id: Security namespace identifier.
        :param str tokens: One or more comma-separated security tokens
        :param bool recurse: If true and this is a hierarchical namespace, also remove child ACLs of the specified tokens.
        :rtype: bool
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        query_parameters = {}
        if tokens is not None:
            query_parameters['tokens'] = self._serialize.query(
                'tokens', tokens, 'str')
        if recurse is not None:
            query_parameters['recurse'] = self._serialize.query(
                'recurse', recurse, 'bool')
        response = self._send(
            http_method='DELETE',
            location_id='18a2ad18-7571-46ae-bec7-0c7da1495885',
            version='4.1-preview.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('bool', response)

    def set_access_control_lists(self, access_control_lists,
                                 security_namespace_id):
        """SetAccessControlLists.
        [Preview API] Create one or more access control lists.
        :param :class:`<VssJsonCollectionWrapper> <security.v4_1.models.VssJsonCollectionWrapper>` access_control_lists:
        :param str security_namespace_id: Security namespace identifier.
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        content = self._serialize.body(access_control_lists,
                                       'VssJsonCollectionWrapper')
        self._send(http_method='POST',
                   location_id='18a2ad18-7571-46ae-bec7-0c7da1495885',
                   version='4.1-preview.1',
                   route_values=route_values,
                   content=content)

    def has_permissions_batch(self, eval_batch):
        """HasPermissionsBatch.
        [Preview API] Evaluates multiple permissions for the callign user.  Note: This methods does not aggregate the results nor does it short-circut if one of the permissions evaluates to false.
        :param :class:`<PermissionEvaluationBatch> <security.v4_1.models.PermissionEvaluationBatch>` eval_batch: The set of permissions to check.
        :rtype: :class:`<PermissionEvaluationBatch> <security.v4_1.models.PermissionEvaluationBatch>`
        """
        content = self._serialize.body(eval_batch, 'PermissionEvaluationBatch')
        response = self._send(
            http_method='POST',
            location_id='cf1faa59-1b63-4448-bf04-13d981a46f5d',
            version='4.1-preview.1',
            content=content)
        return self._deserialize('PermissionEvaluationBatch', response)

    def has_permissions(self,
                        security_namespace_id,
                        permissions=None,
                        tokens=None,
                        always_allow_administrators=None,
                        delimiter=None):
        """HasPermissions.
        [Preview API] Evaluates whether the caller has the specified permissions on the specified set of security tokens.
        :param str security_namespace_id: Security namespace identifier.
        :param int permissions: Permissions to evaluate.
        :param str tokens: One or more security tokens to evaluate.
        :param bool always_allow_administrators: If true and if the caller is an administrator, always return true.
        :param str delimiter: Optional security token separator. Defaults to ",".
        :rtype: [bool]
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        if permissions is not None:
            route_values['permissions'] = self._serialize.url(
                'permissions', permissions, 'int')
        query_parameters = {}
        if tokens is not None:
            query_parameters['tokens'] = self._serialize.query(
                'tokens', tokens, 'str')
        if always_allow_administrators is not None:
            query_parameters[
                'alwaysAllowAdministrators'] = self._serialize.query(
                    'always_allow_administrators', always_allow_administrators,
                    'bool')
        if delimiter is not None:
            query_parameters['delimiter'] = self._serialize.query(
                'delimiter', delimiter, 'str')
        response = self._send(
            http_method='GET',
            location_id='dd3b8bd6-c7fc-4cbd-929a-933d9c011c9d',
            version='4.1-preview.2',
            route_values=route_values,
            query_parameters=query_parameters,
            returns_collection=True)
        return self._deserialize('[bool]', response)

    def remove_permission(self,
                          security_namespace_id,
                          permissions=None,
                          token=None,
                          descriptor=None):
        """RemovePermission.
        [Preview API] Removes the specified permissions from the caller or specified user or group.
        :param str security_namespace_id: Security namespace identifier.
        :param int permissions: Permissions to remove.
        :param str token: Security token to remove permissions for.
        :param str descriptor: Identity descriptor of the user to remove permissions for. Defaults to the caller.
        :rtype: :class:`<AccessControlEntry> <security.v4_1.models.AccessControlEntry>`
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        if permissions is not None:
            route_values['permissions'] = self._serialize.url(
                'permissions', permissions, 'int')
        query_parameters = {}
        if token is not None:
            query_parameters['token'] = self._serialize.query(
                'token', token, 'str')
        if descriptor is not None:
            query_parameters['descriptor'] = self._serialize.query(
                'descriptor', descriptor, 'str')
        response = self._send(
            http_method='DELETE',
            location_id='dd3b8bd6-c7fc-4cbd-929a-933d9c011c9d',
            version='4.1-preview.2',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('AccessControlEntry', response)

    def query_security_namespaces(self,
                                  security_namespace_id,
                                  local_only=None):
        """QuerySecurityNamespaces.
        [Preview API]
        :param str security_namespace_id:
        :param bool local_only:
        :rtype: [SecurityNamespaceDescription]
        """
        route_values = {}
        if security_namespace_id is not None:
            route_values['securityNamespaceId'] = self._serialize.url(
                'security_namespace_id', security_namespace_id, 'str')
        query_parameters = {}
        if local_only is not None:
            query_parameters['localOnly'] = self._serialize.query(
                'local_only', local_only, 'bool')
        response = self._send(
            http_method='GET',
            location_id='ce7b9f95-fde9-4be8-a86d-83b366f0b87a',
            version='4.1-preview.1',
            route_values=route_values,
            query_parameters=query_parameters,
            returns_collection=True)
        return self._deserialize('[SecurityNamespaceDescription]', response)
Ejemplo n.º 49
0
class MemberEntitlementManagementClient(Client):
    """MemberEntitlementManagement
    :param str base_url: Service URL
    :param Authentication creds: Authenticated credentials.
    """
    def __init__(self, base_url=None, creds=None):
        super(MemberEntitlementManagementClient,
              self).__init__(base_url, creds)
        client_models = {
            k: v
            for k, v in models.__dict__.items() if isinstance(v, type)
        }
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

    resource_area_identifier = '68ddce18-2501-45f1-a17b-7931a9922690'

    def add_group_entitlement(self, group_entitlement, rule_option=None):
        """AddGroupEntitlement.
        [Preview API] Create a group entitlement with license rule, extension rule.
        :param :class:`<GroupEntitlement> <azure.devops.v5_1.member_entitlement_management.models.GroupEntitlement>` group_entitlement: GroupEntitlement object specifying License Rule, Extensions Rule for the group. Based on the rules the members of the group will be given licenses and extensions. The Group Entitlement can be used to add the group to another project level groups
        :param str rule_option: RuleOption [ApplyGroupRule/TestApplyGroupRule] - specifies if the rules defined in group entitlement should be created and applied to it’s members (default option) or just be tested
        :rtype: :class:`<GroupEntitlementOperationReference> <azure.devops.v5_1.member_entitlement_management.models.GroupEntitlementOperationReference>`
        """
        query_parameters = {}
        if rule_option is not None:
            query_parameters['ruleOption'] = self._serialize.query(
                'rule_option', rule_option, 'str')
        content = self._serialize.body(group_entitlement, 'GroupEntitlement')
        response = self._send(
            http_method='POST',
            location_id='2280bffa-58a2-49da-822e-0764a1bb44f7',
            version='5.1-preview.1',
            query_parameters=query_parameters,
            content=content)
        return self._deserialize('GroupEntitlementOperationReference',
                                 response)

    def delete_group_entitlement(self,
                                 group_id,
                                 rule_option=None,
                                 remove_group_membership=None):
        """DeleteGroupEntitlement.
        [Preview API] Delete a group entitlement.
        :param str group_id: ID of the group to delete.
        :param str rule_option: RuleOption [ApplyGroupRule/TestApplyGroupRule] - specifies if the rules defined in group entitlement should be deleted and the changes are applied to it’s members (default option) or just be tested
        :param bool remove_group_membership: Optional parameter that specifies whether the group with the given ID should be removed from all other groups
        :rtype: :class:`<GroupEntitlementOperationReference> <azure.devops.v5_1.member_entitlement_management.models.GroupEntitlementOperationReference>`
        """
        route_values = {}
        if group_id is not None:
            route_values['groupId'] = self._serialize.url(
                'group_id', group_id, 'str')
        query_parameters = {}
        if rule_option is not None:
            query_parameters['ruleOption'] = self._serialize.query(
                'rule_option', rule_option, 'str')
        if remove_group_membership is not None:
            query_parameters['removeGroupMembership'] = self._serialize.query(
                'remove_group_membership', remove_group_membership, 'bool')
        response = self._send(
            http_method='DELETE',
            location_id='2280bffa-58a2-49da-822e-0764a1bb44f7',
            version='5.1-preview.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('GroupEntitlementOperationReference',
                                 response)

    def get_group_entitlement(self, group_id):
        """GetGroupEntitlement.
        [Preview API] Get a group entitlement.
        :param str group_id: ID of the group.
        :rtype: :class:`<GroupEntitlement> <azure.devops.v5_1.member_entitlement_management.models.GroupEntitlement>`
        """
        route_values = {}
        if group_id is not None:
            route_values['groupId'] = self._serialize.url(
                'group_id', group_id, 'str')
        response = self._send(
            http_method='GET',
            location_id='2280bffa-58a2-49da-822e-0764a1bb44f7',
            version='5.1-preview.1',
            route_values=route_values)
        return self._deserialize('GroupEntitlement', response)

    def get_group_entitlements(self):
        """GetGroupEntitlements.
        [Preview API] Get the group entitlements for an account.
        :rtype: [GroupEntitlement]
        """
        response = self._send(
            http_method='GET',
            location_id='2280bffa-58a2-49da-822e-0764a1bb44f7',
            version='5.1-preview.1')
        return self._deserialize('[GroupEntitlement]',
                                 self._unwrap_collection(response))

    def update_group_entitlement(self, document, group_id, rule_option=None):
        """UpdateGroupEntitlement.
        [Preview API] Update entitlements (License Rule, Extensions Rule, Project memberships etc.) for a group.
        :param :class:`<[JsonPatchOperation]> <azure.devops.v5_1.member_entitlement_management.models.[JsonPatchOperation]>` document: JsonPatchDocument containing the operations to perform on the group.
        :param str group_id: ID of the group.
        :param str rule_option: RuleOption [ApplyGroupRule/TestApplyGroupRule] - specifies if the rules defined in group entitlement should be updated and the changes are applied to it’s members (default option) or just be tested
        :rtype: :class:`<GroupEntitlementOperationReference> <azure.devops.v5_1.member_entitlement_management.models.GroupEntitlementOperationReference>`
        """
        route_values = {}
        if group_id is not None:
            route_values['groupId'] = self._serialize.url(
                'group_id', group_id, 'str')
        query_parameters = {}
        if rule_option is not None:
            query_parameters['ruleOption'] = self._serialize.query(
                'rule_option', rule_option, 'str')
        content = self._serialize.body(document, '[JsonPatchOperation]')
        response = self._send(
            http_method='PATCH',
            location_id='2280bffa-58a2-49da-822e-0764a1bb44f7',
            version='5.1-preview.1',
            route_values=route_values,
            query_parameters=query_parameters,
            content=content,
            media_type='application/json-patch+json')
        return self._deserialize('GroupEntitlementOperationReference',
                                 response)

    def add_member_to_group(self, group_id, member_id):
        """AddMemberToGroup.
        [Preview API] Add a member to a Group.
        :param str group_id: Id of the Group.
        :param str member_id: Id of the member to add.
        """
        route_values = {}
        if group_id is not None:
            route_values['groupId'] = self._serialize.url(
                'group_id', group_id, 'str')
        if member_id is not None:
            route_values['memberId'] = self._serialize.url(
                'member_id', member_id, 'str')
        self._send(http_method='PUT',
                   location_id='45a36e53-5286-4518-aa72-2d29f7acc5d8',
                   version='5.1-preview.1',
                   route_values=route_values)

    def get_group_members(self, group_id, max_results=None, paging_token=None):
        """GetGroupMembers.
        [Preview API] Get direct members of a Group.
        :param str group_id: Id of the Group.
        :param int max_results: Maximum number of results to retrieve.
        :param str paging_token: Paging Token from the previous page fetched. If the 'pagingToken' is null, the results would be fetched from the begining of the Members List.
        :rtype: :class:`<PagedGraphMemberList> <azure.devops.v5_1.member_entitlement_management.models.PagedGraphMemberList>`
        """
        route_values = {}
        if group_id is not None:
            route_values['groupId'] = self._serialize.url(
                'group_id', group_id, 'str')
        query_parameters = {}
        if max_results is not None:
            query_parameters['maxResults'] = self._serialize.query(
                'max_results', max_results, 'int')
        if paging_token is not None:
            query_parameters['pagingToken'] = self._serialize.query(
                'paging_token', paging_token, 'str')
        response = self._send(
            http_method='GET',
            location_id='45a36e53-5286-4518-aa72-2d29f7acc5d8',
            version='5.1-preview.1',
            route_values=route_values,
            query_parameters=query_parameters)
        return self._deserialize('PagedGraphMemberList', response)

    def remove_member_from_group(self, group_id, member_id):
        """RemoveMemberFromGroup.
        [Preview API] Remove a member from a Group.
        :param str group_id: Id of the group.
        :param str member_id: Id of the member to remove.
        """
        route_values = {}
        if group_id is not None:
            route_values['groupId'] = self._serialize.url(
                'group_id', group_id, 'str')
        if member_id is not None:
            route_values['memberId'] = self._serialize.url(
                'member_id', member_id, 'str')
        self._send(http_method='DELETE',
                   location_id='45a36e53-5286-4518-aa72-2d29f7acc5d8',
                   version='5.1-preview.1',
                   route_values=route_values)

    def add_user_entitlement(self, user_entitlement):
        """AddUserEntitlement.
        [Preview API] Add a user, assign license and extensions and make them a member of a project group in an account.
        :param :class:`<UserEntitlement> <azure.devops.v5_1.member_entitlement_management.models.UserEntitlement>` user_entitlement: UserEntitlement object specifying License, Extensions and Project/Team groups the user should be added to.
        :rtype: :class:`<UserEntitlementsPostResponse> <azure.devops.v5_1.member_entitlement_management.models.UserEntitlementsPostResponse>`
        """
        content = self._serialize.body(user_entitlement, 'UserEntitlement')
        response = self._send(
            http_method='POST',
            location_id='387f832c-dbf2-4643-88e9-c1aa94dbb737',
            version='5.1-preview.2',
            content=content)
        return self._deserialize('UserEntitlementsPostResponse', response)

    def get_user_entitlements(self,
                              top=None,
                              skip=None,
                              filter=None,
                              sort_option=None):
        """GetUserEntitlements.
        [Preview API] Get a paged set of user entitlements matching the filter criteria. If no filter is is passed, a page from all the account users is returned.
        :param int top: Maximum number of the user entitlements to return. Max value is 10000. Default value is 100
        :param int skip: Offset: Number of records to skip. Default value is 0
        :param str filter: Comma (",") separated list of properties and their values to filter on. Currently, the API only supports filtering by ExtensionId. An example parameter would be filter=extensionId eq search.
        :param str sort_option: PropertyName and Order (separated by a space ( )) to sort on (e.g. LastAccessDate Desc)
        :rtype: :class:`<PagedGraphMemberList> <azure.devops.v5_1.member_entitlement_management.models.PagedGraphMemberList>`
        """
        query_parameters = {}
        if top is not None:
            query_parameters['top'] = self._serialize.query('top', top, 'int')
        if skip is not None:
            query_parameters['skip'] = self._serialize.query(
                'skip', skip, 'int')
        if filter is not None:
            query_parameters['filter'] = self._serialize.query(
                'filter', filter, 'str')
        if sort_option is not None:
            query_parameters['sortOption'] = self._serialize.query(
                'sort_option', sort_option, 'str')
        response = self._send(
            http_method='GET',
            location_id='387f832c-dbf2-4643-88e9-c1aa94dbb737',
            version='5.1-preview.2',
            query_parameters=query_parameters)
        return self._deserialize('PagedGraphMemberList', response)

    def update_user_entitlements(self,
                                 document,
                                 do_not_send_invite_for_new_users=None):
        """UpdateUserEntitlements.
        [Preview API] Edit the entitlements (License, Extensions, Projects, Teams etc) for one or more users.
        :param :class:`<[JsonPatchOperation]> <azure.devops.v5_1.member_entitlement_management.models.[JsonPatchOperation]>` document: JsonPatchDocument containing the operations to perform.
        :param bool do_not_send_invite_for_new_users: Whether to send email invites to new users or not
        :rtype: :class:`<UserEntitlementOperationReference> <azure.devops.v5_1.member_entitlement_management.models.UserEntitlementOperationReference>`
        """
        query_parameters = {}
        if do_not_send_invite_for_new_users is not None:
            query_parameters[
                'doNotSendInviteForNewUsers'] = self._serialize.query(
                    'do_not_send_invite_for_new_users',
                    do_not_send_invite_for_new_users, 'bool')
        content = self._serialize.body(document, '[JsonPatchOperation]')
        response = self._send(
            http_method='PATCH',
            location_id='387f832c-dbf2-4643-88e9-c1aa94dbb737',
            version='5.1-preview.2',
            query_parameters=query_parameters,
            content=content,
            media_type='application/json-patch+json')
        return self._deserialize('UserEntitlementOperationReference', response)

    def delete_user_entitlement(self, user_id):
        """DeleteUserEntitlement.
        [Preview API] Delete a user from the account.
        :param str user_id: ID of the user.
        """
        route_values = {}
        if user_id is not None:
            route_values['userId'] = self._serialize.url(
                'user_id', user_id, 'str')
        self._send(http_method='DELETE',
                   location_id='8480c6eb-ce60-47e9-88df-eca3c801638b',
                   version='5.1-preview.2',
                   route_values=route_values)

    def get_user_entitlement(self, user_id):
        """GetUserEntitlement.
        [Preview API] Get User Entitlement for a user.
        :param str user_id: ID of the user.
        :rtype: :class:`<UserEntitlement> <azure.devops.v5_1.member_entitlement_management.models.UserEntitlement>`
        """
        route_values = {}
        if user_id is not None:
            route_values['userId'] = self._serialize.url(
                'user_id', user_id, 'str')
        response = self._send(
            http_method='GET',
            location_id='8480c6eb-ce60-47e9-88df-eca3c801638b',
            version='5.1-preview.2',
            route_values=route_values)
        return self._deserialize('UserEntitlement', response)

    def update_user_entitlement(self, document, user_id):
        """UpdateUserEntitlement.
        [Preview API] Edit the entitlements (License, Extensions, Projects, Teams etc) for a user.
        :param :class:`<[JsonPatchOperation]> <azure.devops.v5_1.member_entitlement_management.models.[JsonPatchOperation]>` document: JsonPatchDocument containing the operations to perform on the user.
        :param str user_id: ID of the user.
        :rtype: :class:`<UserEntitlementsPatchResponse> <azure.devops.v5_1.member_entitlement_management.models.UserEntitlementsPatchResponse>`
        """
        route_values = {}
        if user_id is not None:
            route_values['userId'] = self._serialize.url(
                'user_id', user_id, 'str')
        content = self._serialize.body(document, '[JsonPatchOperation]')
        response = self._send(
            http_method='PATCH',
            location_id='8480c6eb-ce60-47e9-88df-eca3c801638b',
            version='5.1-preview.2',
            route_values=route_values,
            content=content,
            media_type='application/json-patch+json')
        return self._deserialize('UserEntitlementsPatchResponse', response)

    def get_users_summary(self, select=None):
        """GetUsersSummary.
        [Preview API] Get summary of Licenses, Extension, Projects, Groups and their assignments in the collection.
        :param str select: Comma (",") separated list of properties to select. Supported property names are {AccessLevels, Licenses, Extensions, Projects, Groups}.
        :rtype: :class:`<UsersSummary> <azure.devops.v5_1.member_entitlement_management.models.UsersSummary>`
        """
        query_parameters = {}
        if select is not None:
            query_parameters['select'] = self._serialize.query(
                'select', select, 'str')
        response = self._send(
            http_method='GET',
            location_id='5ae55b13-c9dd-49d1-957e-6e76c152e3d9',
            version='5.1-preview.1',
            query_parameters=query_parameters)
        return self._deserialize('UsersSummary', response)
class AutoRestResourceFlatteningTestService(object):
    """Resource Flattening for AutoRest

    :ivar config: Configuration for client.
    :vartype config: AutoRestResourceFlatteningTestServiceConfiguration

    :param credentials: Credentials needed for the client to connect to Azure.
    :type credentials: :mod:`A msrestazure Credentials
     object<msrestazure.azure_active_directory>`
    :param accept_language: Gets or sets the preferred language for the
     response.
    :type accept_language: str
    :param long_running_operation_retry_timeout: Gets or sets the retry
     timeout in seconds for Long Running Operations. Default value is 30.
    :type long_running_operation_retry_timeout: int
    :param generate_client_request_id: When set to true a unique
     x-ms-client-request-id value is generated and included in each request.
     Default is true.
    :type generate_client_request_id: bool
    :param str base_url: Service URL
    :param str filepath: Existing config
    """

    def __init__(
            self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None):

        self.config = AutoRestResourceFlatteningTestServiceConfiguration(credentials, accept_language, long_running_operation_retry_timeout, generate_client_request_id, base_url, filepath)
        self._client = ServiceClient(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)


    def put_array(
            self, resource_array=None, custom_headers=None, raw=False, **operation_config):
        """Put External Resource as an Array.

        :param resource_array: External Resource as an Array to put
        :type resource_array: list of :class:`Resource
         <fixtures.acceptancetestsazureresource.models.Resource>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`ErrorException<fixtures.acceptancetestsazureresource.models.ErrorException>`
        """
        # Construct URL
        url = '/azure/resource-flatten/array'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        if resource_array is not None:
            body_content = self._serialize.body(resource_array, '[Resource]')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def get_array(
            self, custom_headers=None, raw=False, **operation_config):
        """Get External Resource as an Array.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: list of :class:`FlattenedProduct
         <fixtures.acceptancetestsazureresource.models.FlattenedProduct>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`ErrorException<fixtures.acceptancetestsazureresource.models.ErrorException>`
        """
        # Construct URL
        url = '/azure/resource-flatten/array'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('[FlattenedProduct]', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def put_dictionary(
            self, resource_dictionary=None, custom_headers=None, raw=False, **operation_config):
        """Put External Resource as a Dictionary.

        :param resource_dictionary: External Resource as a Dictionary to put
        :type resource_dictionary: dict
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`ErrorException<fixtures.acceptancetestsazureresource.models.ErrorException>`
        """
        # Construct URL
        url = '/azure/resource-flatten/dictionary'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        if resource_dictionary is not None:
            body_content = self._serialize.body(resource_dictionary, '{FlattenedProduct}')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def get_dictionary(
            self, custom_headers=None, raw=False, **operation_config):
        """Get External Resource as a Dictionary.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: dict
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`ErrorException<fixtures.acceptancetestsazureresource.models.ErrorException>`
        """
        # Construct URL
        url = '/azure/resource-flatten/dictionary'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('{FlattenedProduct}', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def put_resource_collection(
            self, resource_complex_object=None, custom_headers=None, raw=False, **operation_config):
        """Put External Resource as a ResourceCollection.

        :param resource_complex_object: External Resource as a
         ResourceCollection to put
        :type resource_complex_object: :class:`ResourceCollection
         <fixtures.acceptancetestsazureresource.models.ResourceCollection>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`ErrorException<fixtures.acceptancetestsazureresource.models.ErrorException>`
        """
        # Construct URL
        url = '/azure/resource-flatten/resourcecollection'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        if resource_complex_object is not None:
            body_content = self._serialize.body(resource_complex_object, 'ResourceCollection')
        else:
            body_content = None

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def get_resource_collection(
            self, custom_headers=None, raw=False, **operation_config):
        """Get External Resource as a ResourceCollection.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`ResourceCollection
         <fixtures.acceptancetestsazureresource.models.ResourceCollection>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`ErrorException<fixtures.acceptancetestsazureresource.models.ErrorException>`
        """
        # Construct URL
        url = '/azure/resource-flatten/resourcecollection'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ResourceCollection', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
class TextAnalyticsClient(SDKClient):
    """The Text Analytics API is a suite of text analytics web services built with best-in-class Microsoft machine learning algorithms. The API can be used to analyze unstructured text for tasks such as sentiment analysis, key phrase extraction and language detection. No training data is needed to use this API; just bring your text data. This API uses advanced natural language processing techniques to deliver best in class predictions. Further documentation can be found in https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview

    :ivar config: Configuration for client.
    :vartype config: TextAnalyticsClientConfiguration

    :param endpoint: Supported Cognitive Services endpoints (protocol and
     hostname, for example: https://westus.api.cognitive.microsoft.com).
    :type endpoint: str
    :param credentials: Subscription credentials which uniquely identify
     client subscription.
    :type credentials: None
    """

    def __init__(
            self, endpoint, credentials):

        self.config = TextAnalyticsClientConfiguration(endpoint, credentials)
        super(TextAnalyticsClient, self).__init__(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self.api_version = 'v2.1'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)


    def detect_language(
            self, show_stats=None, documents=None, custom_headers=None, raw=False, **operation_config):
        """The API returns the detected language and a numeric score between 0 and
        1.

        Scores close to 1 indicate 100% certainty that the identified language
        is true. A total of 120 languages are supported.

        :param show_stats: (optional) if set to true, response will contain
         input and document level statistics.
        :type show_stats: bool
        :param documents:
        :type documents:
         list[~azure.cognitiveservices.language.textanalytics.models.LanguageInput]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: LanguageBatchResult or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.language.textanalytics.models.LanguageBatchResult
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.language.textanalytics.models.ErrorResponseException>`
        """
        language_batch_input = None
        if documents is not None:
            language_batch_input = models.LanguageBatchInput(documents=documents)

        # Construct URL
        url = self.detect_language.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if show_stats is not None:
            query_parameters['showStats'] = self._serialize.query("show_stats", show_stats, 'bool')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if language_batch_input is not None:
            body_content = self._serialize.body(language_batch_input, 'LanguageBatchInput')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('LanguageBatchResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    detect_language.metadata = {'url': '/languages'}

    def entities(
            self, show_stats=None, documents=None, custom_headers=None, raw=False, **operation_config):
        """The API returns a list of recognized entities in a given document.

        To get even more information on each recognized entity we recommend
        using the Bing Entity Search API by querying for the recognized
        entities names. See the <a
        href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/text-analytics-supported-languages">Supported
        languages in Text Analytics API</a> for the list of enabled languages.

        :param show_stats: (optional) if set to true, response will contain
         input and document level statistics.
        :type show_stats: bool
        :param documents:
        :type documents:
         list[~azure.cognitiveservices.language.textanalytics.models.MultiLanguageInput]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: EntitiesBatchResult or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.language.textanalytics.models.EntitiesBatchResult
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.language.textanalytics.models.ErrorResponseException>`
        """
        multi_language_batch_input = None
        if documents is not None:
            multi_language_batch_input = models.MultiLanguageBatchInput(documents=documents)

        # Construct URL
        url = self.entities.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if show_stats is not None:
            query_parameters['showStats'] = self._serialize.query("show_stats", show_stats, 'bool')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if multi_language_batch_input is not None:
            body_content = self._serialize.body(multi_language_batch_input, 'MultiLanguageBatchInput')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('EntitiesBatchResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    entities.metadata = {'url': '/entities'}

    def key_phrases(
            self, show_stats=None, documents=None, custom_headers=None, raw=False, **operation_config):
        """The API returns a list of strings denoting the key talking points in
        the input text.

        See the <a
        href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
        Analytics Documentation</a> for details about the languages that are
        supported by key phrase extraction.

        :param show_stats: (optional) if set to true, response will contain
         input and document level statistics.
        :type show_stats: bool
        :param documents:
        :type documents:
         list[~azure.cognitiveservices.language.textanalytics.models.MultiLanguageInput]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: KeyPhraseBatchResult or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.language.textanalytics.models.KeyPhraseBatchResult
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.language.textanalytics.models.ErrorResponseException>`
        """
        multi_language_batch_input = None
        if documents is not None:
            multi_language_batch_input = models.MultiLanguageBatchInput(documents=documents)

        # Construct URL
        url = self.key_phrases.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if show_stats is not None:
            query_parameters['showStats'] = self._serialize.query("show_stats", show_stats, 'bool')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if multi_language_batch_input is not None:
            body_content = self._serialize.body(multi_language_batch_input, 'MultiLanguageBatchInput')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('KeyPhraseBatchResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    key_phrases.metadata = {'url': '/keyPhrases'}

    def sentiment(
            self, show_stats=None, documents=None, custom_headers=None, raw=False, **operation_config):
        """The API returns a numeric score between 0 and 1.

        Scores close to 1 indicate positive sentiment, while scores close to 0
        indicate negative sentiment. A score of 0.5 indicates the lack of
        sentiment (e.g. a factoid statement). See the <a
        href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
        Analytics Documentation</a> for details about the languages that are
        supported by sentiment analysis.

        :param show_stats: (optional) if set to true, response will contain
         input and document level statistics.
        :type show_stats: bool
        :param documents:
        :type documents:
         list[~azure.cognitiveservices.language.textanalytics.models.MultiLanguageInput]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: object or ClientRawResponse if raw=true
        :rtype: object or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        multi_language_batch_input = None
        if documents is not None:
            multi_language_batch_input = models.MultiLanguageBatchInput(documents=documents)

        # Construct URL
        url = self.sentiment.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if show_stats is not None:
            query_parameters['showStats'] = self._serialize.query("show_stats", show_stats, 'bool')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        if multi_language_batch_input is not None:
            body_content = self._serialize.body(multi_language_batch_input, 'MultiLanguageBatchInput')
        else:
            body_content = None

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 500]:
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('SentimentBatchResult', response)
        if response.status_code == 500:
            deserialized = self._deserialize('ErrorResponse', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    sentiment.metadata = {'url': '/sentiment'}